RediWM is a Wayland compositor written in Zig (OpenGL ES) that includes everything in one process
Tearing: per-frame fallback, borderless games, Settings toggle
oxydizera8c96d5bdb3a
diff --git a/docs/plans/vrr-tearing.md b/docs/plans/vrr-tearing.mdnew file mode 100644index 0000000..6ae76ab--- /dev/null+++ b/docs/plans/vrr-tearing.md@@ -0,0 +1,285 @@+# Plan: variable refresh rate and tearing for games++Status: 2026-11-17. D1–D5 decided (as proposed). P1 built (uncommitted);+P0 and P2–P4 not started.++Scope: adaptive sync (VRR: FreeSync, G-Sync Compatible, VESA Adaptive-Sync)+per DRM output, making the tearing support we already have reliable, and a+frame path that serves a fullscreen game on both. Out of scope: nested and+headless sessions (no VRR, and headless presents synchronously), HDR+(`hdr.md`), frame limiters (a client or MangoHud job), fifo-v1 and+commit-timing-v1 (not in installed wlroots 0.20; revisit when they land).++"VSync" itself is the client's choice: Vulkan FIFO, MAILBOX or IMMEDIATE, GL+swap interval. The compositor's part is to pace FIFO clients with frame+callbacks (it does), let VRR follow their frame rate, and honour the+tearing hint that IMMEDIATE sends.++## Where we are++**Tearing exists, as a global opt-in.**++* `[compositor] allow_tearing = false` (`config/default.zig:131`), with no+ Settings control.+* `extra_protocols.c` creates `wp_tearing_control_manager_v1`;+ `rediwm_protocols_tearing` reads a surface's hint.+* `Output.tearingAllowed` (`output/frame.zig:169`) allows it only for the+ keyboard-focused toplevel that is fullscreen, in the world, on this output,+ and has asked for `async`. It is never allowed while locked, during a polkit+ dialog or in the greeter.+* `commitFrameState` sets `state.tearing_page_flip`, tests the state and+ commits. `handleSurfaceCommit` → `queueTearing` renders from an idle+ callback as soon as the previous flip is done, so it does not wait for a+ frame event.+* **The gap: rejection is permanent.** One failed test or commit sets+ `output.tearing_rejected`, and nothing clears it until the compositor+ restarts. Atomic async flips may change only the primary plane's+ `FB_ID`, so any frame that also moves the hardware cursor, changes the+ colour transform (night light), or uses a buffer whose modifier the driver+ cannot flip asynchronously (i915 restricts these) fails. One cursor move+ in a game menu turns tearing off for the rest of the session, and nothing+ reports it.+* `late_render` already steps aside for tearing and VRR (`output/late.zig:33`).+* `tests/wlr_protocols.py` checks only that the global is advertised and+ takes a hint.++**Adaptive sync does not exist.** The bindings are there+(`wlr.Output.State.setAdaptiveSyncEnabled`, `adaptive_sync_supported`,+`adaptive_sync_status`), but nothing sets them. `OutputConfig` has no key for+it, `output_config.Patch` has no field, Settings → Display has no row, and+`output_management.zig` ignores a client's `adaptive_sync_enabled` (so+`wlr-randr --adaptive-sync on` does nothing).++**Direct scanout exists** (`scene_output.c:102`): one opaque surface covering+the whole output, unclipped, undimmed, at opacity 1, with matching colour+description. A fullscreen game is the case it was built for. The plan does not+change it, but it checks that games actually reach it (P0).++## Hardware facts (this machine)++* Laptop panel `eDP-1` is on the Intel GPU (card1) and reports+ `vrr_capable = 1` (`modetest -M i915 -c`). VRR can be tested locally.+* The NVIDIA GPU (card0) drives the HDMI/DP connectors, so an external+ G-Sync monitor goes through `nvidia-drm` (`modeset=Y`). Games on the+ laptop panel rendered on NVIDIA (PRIME offload) arrive as cross-GPU+ buffers that wlroots copies, so **they never scan out directly**. Tearing+ and VRR still work on the composited frame.+* Kernel 7.2, Xwayland 24.1.14. Xwayland has passed Present async flips on+ as `wp_tearing_control` hints since 23.2, so X11/Proton games go through the+ same path as native ones, provided `Toplevel.fromSurface` resolves the+ focused Xwayland surface (it should: `toplevel.surface()` covers X11).++## Design++### Adaptive sync: one mode per output++Per-output key `adaptive_sync = "off" | "auto" | "always"` in `[[output]]`+(see D1 for the default).++* **always**: requested on every enable and modeset. The desktop then runs+ at variable rate too. When nothing changes we commit nothing, so the panel+ falls to its minimum rate and returns to the maximum for an animation. Some+ panels flicker in brightness at that boundary, which is why this is not the+ default.+* **auto**: on while the output shows a *game-like* window (below), off+ otherwise. KDE's "Automatic" and Hyprland's `vrr = 2` do the same.+* **off**: never.++A window counts as game-like when it is the keyboard-focused toplevel on this+output, in the world, not minimized or tab-hidden, and either fullscreen or+(D3) an undecorated window that exactly covers the output, the+"borderless windowed" mode many games default to. The same predicate replaces+the fullscreen test in `tearingAllowed`, so VRR, tearing and their reporting+agree on one rule. It moves to its own `output/game.zig` so both callers use+it.++**Applying.** A pure function `vrr.wanted(mode, supported, game_like,+locked, greeter)` → bool, tested in `vrr_tests.zig` like+`late_render_tests.zig`. The output re-evaluates it on focus change,+fullscreen enter/exit, workspace switch end, window move between outputs,+lock/unlock and config reload. It does **not** do this on every commit. When+the wanted state differs from `adaptive_sync_status`, it puts the change on+the next frame's state (`buildOutputState`), not on a separate commit, so it+rides a normal page flip.++* **Turning off is debounced** (about 500 ms). Alt-tabbing to a chat window+ and back should not toggle twice. Turning on is immediate.+* **A change that needs a modeset is not made automatically.** wlroots+ allows a modeset only when the state changes the mode or enablement, so a+ driver that cannot toggle `VRR_ENABLED` seamlessly fails `testState`. In+ that case `auto` marks the output as needing a modeset for VRR, keeps the+ current state, and Settings says so. `always` and `off` still work, because+ they are applied at a modeset anyway. P0 finds out which side i915 and+ nvidia-drm are on.+* An enabled request that comes back `.disabled` (unsupported panel, or a+ driver refusal) is remembered per mode, as night light's colour transform+ is, and logged once.++**Plumbing.**++* `OutputConfig.adaptive_sync` and its loader field.+* A `Patch.adaptive_sync` field, applied in `applyAndPersist` and persisted+ like `transform`.+* `output_management.zig`: when a client sets `adaptive_sync_enabled`,+ `diff` maps it to `always` or `off`, and the head reports the real+ status back.+* Hotplug and mode restore apply the saved mode.++### Tearing: per-frame fallback instead of a permanent flag++* Drop the sticky `tearing_rejected`. A failed async test makes **this+ frame** synchronous, nothing more. Count consecutive failures. After about+ 30 in a row (a buffer the driver will never flip asynchronously), pause+ async attempts on that output for a few seconds with backoff, and log the+ reason once per pause. Late render's missed-deadline backoff works the+ same way. Each failed test costs an extra atomic test commit, which is why+ it should not repeat forever.+* Classify the cheap cases before testing. If the frame's state has a+ committed colour transform, a mode change, or a cursor plane change, go+ synchronous without spending a test. Getting the cursor information depends+ on what `wlr_output_state` exposes: check in P0.+* Optional, if P0 shows cursor moves are the common failure: while tearing+ is active, hold a cursor-only change for the next client commit. Games+ commit at hundreds of fps, so the delay is under a frame. A cursor still+ hidden gets its update within one refresh period, from the vblank timer.+* VRR and tearing combine. With both on, frames under the maximum refresh+ arrive whole at a variable rate, and only frames above it tear. That is+ what "G-Sync + uncapped" players expect. Nothing here makes one exclude+ the other (D4).++### Frame pacing under VRR++Most of the path is already right. A fullscreen client commit schedules a+frame, the frame event fires at once if no flip is pending, and the frame+callbacks go out after the flip, so a FIFO game runs at its own rate up to+the maximum refresh, and the panel follows. Three things to check and, if+needed, fix:++1. **Cursor-only commits.** A moving hardware cursor makes us commit at+ pointer rate. Under VRR each commit starts a refresh early, so a 40 fps+ game with a moving cursor stutters. Mutter throttles cursor updates+ under VRR. Here, while VRR is active on the output with a game-like+ window, a cursor-only change waits for the next content frame or at most+ one minimum-refresh period (the panel's lowest rate, from EDID through+ wlroots if exposed, else 1/48 s).+2. **Compositor animations over a game** (OSD, notifications, the dock+ revealing) drive commits at the maximum rate while they run. That is fine:+ they are short and the game is composited behind them. They must not+ leave something ticking afterwards. The panel-tick edge-trigger rule+ already covers this; verify with the frame trace.+3. **`deferFrameDone` and the vblank timer** estimate the next vblank from+ `refresh` (the maximum). Under VRR that is the earliest possible next+ flip, which is the right pace for callback-only commits. No change+ expected; confirm in the trace.++### Reporting++* IPC `outputs`: an `adaptive_sync` object with `mode`, `supported`,+ `wanted` and `active` (the wlroots status), plus `needs_modeset`.+ Tearing gets `allowed` (the policy), `active` (the last flip was async)+ and `paused_reason`. A `direct_scanout` bool is added too. The policy+ fields work headless, which is what makes integration tests possible+ there.+* `ipc/stats.zig`: `async_flips`, `async_fallbacks`, `vrr_toggles`.+* Frame trace (`output/frame_trace.zig`): tag each committed frame as+ sync/async and scanout/composited, so a DRM run can show present intervals+ following the game.++### Settings → Display++* Per output: a **Variable refresh rate** select (Off / Automatic / Always),+ disabled and labelled "Not supported by this display" when+ `adaptive_sync_supported` is false. When `needs_modeset` is set it adds a+ note that Automatic needs the display to switch modes, so Always or Off is+ recommended. The new row goes through a new `row_*` slot constant and+ `layout.appendRow`, never a raw index.+* Global, below the outputs: an **Allow tearing in fullscreen games**+ toggle for `allow_tearing`, with one line explaining that games must ask+ for it (their "VSync off" or "Immediate" setting).++## Phases++**P0 facts (on the laptop's VT; nothing committed).** Record each in this+plan.++* Does i915 toggle `VRR_ENABLED` on eDP-1 without a modeset? Test with a+ scratch build that flips it in `buildOutputState` and checks `testState`;+ read the property back with `modetest -p`.+* Does an async flip pass on i915 for our composited swapchain buffer, and+ for a scanned-out client buffer (`vkcube --present_mode 0` on Intel)?+* What fails while the cursor moves? Can `wlr_output_state` tell us a frame+ carries a cursor change?+* Is a Proton or Xwayland game (`vblank_mode=0 glxgears` fullscreen, a Steam+ title) recognised by `tearingAllowed`, and does it get its hint through?+* Does a fullscreen native game reach direct scanout (`Direct scan-out+ enabled` in the debug log), and on NVIDIA offload confirm that it doesn't?+* If an external VRR monitor is at hand: run the same checks on+ nvidia-drm.++**P1 tearing that stays on.**++* Per-frame fallback with backoff, the pre-test classification, the+ `output/game.zig` predicate (with D3), the IPC/stats fields and the+ Settings toggle.+* Tests: `tests/wlr_protocols.py` grows a case in which a fullscreen fixture+ with the async hint makes IPC report `allowed = true`, and unfocusing or+ leaving fullscreen makes it false. A unit test checks that the fallback+ counter pauses and resumes.++**P2 adaptive sync.**++* Config key, Patch, `applyAndPersist`, output-management mapping,+ `vrr.zig` policy + `vrr_tests.zig`, application on the frame state,+ debounce, modeset detection, and the Settings row.+* Tests: unit tests for the policy and debounce. A headless integration case+ checks that `wanted` follows fullscreen in `auto` while `supported` stays+ false, and that `wlr-randr`-style output management persists the mode.++**P3 pacing under VRR.**++* Cursor throttle, the frame-trace tags, then a DRM run: vkcube at a+ 45 fps cap fullscreen on eDP-1 with `auto`, with the trace showing ~22 ms+ present intervals and `active = true`; idle desktop back at fixed rate after+ the debounce. Add the run as a mode of `tests/frame_latency.py` (DRM only,+ like late render's engaged path).++**P4 docs.** Add a short section to `docs/agent-notes/rendering.md`+(predicate, fallback, where VRR is applied), add the config keys to+`config/default.zig`, and check translations for the new Settings+strings.++Each phase ends with the usual gates: Debug and ReleaseSafe builds, `zig+build test`, `tests/wlr_protocols.py`, `tests/greeter.py` (the greeter must+never toggle VRR or tear), and the display Settings suite. Compare failures+with a HEAD worktree.++## Decisions (taken 2026-11-17, all as proposed)++* **D1 Default mode:** `auto` where VRR is supported, falling back to `off`+ on a driver P0 shows needs a modeset to toggle.+* **D2 Per-app overrides:** none in P1; a `tearing` window rule only if a real+ game needs it.+* **D3 Borderless windowed counts as fullscreen:** yes, an undecorated window+ the client placed (not maximized or tiled) whose frame is exactly the+ output (`output/game.zig`).+* **D4 VRR + tearing together:** yes, no exclusion option.+* **D5 Cursor throttle under VRR:** P3, only if measured stutter.++## P1 as built++* `output/tearing_policy.zig`: the backoff model and its tests (30 refusals+ in a row pause attempts 2 s, doubling to 30 s; a success resets).+* `output/tearing.zig`: `wanted` (policy), `allowed` (minus a pause),+ `frameCanTear` (skips the test commit when the frame changes mode, scale,+ transform, adaptive sync, format, colour transform, image description or+ the hardware cursor), `refused`/`committed`, and the idle `queue` moved from+ `frame.zig`. `Output.tearing_rejected` is gone.+* `output/game.zig`: the game-window predicate (D3).+* IPC: `outputs` gains `tearing_allowed`, `tearing_active`, `tearing_paused`,+ `direct_scanout`; performance stats gain `tearing_async_flips` and+ `tearing_refused_flips`.+* Settings → Displays: an "Allow tearing in games" card; search entry.+* `tests/wlr_protocols.py` checks `tearing_allowed` follows the hint on the+ focused fullscreen window.+* Not verified on DRM yet: that needs P0's run on the VT (does i915 take the+ composited buffer asynchronously, how often the cursor check fires).diff --git a/po/de.po b/po/de.poindex 526d51c..16746b9 100644--- a/po/de.po+++ b/po/de.po@@ -284,6 +284,11 @@ msgstr "Verbindungen dieses Geräts ohne Rückfrage zulassen."msgid "Allow pairing with this device?"msgstr "Kopplung mit diesem Gerät erlauben?"+#: src/control_center/search_index.zig+#: src/control_center/sections/display.zig+msgid "Allow tearing in games"+msgstr "Tearing in Spielen erlauben"+#: src/files/app_places.zigmsgid "Already in Places"msgstr "Bereits in Orten"@@ -2728,6 +2733,10 @@ msgstr "Volle Kapazität"msgid "Full name"msgstr "Vollständiger Name"+#: src/control_center/sections/display.zig+msgid "Fullscreen games with VSync off show new frames at once; the picture may tear"+msgstr "Vollbildspiele ohne VSync zeigen neue Bilder sofort; das Bild kann reißen"+#: src/taskbar/battery.zigmsgid "Fully Charged"msgstr "Vollständig geladen"@@ -7226,6 +7235,10 @@ msgstr "unfokussiert dunkelheit"msgid "users login password administrator groups"msgstr "benutzer anmeldung passwort administrator gruppen"+#: src/control_center/search_index.zig+msgid "vsync latency fullscreen game immediate"+msgstr "vsync latenz vollbild spiel sofort"+#: src/control_center/search_index.zigmsgid "warmth colour color"msgstr "wärme farbe"diff --git a/po/es.po b/po/es.poindex a99953d..02d087f 100644--- a/po/es.po+++ b/po/es.po@@ -281,6 +281,11 @@ msgstr "Permitir conexiones de este dispositivo sin preguntar."msgid "Allow pairing with this device?"msgstr "¿Permitir el emparejamiento con este dispositivo?"+#: src/control_center/search_index.zig+#: src/control_center/sections/display.zig+msgid "Allow tearing in games"+msgstr "Permitir tearing en juegos"+#: src/files/app_places.zigmsgid "Already in Places"msgstr "Ya está en Lugares"@@ -2725,6 +2730,10 @@ msgstr "Capacidad total"msgid "Full name"msgstr "Nombre completo"+#: src/control_center/sections/display.zig+msgid "Fullscreen games with VSync off show new frames at once; the picture may tear"+msgstr "Los juegos a pantalla completa sin VSync muestran cada fotograma al instante; la imagen puede cortarse"+#: src/taskbar/battery.zigmsgid "Fully Charged"msgstr "Carga completa"@@ -7223,6 +7232,10 @@ msgstr "oscurecimiento sin foco"msgid "users login password administrator groups"msgstr "usuarios inicio sesión contraseña administrador grupos"+#: src/control_center/search_index.zig+msgid "vsync latency fullscreen game immediate"+msgstr "vsync latencia pantalla completa juego inmediato"+#: src/control_center/search_index.zigmsgid "warmth colour color"msgstr "calidez color"diff --git a/po/fr.po b/po/fr.poindex cb3449f..6ac21bb 100644--- a/po/fr.po+++ b/po/fr.po@@ -284,6 +284,11 @@ msgstr "Autoriser les connexions de cet appareil sans confirmation."msgid "Allow pairing with this device?"msgstr "Autoriser l'association avec cet appareil ?"+#: src/control_center/search_index.zig+#: src/control_center/sections/display.zig+msgid "Allow tearing in games"+msgstr "Autoriser le tearing dans les jeux"+#: src/files/app_places.zigmsgid "Already in Places"msgstr "Déjà dans les emplacements"@@ -2728,6 +2733,10 @@ msgstr "Capacité totale"msgid "Full name"msgstr "Nom complet"+#: src/control_center/sections/display.zig+msgid "Fullscreen games with VSync off show new frames at once; the picture may tear"+msgstr "Les jeux en plein écran sans VSync affichent chaque image aussitôt ; l’image peut se déchirer"+#: src/taskbar/battery.zigmsgid "Fully Charged"msgstr "Charge complète"@@ -7226,6 +7235,10 @@ msgstr "inactif assombrissement"msgid "users login password administrator groups"msgstr "utilisateurs connexion mot de passe administrateur groupes"+#: src/control_center/search_index.zig+msgid "vsync latency fullscreen game immediate"+msgstr "vsync latence plein écran jeu immédiat"+#: src/control_center/search_index.zigmsgid "warmth colour color"msgstr "chaleur couleur"diff --git a/po/pt_BR.po b/po/pt_BR.poindex 3b2639b..3f31199 100644--- a/po/pt_BR.po+++ b/po/pt_BR.po@@ -281,6 +281,11 @@ msgstr "Permitir conexões deste dispositivo sem perguntar."msgid "Allow pairing with this device?"msgstr "Permitir o pareamento com este dispositivo?"+#: src/control_center/search_index.zig+#: src/control_center/sections/display.zig+msgid "Allow tearing in games"+msgstr "Permitir tearing em jogos"+#: src/files/app_places.zigmsgid "Already in Places"msgstr "Já está em Locais"@@ -2725,6 +2730,10 @@ msgstr "Capacidade total"msgid "Full name"msgstr "Nome completo"+#: src/control_center/sections/display.zig+msgid "Fullscreen games with VSync off show new frames at once; the picture may tear"+msgstr "Jogos em tela cheia sem VSync mostram cada quadro na hora; a imagem pode rasgar"+#: src/taskbar/battery.zigmsgid "Fully Charged"msgstr "Carga completa"@@ -7223,6 +7232,10 @@ msgstr "escurecimento sem foco"msgid "users login password administrator groups"msgstr "usuários login senha administrador grupos"+#: src/control_center/search_index.zig+msgid "vsync latency fullscreen game immediate"+msgstr "vsync latência tela cheia jogo imediato"+#: src/control_center/search_index.zigmsgid "warmth colour color"msgstr "calor cor cores"diff --git a/po/rediwm.pot b/po/rediwm.potindex dc35d03..4559f0c 100644--- a/po/rediwm.pot+++ b/po/rediwm.pot@@ -323,6 +323,11 @@ msgstr ""msgid "Allow pairing with this device?"msgstr ""+#: src/control_center/search_index.zig+#: src/control_center/sections/display.zig+msgid "Allow tearing in games"+msgstr ""+#: src/files/app_places.zigmsgid "Already in Places"msgstr ""@@ -3228,6 +3233,10 @@ msgstr ""msgid "Full name"msgstr ""+#: src/control_center/sections/display.zig+msgid "Fullscreen games with VSync off show new frames at once; the picture may tear"+msgstr ""+#: src/taskbar/battery.zigmsgid "Fully Charged"msgstr ""@@ -8551,6 +8560,10 @@ msgstr ""msgid "users login password administrator groups"msgstr ""+#: src/control_center/search_index.zig+msgid "vsync latency fullscreen game immediate"+msgstr ""+#: src/control_center/search_index.zigmsgid "warmth colour color"msgstr ""diff --git a/po/ru.po b/po/ru.poindex 1484e3a..bee006b 100644--- a/po/ru.po+++ b/po/ru.po@@ -284,6 +284,11 @@ msgstr "Разрешить подключения с этого устройстmsgid "Allow pairing with this device?"msgstr "Разрешить сопряжение с этим устройством?"+#: src/control_center/search_index.zig+#: src/control_center/sections/display.zig+msgid "Allow tearing in games"+msgstr "Разрешить разрывы изображения в играх"+#: src/files/app_places.zigmsgid "Already in Places"msgstr "Уже есть в «Местах»"@@ -2730,6 +2735,10 @@ msgstr "Полная ёмкость"msgid "Full name"msgstr "Полное имя"+#: src/control_center/sections/display.zig+msgid "Fullscreen games with VSync off show new frames at once; the picture may tear"+msgstr "Полноэкранные игры без VSync показывают кадры сразу; изображение может разрываться"+#: src/taskbar/battery.zigmsgid "Fully Charged"msgstr "Полностью заряжено"@@ -7229,6 +7238,10 @@ msgstr "затемнение неактивных окон"msgid "users login password administrator groups"msgstr "пользователи вход пароль администратор группы"+#: src/control_center/search_index.zig+msgid "vsync latency fullscreen game immediate"+msgstr "vsync задержка полноэкранный игра немедленно"+#: src/control_center/search_index.zigmsgid "warmth colour color"msgstr "теплота цвет"diff --git a/src/Output.zig b/src/Output.zigindex 0a61880..8f83d65 100644--- a/src/Output.zig+++ b/src/Output.zig@@ -20,6 +20,7 @@ const output_panels = @import("output/panels.zig");const output_wallpaper = @import("output/wallpaper.zig");const output_frame = @import("output/frame.zig");const output_late = @import("output/late.zig");+const output_tearing = @import("output/tearing.zig");pub const wlr_color_transform_init_lut_3x1d = wlr.color.transformInitLut3x1d;pub const wlr_color_transform_unref = wlr.color.transformUnref;@@ -112,8 +113,8 @@ late_animating: bool = false,/// callbacks need a frame (`frameCallbacksWanted`).callback_idle: ?*wl.EventSource = null,callback_frame_seq: u64 = 0,-tearing_idle: ?*wl.EventSource = null,-tearing_rejected: bool = false,+/// Asynchronous page flips for a game window (`output/tearing.zig`).+tearing: output_tearing.State = .{},/// An ext-session-lock client waits for this output to commit a locked frame.lock_commit_pending: bool = false,/// Hardware cursor state as of the last commit. Atomic DRM applies cursor@@ -480,9 +481,6 @@ pub const deferFrameDone = output_frame.deferFrameDone;pub const handleVblank = output_frame.handleVblank;pub const frameCallbacksWanted = output_frame.frameCallbacksWanted;pub const sendFrameDone = output_frame.sendFrameDone;-pub const tearingAllowed = output_frame.tearingAllowed;-pub const queueTearing = output_frame.queueTearing;-pub const tearingIdle = output_frame.tearingIdle;pub const handleFrame = output_frame.handleFrame;pub const runFrame = output_frame.runFrame;pub const setDisplayMode = output_frame.setDisplayMode;@@ -493,6 +491,10 @@ pub const startupVisible = output_frame.startupVisible;// output/late.zigpub const lateFire = output_late.fire;+// output/tearing.zig+pub const tearingAllowed = output_tearing.allowed;+pub const queueTearing = output_tearing.queue;+pub const CursorState = struct {cursor: ?*wlr.OutputCursor = null,buffer: ?*wlr.Buffer = null,@@ -521,8 +523,7 @@ pub const CursorState = struct {pub fn handleDestroy(listener: *wl.Listener(*wlr.Output), _: *wlr.Output) void {const output: *Output = @fieldParentPtr("destroy", listener);output.server.world.overview.cancel(&output.server.world);- if (output.tearing_idle) |source| source.remove();- output.tearing_idle = null;+ output_tearing.deinit(output);if (output.server.screenshot_selector.output == output) output.server.screenshot_selector.cancel();if (output.server.screenshot_mgr) |mgr| mgr.cancelForOutput(output);const server = output.server;diff --git a/src/config/default.zig b/src/config/default.zigindex 35f31de..be25ef0 100644--- a/src/config/default.zig+++ b/src/config/default.zig@@ -127,7 +127,8 @@ pub const source =\\# Workspace shortcuts are overridden separately in [keybinds.workspace].\\desktop_mode = "canvas"\\floating_apps = [] # app ID glob patterns that float in workspaces- \\# Allow fullscreen clients to request asynchronous presentation (may tear).+ \\# Let a fullscreen or borderless game that asks for it (VSync off) show+ \\# frames at once instead of at the next refresh. The picture may tear.\\allow_tearing = false\\# Render as late as the display allows, so input made just before a refresh\\# still reaches it. Only displays that report presentation times qualifydiff --git a/src/control_center/search_index.zig b/src/control_center/search_index.zigindex e68ccac..163f098 100644--- a/src/control_center/search_index.zig+++ b/src/control_center/search_index.zig@@ -71,6 +71,7 @@ const source_entries = [_]SourceEntry{.{ .page = .displays, .title = i18n.msg("Refresh rate"), .target = "refresh_rate", .keywords = i18n.msg("screen frequency hz") },.{ .page = .displays, .title = i18n.msg("Display scale"), .target = "scale", .keywords = i18n.msg("screen scaling dpi zoom") },.{ .page = .displays, .title = i18n.msg("Xwayland scale"), .target = "xwayland_scale", .keywords = i18n.msg("x11 legacy apps scaling") },+ .{ .page = .displays, .title = i18n.msg("Allow tearing in games"), .target = "allow_tearing", .keywords = i18n.msg("vsync latency fullscreen game immediate") },.{ .page = .displays, .title = i18n.msg("Rotation"), .target = "transform", .keywords = i18n.msg("orientation portrait landscape screen") },.{ .page = .displays, .title = i18n.msg("Night light"), .target = "night_light", .keywords = i18n.msg("blue light warm screen") },.{ .page = .displays, .title = i18n.msg("Night light temperature"), .target = "night_light_temperature", .keywords = i18n.msg("warmth colour color") },diff --git a/src/control_center/sections/display.zig b/src/control_center/sections/display.zigindex 500a593..2d70387 100644--- a/src/control_center/sections/display.zig+++ b/src/control_center/sections/display.zig@@ -78,6 +78,8 @@ pub const Section = struct {nl_temp_value_buf: [16]u8 = undefined,nl_temp_slider: Widget = undefined,nl_group_children: [3]Widget = undefined,+ tearing_label_children: [2]Widget = undefined,+ tearing_group_children: [2]Widget = undefined,/// Shown only on machines with a lid switch.has_lid: bool = false,initial_lid: ?usize = null,@@ -188,6 +190,7 @@ pub fn build(out: *Section, cc: *panel.ControlCenter, wlr_output: *wlr.Output) v};out.root = .{ .kind = .container, .direction = .column, .gap = 8, .children = &out.top_children };buildNightLight(out);+ buildTearing(out);buildLid(out);buildArrangement(out, name);}@@ -510,6 +513,31 @@ fn buildNightLight(out: *Section) void {};}+fn buildTearing(out: *Section) void {+ const t = panel.palette();+ out.tearing_label_children = .{+ .{ .kind = .{ .text = .{ .content = i18n.tr("Allow tearing in games"), .font_size = 13, .weight = 600, .color = t.fg } } },+ .{ .kind = .{ .text = .{ .content = i18n.tr("Fullscreen games with VSync off show new frames at once; the picture may tear"), .font_size = 12, .color = t.dim } } },+ };+ out.tearing_group_children = .{+ .{ .kind = .container, .direction = .column, .gap = 2, .width = .{ .flex = 1 }, .children = &out.tearing_label_children },+ .{ .name = "allow_tearing", .kind = .{ .toggle = .{ .style = .settings, .on = out.cc.server.config.compositor.allow_tearing, .owner = out, .on_change = &onTearingToggled } } },+ };+}++fn onTearingToggled(owner: ?*anyopaque, _: usize, on: bool) void {+ const out = section(owner);+ const server = out.cc.server;+ if (server.config.compositor.allow_tearing == on) return;+ setting_save.saveCompositor(main.gpa, server.io, server.config.path, "allow_tearing", on) catch |err| {+ std.log.warn("could not save allow_tearing: {}", .{err});+ out.tearing_group_children[1].kind.toggle.on = server.config.compositor.allow_tearing;+ out.tearing_group_children[1].markDirty();+ return;+ };+ server.config.compositor.allow_tearing = on;+}+fn onNightLightToggled(owner: ?*anyopaque, _: usize, on: bool) void {const server = section(owner).cc.server;if (server.config.night_light.enabled == on) return;diff --git a/src/control_center/tree.zig b/src/control_center/tree.zigindex ba95fce..159586b 100644--- a/src/control_center/tree.zig+++ b/src/control_center/tree.zig@@ -218,6 +218,12 @@ pub fn buildTree(cc: *ControlCenter) void {var nl_card = card(&cc.display.nl_group_children);nl_card.name = "displays";cc.append(nl_card);+ var tearing_card = card(&cc.display.tearing_group_children);+ tearing_card.name = "displays";+ tearing_card.direction = .row;+ tearing_card.justify = .space_between;+ tearing_card.@"align" = .center;+ cc.append(tearing_card);cc.append(.{ .name = "power_settings_link", .kind = .{ .button = .{ .label = i18n.tr("Power and lid settings"), .owner = cc, .id = @backingInt(Page.power), .on_click = pageClicked } }, .height = .{ .fixed = 36 } });},.audio => {diff --git a/src/ipc/handlers_data.zig b/src/ipc/handlers_data.zigindex 182deda..3b765d2 100644--- a/src/ipc/handlers_data.zig+++ b/src/ipc/handlers_data.zig@@ -5,6 +5,8 @@ const wlr = @import("wlroots");const Server = @import("../Server.zig");const Output = @import("../Output.zig");const Toplevel = @import("../Toplevel.zig");+const output_tearing = @import("../output/tearing.zig");+const stats = @import("stats.zig");const protocol = @import("protocol.zig");const ui = @import("ui");const controlCenterState = @import("handlers_panels.zig").controlCenterState;@@ -194,6 +196,10 @@ pub fn makeOutputData(server: *Server, output: *Output) protocol.OutputData {.scale = output.wlr_output.scale,.refresh_hz = refresh_hz,.is_focused = is_focused,+ .tearing_allowed = output_tearing.wanted(output),+ .tearing_active = output.tearing.active,+ .tearing_paused = output.tearing.backoff.paused_until_ns != 0 and output.tearing.backoff.paused(stats.nowNs()),+ .direct_scanout = if (server.scene_outputs.get(output.wlr_output)) |scene_output| scene_output.directScanout() else false,};}diff --git a/src/ipc/handlers_frames.zig b/src/ipc/handlers_frames.zigindex fb41a16..48ce739 100644--- a/src/ipc/handlers_frames.zig+++ b/src/ipc/handlers_frames.zig@@ -184,6 +184,8 @@ pub fn handleFrameAction(.desktop = stats.global_stats.desktop,.output_skipped_commits = stats.global_stats.output_skipped_commits,.glass_reblurs = @import("../scene_output.zig").reblurs.*,+ .tearing_async_flips = stats.global_stats.tearing_async_flips,+ .tearing_refused_flips = stats.global_stats.tearing_refused_flips,} } };},.reset_performance_stats => {diff --git a/src/ipc/protocol_data.zig b/src/ipc/protocol_data.zigindex 1214d8c..84fb4ac 100644--- a/src/ipc/protocol_data.zig+++ b/src/ipc/protocol_data.zig@@ -171,6 +171,14 @@ pub const OutputData = struct {scale: f32,refresh_hz: f32,is_focused: bool,+ /// A game window here asks to tear and `allow_tearing` permits it.+ tearing_allowed: bool = false,+ /// The last committed buffer was flipped asynchronously.+ tearing_active: bool = false,+ /// Asynchronous flips are paused after a run of driver refusals.+ tearing_paused: bool = false,+ /// The last frame scanned a client buffer out directly.+ direct_scanout: bool = false,};pub const WorkspaceData = struct {diff --git a/src/ipc/protocol_results.zig b/src/ipc/protocol_results.zigindex 561f536..7d26557 100644--- a/src/ipc/protocol_results.zig+++ b/src/ipc/protocol_results.zig@@ -158,6 +158,9 @@ pub const PerformanceStatsResult = struct {output_skipped_commits: ?u64 = null,/// Glass blurs re-taken by the output pass (stage 5c), all outputs.glass_reblurs: ?u64 = null,+ /// Asynchronous (tearing) flips, and those the driver refused, all outputs.+ tearing_async_flips: ?u64 = null,+ tearing_refused_flips: ?u64 = null,};/// The compositor-drawn desktop's repaint work since the last reset.diff --git a/src/ipc/protocol_stringify.zig b/src/ipc/protocol_stringify.zigindex 9d2130f..2855a09 100644--- a/src/ipc/protocol_stringify.zig+++ b/src/ipc/protocol_stringify.zig@@ -541,6 +541,12 @@ pub fn stringifyPerformanceStats(res: PerformanceStatsResult, writer: anytype) !if (res.glass_reblurs) |reblurs| {try writer.print("\"glass_reblurs\":{d},", .{reblurs});}+ if (res.tearing_async_flips) |flips| {+ try writer.print("\"tearing_async_flips\":{d},", .{flips});+ }+ if (res.tearing_refused_flips) |flips| {+ try writer.print("\"tearing_refused_flips\":{d},", .{flips});+ }try writer.print("\"output_commits\":{d},\"output_failed_commits\":{d},\"fps\":{d:.1},\"frame_time_ms\":{d:.1},\"missed_frames\":{d},\"refresh_hz\":{d:.1},\"titlebar_paints\":{d},\"footer_paints\":{d},\"edge_samples_attempted\":{d},\"edge_samples_succeeded\":{d},\"edge_samples_skipped\":{d},\"edge_sample_ns\":{d},\"panel_paints\":{d},\"panel_allocated_bytes\":{d},\"panel_reused_bytes\":{d},\"icon_cache_hits\":{d},\"icon_cache_misses\":{d},\"icon_decode_ns\":{d},\"icon_decode_count\":{d},\"icon_decoded_bytes\":{d},\"icon_queue_depth_max\":{d},", .{res.output_commits,res.output_failed_commits,@@ -869,6 +875,7 @@ pub fn stringifyOutput(out: OutputData, writer: anytype) !void {try writer.print(",\"bottom_exclusion\":{d}", .{out.bottom_exclusion});try writer.print(",\"scale\":{d},\"refresh_hz\":{d},\"is_focused\":", .{ out.scale, out.refresh_hz });try writer.writeAll(if (out.is_focused) "true" else "false");+ try writer.print(",\"tearing_allowed\":{},\"tearing_active\":{},\"tearing_paused\":{},\"direct_scanout\":{}", .{ out.tearing_allowed, out.tearing_active, out.tearing_paused, out.direct_scanout });try writer.writeByte('}');}diff --git a/src/ipc/stats.zig b/src/ipc/stats.zigindex 16e7380..32d2870 100644--- a/src/ipc/stats.zig+++ b/src/ipc/stats.zig@@ -37,6 +37,9 @@ pub const PerformanceStats = struct {output_failed_commits: u64 = 0,/// Frames whose output commit was skipped because nothing on screen changed.output_skipped_commits: u64 = 0,+ /// Buffers flipped asynchronously (tearing), and async flips the driver refused.+ tearing_async_flips: u64 = 0,+ tearing_refused_flips: u64 = 0,titlebar_paints: u64 = 0,// Always 0 since the window shapes (no footer raster, no edge sample); kept// so the PerformanceStats wire format and its readers stay unchanged.@@ -109,6 +112,8 @@ pub const PerformanceStats = struct {self.output_commits = 0;self.output_failed_commits = 0;self.output_skipped_commits = 0;+ self.tearing_async_flips = 0;+ self.tearing_refused_flips = 0;self.titlebar_paints = 0;self.footer_paints = 0;self.edge_samples_attempted = 0;diff --git a/src/ipc_serializers.jsonl b/src/ipc_serializers.jsonlindex d673eef..eae7365 100644--- a/src/ipc_serializers.jsonl+++ b/src/ipc_serializers.jsonl@@ -24,8 +24,8 @@{"Ok":{"DescribeIPC":{"protocol_version":"text \"quoted\"\n\\","build_version":"text \"quoted\"\n\\","backend":"text \"quoted\"\n\\","renderer":"text \"quoted\"\n\\","commands":[{"name":"text \"quoted\"\n\\","kind":"text \"quoted\"\n\\","description":"text \"quoted\"\n\\","params_schema":"text \"quoted\"\n\\","units":"text \"quoted\"\n\\"}],"unavailable_reasons":["text \"quoted\"\n\\"]}}}{"Ok":{"Windows":[{"id":0,"title":null,"app_id":null,"sandbox":null,"pid":null,"is_focused":false,"is_minimized":false,"is_maximized":false,"workspace_id":null,"x":0,"y":0,"width":0,"height":0,"zoom_percent":0,"backend":"text \"quoted\"\n\\","x11_class":null,"x11_instance":null,"is_urgent":false,"workspace_order":0,"placement":"text \"quoted\"\n\\","floating_override":null}]}}{"Ok":{"Windows":[{"id":7,"title":"text \"quoted\"\n\\","app_id":"text \"quoted\"\n\\","sandbox":{"engine":"text \"quoted\"\n\\","app_id":"text \"quoted\"\n\\","instance_id":"text \"quoted\"\n\\"},"pid":7,"is_focused":true,"is_minimized":true,"is_maximized":true,"workspace_id":7,"x":7,"y":7,"width":7,"height":7,"zoom_percent":7,"backend":"text \"quoted\"\n\\","x11_class":"text \"quoted\"\n\\","x11_instance":"text \"quoted\"\n\\","is_urgent":true,"workspace_order":7,"placement":"text \"quoted\"\n\\","floating_override":true}]}}-{"Ok":{"Outputs":[{"name":"text \"quoted\"\n\\","make":null,"model":null,"enabled":false,"x":0,"y":0,"logical_width":0,"logical_height":0,"buffer_width":0,"buffer_height":0,"transform":"text \"quoted\"\n\\","bottom_exclusion":0,"scale":0,"refresh_hz":0,"is_focused":false}]}}-{"Ok":{"Outputs":[{"name":"text \"quoted\"\n\\","make":"text \"quoted\"\n\\","model":"text \"quoted\"\n\\","enabled":true,"x":7,"y":7,"logical_width":7,"logical_height":7,"buffer_width":7,"buffer_height":7,"transform":"text \"quoted\"\n\\","bottom_exclusion":7,"scale":1.23456,"refresh_hz":1.23456,"is_focused":true}]}}+{"Ok":{"Outputs":[{"name":"text \"quoted\"\n\\","make":null,"model":null,"enabled":false,"x":0,"y":0,"logical_width":0,"logical_height":0,"buffer_width":0,"buffer_height":0,"transform":"text \"quoted\"\n\\","bottom_exclusion":0,"scale":0,"refresh_hz":0,"is_focused":false,"tearing_allowed":false,"tearing_active":false,"tearing_paused":false,"direct_scanout":false}]}}+{"Ok":{"Outputs":[{"name":"text \"quoted\"\n\\","make":"text \"quoted\"\n\\","model":"text \"quoted\"\n\\","enabled":true,"x":7,"y":7,"logical_width":7,"logical_height":7,"buffer_width":7,"buffer_height":7,"transform":"text \"quoted\"\n\\","bottom_exclusion":7,"scale":1.23456,"refresh_hz":1.23456,"is_focused":true,"tearing_allowed":true,"tearing_active":true,"tearing_paused":true,"direct_scanout":true}]}}{"Ok":{"FocusedWindow":null}}{"Ok":{"FocusedWindow":{"id":7,"title":"text \"quoted\"\n\\","app_id":"text \"quoted\"\n\\","sandbox":{"engine":"text \"quoted\"\n\\","app_id":"text \"quoted\"\n\\","instance_id":"text \"quoted\"\n\\"},"pid":7,"is_focused":true,"is_minimized":true,"is_maximized":true,"workspace_id":7,"x":7,"y":7,"width":7,"height":7,"zoom_percent":7,"backend":"text \"quoted\"\n\\","x11_class":"text \"quoted\"\n\\","x11_instance":"text \"quoted\"\n\\","is_urgent":true,"workspace_order":7,"placement":"text \"quoted\"\n\\","floating_override":true}}}{"Ok":{"Workspaces":[{"id":0,"name":null,"is_focused":false,"is_visible":false,"output":null,"automatic":false,"window_gap":0,"nodes":[{"id":null,"group":false,"axis":"horizontal","ratio":0}]}]}}@@ -38,8 +38,8 @@{"Ok":{"AudioState":{"master_volume":1.23456,"master_muted":true,"default_sink":"text \"quoted\"\n\\","streams":[{"index":7,"name":"text \"quoted\"\n\\","app_id":"text \"quoted\"\n\\","pid":7,"volume":1.23456,"muted":true}]}}}{"Ok":{"PanelStats":{"paints":0,"allocated_bytes":0,"reused_bytes":0,"paint_ns":0}}}{"Ok":{"PanelStats":{"paints":7,"allocated_bytes":7,"reused_bytes":7,"paint_ns":7}}}-{"Ok":{"State":{"seq":0,"session_id":"text \"quoted\"\n\\","focused_window_id":null,"windows":[{"id":0,"title":null,"app_id":null,"sandbox":null,"pid":null,"is_focused":false,"is_minimized":false,"is_maximized":false,"workspace_id":null,"x":0,"y":0,"width":0,"height":0,"zoom_percent":0,"backend":"text \"quoted\"\n\\","x11_class":null,"x11_instance":null,"is_urgent":false,"workspace_order":0,"placement":"text \"quoted\"\n\\","floating_override":null}],"outputs":[{"name":"text \"quoted\"\n\\","make":null,"model":null,"enabled":false,"x":0,"y":0,"logical_width":0,"logical_height":0,"buffer_width":0,"buffer_height":0,"transform":"text \"quoted\"\n\\","bottom_exclusion":0,"scale":0,"refresh_hz":0,"is_focused":false}],"camera":{"x":0,"y":0,"max_x":0,"max_y":0,"zoom_percent":0},"shell":{"start_menu":null,"control_center":null,"power_menu":null,"taskbar_count":0,"polkit_dialog":null},"workspaces":[{"id":0,"name":null,"is_focused":false,"is_visible":false,"output":null,"automatic":false,"window_gap":0,"nodes":[{"id":null,"group":false,"axis":"horizontal","ratio":0}]}]}}}-{"Ok":{"State":{"seq":7,"session_id":"text \"quoted\"\n\\","focused_window_id":7,"windows":[{"id":7,"title":"text \"quoted\"\n\\","app_id":"text \"quoted\"\n\\","sandbox":{"engine":"text \"quoted\"\n\\","app_id":"text \"quoted\"\n\\","instance_id":"text \"quoted\"\n\\"},"pid":7,"is_focused":true,"is_minimized":true,"is_maximized":true,"workspace_id":7,"x":7,"y":7,"width":7,"height":7,"zoom_percent":7,"backend":"text \"quoted\"\n\\","x11_class":"text \"quoted\"\n\\","x11_instance":"text \"quoted\"\n\\","is_urgent":true,"workspace_order":7,"placement":"text \"quoted\"\n\\","floating_override":true}],"outputs":[{"name":"text \"quoted\"\n\\","make":"text \"quoted\"\n\\","model":"text \"quoted\"\n\\","enabled":true,"x":7,"y":7,"logical_width":7,"logical_height":7,"buffer_width":7,"buffer_height":7,"transform":"text \"quoted\"\n\\","bottom_exclusion":7,"scale":1.23456,"refresh_hz":1.23456,"is_focused":true}],"camera":{"x":7,"y":7,"max_x":7,"max_y":7,"zoom_percent":7},"shell":{"start_menu":{"state":"text \"quoted\"\n\\","progress":1.23456,"is_settled":true,"box":{"x":7,"y":7,"width":7,"height":7},"search_text":"text \"quoted\"\n\\","category":"text \"quoted\"\n\\","selected_index":7,"result_count":7},"control_center":{"state":"text \"quoted\"\n\\","progress":1.23456,"is_settled":true,"box":{"x":7,"y":7,"width":7,"height":7},"search_text":"text \"quoted\"\n\\","category":"text \"quoted\"\n\\","selected_index":7,"result_count":7},"power_menu":{"state":"text \"quoted\"\n\\","progress":1.23456,"is_settled":true,"box":{"x":7,"y":7,"width":7,"height":7},"search_text":"text \"quoted\"\n\\","category":"text \"quoted\"\n\\","selected_index":7,"result_count":7},"taskbar_count":7,"polkit_dialog":{"state":"text \"quoted\"\n\\","progress":1.23456,"is_settled":true,"box":{"x":7,"y":7,"width":7,"height":7},"search_text":"text \"quoted\"\n\\","category":"text \"quoted\"\n\\","selected_index":7,"result_count":7}},"workspaces":[{"id":7,"name":"text \"quoted\"\n\\","is_focused":true,"is_visible":true,"output":"text \"quoted\"\n\\","automatic":true,"window_gap":7,"nodes":[{"id":7,"group":true,"axis":"horizontal","ratio":1.23456}]}]}}}+{"Ok":{"State":{"seq":0,"session_id":"text \"quoted\"\n\\","focused_window_id":null,"windows":[{"id":0,"title":null,"app_id":null,"sandbox":null,"pid":null,"is_focused":false,"is_minimized":false,"is_maximized":false,"workspace_id":null,"x":0,"y":0,"width":0,"height":0,"zoom_percent":0,"backend":"text \"quoted\"\n\\","x11_class":null,"x11_instance":null,"is_urgent":false,"workspace_order":0,"placement":"text \"quoted\"\n\\","floating_override":null}],"outputs":[{"name":"text \"quoted\"\n\\","make":null,"model":null,"enabled":false,"x":0,"y":0,"logical_width":0,"logical_height":0,"buffer_width":0,"buffer_height":0,"transform":"text \"quoted\"\n\\","bottom_exclusion":0,"scale":0,"refresh_hz":0,"is_focused":false,"tearing_allowed":false,"tearing_active":false,"tearing_paused":false,"direct_scanout":false}],"camera":{"x":0,"y":0,"max_x":0,"max_y":0,"zoom_percent":0},"shell":{"start_menu":null,"control_center":null,"power_menu":null,"taskbar_count":0,"polkit_dialog":null},"workspaces":[{"id":0,"name":null,"is_focused":false,"is_visible":false,"output":null,"automatic":false,"window_gap":0,"nodes":[{"id":null,"group":false,"axis":"horizontal","ratio":0}]}]}}}+{"Ok":{"State":{"seq":7,"session_id":"text \"quoted\"\n\\","focused_window_id":7,"windows":[{"id":7,"title":"text \"quoted\"\n\\","app_id":"text \"quoted\"\n\\","sandbox":{"engine":"text \"quoted\"\n\\","app_id":"text \"quoted\"\n\\","instance_id":"text \"quoted\"\n\\"},"pid":7,"is_focused":true,"is_minimized":true,"is_maximized":true,"workspace_id":7,"x":7,"y":7,"width":7,"height":7,"zoom_percent":7,"backend":"text \"quoted\"\n\\","x11_class":"text \"quoted\"\n\\","x11_instance":"text \"quoted\"\n\\","is_urgent":true,"workspace_order":7,"placement":"text \"quoted\"\n\\","floating_override":true}],"outputs":[{"name":"text \"quoted\"\n\\","make":"text \"quoted\"\n\\","model":"text \"quoted\"\n\\","enabled":true,"x":7,"y":7,"logical_width":7,"logical_height":7,"buffer_width":7,"buffer_height":7,"transform":"text \"quoted\"\n\\","bottom_exclusion":7,"scale":1.23456,"refresh_hz":1.23456,"is_focused":true,"tearing_allowed":true,"tearing_active":true,"tearing_paused":true,"direct_scanout":true}],"camera":{"x":7,"y":7,"max_x":7,"max_y":7,"zoom_percent":7},"shell":{"start_menu":{"state":"text \"quoted\"\n\\","progress":1.23456,"is_settled":true,"box":{"x":7,"y":7,"width":7,"height":7},"search_text":"text \"quoted\"\n\\","category":"text \"quoted\"\n\\","selected_index":7,"result_count":7},"control_center":{"state":"text \"quoted\"\n\\","progress":1.23456,"is_settled":true,"box":{"x":7,"y":7,"width":7,"height":7},"search_text":"text \"quoted\"\n\\","category":"text \"quoted\"\n\\","selected_index":7,"result_count":7},"power_menu":{"state":"text \"quoted\"\n\\","progress":1.23456,"is_settled":true,"box":{"x":7,"y":7,"width":7,"height":7},"search_text":"text \"quoted\"\n\\","category":"text \"quoted\"\n\\","selected_index":7,"result_count":7},"taskbar_count":7,"polkit_dialog":{"state":"text \"quoted\"\n\\","progress":1.23456,"is_settled":true,"box":{"x":7,"y":7,"width":7,"height":7},"search_text":"text \"quoted\"\n\\","category":"text \"quoted\"\n\\","selected_index":7,"result_count":7}},"workspaces":[{"id":7,"name":"text \"quoted\"\n\\","is_focused":true,"is_visible":true,"output":"text \"quoted\"\n\\","automatic":true,"window_gap":7,"nodes":[{"id":7,"group":true,"axis":"horizontal","ratio":1.23456}]}]}}}{"Ok":{"WaitFor":{"condition":"text \"quoted\"\n\\","elapsed_ms":0,"state":null}}}{"Ok":{"WaitFor":{"condition":"text \"quoted\"\n\\","elapsed_ms":7,"state":"text \"quoted\"\n\\"}}}{"Ok":{"WaitForFrame":{"output":"text \"quoted\"\n\\","frame_seq":0,"elapsed_ms":0}}}@@ -67,7 +67,7 @@{"Ok":{"SamplePixels":{"output":"text \"quoted\"\n\\","x":0,"y":0,"width":0,"height":0,"gpu_readback":false,"pixels":[0]}}}{"Ok":{"SamplePixels":{"output":"text \"quoted\"\n\\","x":7,"y":7,"width":7,"height":7,"gpu_readback":true,"pixels":[7]}}}{"Ok":{"PerformanceStats":{"output_commits":0,"output_failed_commits":0,"fps":0.0,"frame_time_ms":0.0,"missed_frames":0,"refresh_hz":0.0,"titlebar_paints":0,"footer_paints":0,"edge_samples_attempted":0,"edge_samples_succeeded":0,"edge_samples_skipped":0,"edge_sample_ns":0,"panel_paints":0,"panel_allocated_bytes":0,"panel_reused_bytes":0,"icon_cache_hits":0,"icon_cache_misses":0,"icon_decode_ns":0,"icon_decode_count":0,"icon_decoded_bytes":0,"icon_queue_depth_max":0,"taskbar_paints":0,"taskbar_paint_ns":0,"taskbar_raster_pixels":0,"taskbar_clock_frame_requests":0,"taskbar_clock_paints":0,"taskbar_start_paints":0,"taskbar_chip_paints":0,"taskbar_tray_paints":0,"taskbar_hover_paints":0,"taskbar_press_paints":0,"taskbar_audio_paints":0,"recent_errors_count":0,"anim_frames_scheduled":0,"anim_wasted_wakeups":0,"anim_longest_ms":0,"anim_speed":0,"anim_enabled":false,"anim_reduced_motion":false}}}-{"Ok":{"PerformanceStats":{"screenshot_selection":{"motion_events":7,"updates":7,"update_ns":7,"toolbar_paints":7,"label_paints":7,"scene_nodes_created":7},"frame_work":{"cpu_frame":{"samples":7,"total_samples":7,"avg_ms":1.23456,"p50_ms":1.23456,"p95_ms":1.23456,"p99_ms":1.23456,"max_ms":1.23456},"taskbar_cpu":{"samples":7,"total_samples":7,"avg_ms":1.23456,"p50_ms":1.23456,"p95_ms":1.23456,"p99_ms":1.23456,"max_ms":1.23456},"chrome_cpu":{"samples":7,"total_samples":7,"avg_ms":1.23456,"p50_ms":1.23456,"p95_ms":1.23456,"p99_ms":1.23456,"max_ms":1.23456},"panels_cpu":{"samples":7,"total_samples":7,"avg_ms":1.23456,"p50_ms":1.23456,"p95_ms":1.23456,"p99_ms":1.23456,"max_ms":1.23456},"anim_cpu":{"samples":7,"total_samples":7,"avg_ms":1.23456,"p50_ms":1.23456,"p95_ms":1.23456,"p99_ms":1.23456,"max_ms":1.23456},"projection_cpu":{"samples":7,"total_samples":7,"avg_ms":1.23456,"p50_ms":1.23456,"p95_ms":1.23456,"p99_ms":1.23456,"max_ms":1.23456},"glass_cpu":{"samples":7,"total_samples":7,"avg_ms":1.23456,"p50_ms":1.23456,"p95_ms":1.23456,"p99_ms":1.23456,"max_ms":1.23456},"scene_commit_cpu":{"samples":7,"total_samples":7,"avg_ms":1.23456,"p50_ms":1.23456,"p95_ms":1.23456,"p99_ms":1.23456,"max_ms":1.23456},"gpu_elapsed":{"samples":7,"total_samples":7,"avg_ms":1.23456,"p50_ms":1.23456,"p95_ms":1.23456,"p99_ms":1.23456,"max_ms":1.23456},"gpu_timing_available":true,"gpu_samples_dropped":7},"output_commits":7,"output_failed_commits":7,"fps":1.2,"frame_time_ms":1.2,"missed_frames":7,"refresh_hz":1.2,"titlebar_paints":7,"footer_paints":7,"edge_samples_attempted":7,"edge_samples_succeeded":7,"edge_samples_skipped":7,"edge_sample_ns":7,"panel_paints":7,"panel_allocated_bytes":7,"panel_reused_bytes":7,"icon_cache_hits":7,"icon_cache_misses":7,"icon_decode_ns":7,"icon_decode_count":7,"icon_decoded_bytes":7,"icon_queue_depth_max":7,"taskbar_paints":7,"taskbar_paint_ns":7,"taskbar_raster_pixels":7,"taskbar_clock_frame_requests":7,"taskbar_clock_paints":7,"taskbar_start_paints":7,"taskbar_chip_paints":7,"taskbar_tray_paints":7,"taskbar_hover_paints":7,"taskbar_press_paints":7,"taskbar_audio_paints":7,"recent_errors_count":7,"anim_frames_scheduled":7,"anim_wasted_wakeups":7,"anim_longest_ms":7,"anim_speed":1.23456,"anim_enabled":true,"anim_reduced_motion":true,"startup":{"build_mode":"text \"quoted\"\n\\","renderer":"text \"quoted\"\n\\","scale":1.23,"output_count":7,"catalog_entries":7,"autostart_count":7,"catalog_state":"text \"quoted\"\n\\","wallpaper_state":"text \"quoted\"\n\\","catalog_provisional":true,"catalog_loading":true,"catalog_generation":7,"renderer_ready_ns":7,"config_ready_ns":7,"catalog_cache_read_ns":7,"catalog_scan_ns":7,"wallpaper_decode_ns":7,"socket_ready_ns":7,"ipc_ready_ns":7,"session_ready_ns":7,"session_clients_started_ns":7,"xwayland_ready_ns":7,"first_presented_ns":7,"first_ipc_ns":7,"first_input_ns":7,"catalog_published_ns":7,"wallpaper_presented_ns":7,"catalog_cache_read_duration_ns":7,"catalog_scan_duration_ns":7,"wallpaper_decode_duration_ns":7,"backend_start_ns":7,"backend_ready_ns":7,"input_ready_ns":7,"first_visible_ns":7,"services_started_ns":7,"login_to_compositor_ns":7,"login_to_visible_ns":7,"reveal_done_ns":7},"desktop":{"paints":7,"damage_pixels":7,"tile_presents":7,"texture_uploads":7},"output_skipped_commits":7,"glass_reblurs":7}}}+{"Ok":{"PerformanceStats":{"screenshot_selection":{"motion_events":7,"updates":7,"update_ns":7,"toolbar_paints":7,"label_paints":7,"scene_nodes_created":7},"frame_work":{"cpu_frame":{"samples":7,"total_samples":7,"avg_ms":1.23456,"p50_ms":1.23456,"p95_ms":1.23456,"p99_ms":1.23456,"max_ms":1.23456},"taskbar_cpu":{"samples":7,"total_samples":7,"avg_ms":1.23456,"p50_ms":1.23456,"p95_ms":1.23456,"p99_ms":1.23456,"max_ms":1.23456},"chrome_cpu":{"samples":7,"total_samples":7,"avg_ms":1.23456,"p50_ms":1.23456,"p95_ms":1.23456,"p99_ms":1.23456,"max_ms":1.23456},"panels_cpu":{"samples":7,"total_samples":7,"avg_ms":1.23456,"p50_ms":1.23456,"p95_ms":1.23456,"p99_ms":1.23456,"max_ms":1.23456},"anim_cpu":{"samples":7,"total_samples":7,"avg_ms":1.23456,"p50_ms":1.23456,"p95_ms":1.23456,"p99_ms":1.23456,"max_ms":1.23456},"projection_cpu":{"samples":7,"total_samples":7,"avg_ms":1.23456,"p50_ms":1.23456,"p95_ms":1.23456,"p99_ms":1.23456,"max_ms":1.23456},"glass_cpu":{"samples":7,"total_samples":7,"avg_ms":1.23456,"p50_ms":1.23456,"p95_ms":1.23456,"p99_ms":1.23456,"max_ms":1.23456},"scene_commit_cpu":{"samples":7,"total_samples":7,"avg_ms":1.23456,"p50_ms":1.23456,"p95_ms":1.23456,"p99_ms":1.23456,"max_ms":1.23456},"gpu_elapsed":{"samples":7,"total_samples":7,"avg_ms":1.23456,"p50_ms":1.23456,"p95_ms":1.23456,"p99_ms":1.23456,"max_ms":1.23456},"gpu_timing_available":true,"gpu_samples_dropped":7},"output_commits":7,"output_failed_commits":7,"fps":1.2,"frame_time_ms":1.2,"missed_frames":7,"refresh_hz":1.2,"titlebar_paints":7,"footer_paints":7,"edge_samples_attempted":7,"edge_samples_succeeded":7,"edge_samples_skipped":7,"edge_sample_ns":7,"panel_paints":7,"panel_allocated_bytes":7,"panel_reused_bytes":7,"icon_cache_hits":7,"icon_cache_misses":7,"icon_decode_ns":7,"icon_decode_count":7,"icon_decoded_bytes":7,"icon_queue_depth_max":7,"taskbar_paints":7,"taskbar_paint_ns":7,"taskbar_raster_pixels":7,"taskbar_clock_frame_requests":7,"taskbar_clock_paints":7,"taskbar_start_paints":7,"taskbar_chip_paints":7,"taskbar_tray_paints":7,"taskbar_hover_paints":7,"taskbar_press_paints":7,"taskbar_audio_paints":7,"recent_errors_count":7,"anim_frames_scheduled":7,"anim_wasted_wakeups":7,"anim_longest_ms":7,"anim_speed":1.23456,"anim_enabled":true,"anim_reduced_motion":true,"startup":{"build_mode":"text \"quoted\"\n\\","renderer":"text \"quoted\"\n\\","scale":1.23,"output_count":7,"catalog_entries":7,"autostart_count":7,"catalog_state":"text \"quoted\"\n\\","wallpaper_state":"text \"quoted\"\n\\","catalog_provisional":true,"catalog_loading":true,"catalog_generation":7,"renderer_ready_ns":7,"config_ready_ns":7,"catalog_cache_read_ns":7,"catalog_scan_ns":7,"wallpaper_decode_ns":7,"socket_ready_ns":7,"ipc_ready_ns":7,"session_ready_ns":7,"session_clients_started_ns":7,"xwayland_ready_ns":7,"first_presented_ns":7,"first_ipc_ns":7,"first_input_ns":7,"catalog_published_ns":7,"wallpaper_presented_ns":7,"catalog_cache_read_duration_ns":7,"catalog_scan_duration_ns":7,"wallpaper_decode_duration_ns":7,"backend_start_ns":7,"backend_ready_ns":7,"input_ready_ns":7,"first_visible_ns":7,"services_started_ns":7,"login_to_compositor_ns":7,"login_to_visible_ns":7,"reveal_done_ns":7},"desktop":{"paints":7,"damage_pixels":7,"tile_presents":7,"texture_uploads":7},"output_skipped_commits":7,"glass_reblurs":7,"tearing_async_flips":7,"tearing_refused_flips":7}}}{"Ok":{"IdleState":{"enabled":false,"state":"text \"quoted\"\n\\","blank_after_seconds":0,"suspend_after_seconds":0,"idle_ms":0,"is_inhibited":false,"inhibitor_count":0,"suspend_request_count":0,"inhibitors":[{"surface_ptr":0,"window_id":null,"app_id":null,"title":null,"is_active":false,"reason":null}]}}}{"Ok":{"IdleState":{"enabled":true,"state":"text \"quoted\"\n\\","blank_after_seconds":7,"suspend_after_seconds":7,"idle_ms":7,"is_inhibited":true,"inhibitor_count":7,"suspend_request_count":7,"inhibitors":[{"surface_ptr":7,"window_id":7,"app_id":"text \"quoted\"\n\\","title":"text \"quoted\"\n\\","is_active":true,"reason":"text \"quoted\"\n\\"}]}}}{"Ok":{"CaptureState":{"supported":false,"active_sessions":0,"sessions":[{"output":null,"window_id":null}],"last_failure":null,"indicator":null}}}diff --git a/src/output/frame.zig b/src/output/frame.zigindex 40e2457..82bf516 100644--- a/src/output/frame.zig+++ b/src/output/frame.zig@@ -1,4 +1,4 @@-//! Output frames: committing, frame scheduling, tearing and presentation.+//! Output frames: committing, frame scheduling and presentation.const std = @import("std");const Output = @import("../Output.zig");@@ -11,6 +11,7 @@ const glass = @import("../glass.zig");const stats = @import("../ipc/stats.zig");const trace = @import("frame_trace.zig");const late = @import("late.zig");+const tearing = @import("tearing.zig");const wlr_color_transform_unref = Output.wlr_color_transform_unref;const log = std.log.scoped(.output);const CursorState = Output.CursorState;@@ -39,17 +40,18 @@ pub fn commitFrameState(output: *Output, state: *wlr.Output.State) bool {}const had_transform = state.committed.color_transform;- state.tearing_page_flip = state.committed.buffer and output.tearingAllowed();+ state.tearing_page_flip = state.committed.buffer and output.tearingAllowed() and tearing.frameCanTear(output, state);if (state.tearing_page_flip and !output.wlr_output.testState(state)) {state.tearing_page_flip = false;- output.tearing_rejected = true;+ tearing.refused(output);}var success = output.wlr_output.commitState(state);if (!success and state.tearing_page_flip) {state.tearing_page_flip = false;- output.tearing_rejected = true;+ tearing.refused(output);success = output.wlr_output.commitState(state);}+ if (success) tearing.committed(output, state);if (had_transform) {if (success) {output.color.status = if (output.color.transform != null) .applied else .neutral;@@ -164,30 +166,6 @@ pub fn sendFrameDone(output: *Output) void {output.server.switcher.frameDone(output, &preview_time);}-// A client commit can render before the next vblank when the previous flip is-// complete. Coalesce commits at idle, after wlroots has updated scene damage.-pub fn tearingAllowed(output: *Output) bool {- const server = output.server;- if (!server.config.compositor.allow_tearing or output.tearing_rejected or- server.locker != null or server.polkit_dialog != null or server.greeter_mode or- output.power_off or !output.wlr_output.enabled) return false;- const focused = server.input.seat.keyboard_state.focused_surface orelse return false;- const top = @import("../Toplevel.zig").fromSurface(server, focused) orelse return false;- if (!top.in_world or top.minimized or top.tab_hidden or !top.isFullscreen() or top.currentOutput() != output) return false;- return @import("../extra_protocols.zig").rediwm_protocols_tearing(server.extra_protocols, top.surface());-}--pub fn queueTearing(output: *Output) void {- if (output.tearing_idle != null or !output.tearingAllowed()) return;- output.tearing_idle = output.server.wl_server.getEventLoop().addIdle(*Output, tearingIdle, output) catch null;-}--pub fn tearingIdle(output: *Output) void {- output.tearing_idle = null;- if (!output.tearingAllowed() or output.wlr_output.frame_pending or output.vblank_armed) return;- runFrame(output);-}-pub fn handleFrame(listener: *wl.Listener(*wlr.Output), _: *wlr.Output) void {const output: *Output = @fieldParentPtr("frame", listener);// A deferred frame is on its way; this event is damage asking for it.diff --git a/src/output/game.zig b/src/output/game.zignew file mode 100644index 0000000..c5f6a3e--- /dev/null+++ b/src/output/game.zig@@ -0,0 +1,36 @@+//! The window an output shows as a game: the keyboard-focused toplevel that+//! fills it, fullscreen or borderless. Tearing follows it (and automatic+//! adaptive sync will), so every caller agrees on one rule.++const wlr = @import("wlroots");+const Output = @import("../Output.zig");+const Toplevel = @import("../Toplevel.zig");++pub fn window(output: *Output) ?*Toplevel {+ const server = output.server;+ const focused = server.input.seat.keyboard_state.focused_surface orelse return null;+ const top = Toplevel.fromSurface(server, focused) orelse return null;+ if (!top.in_world or top.minimized or top.tab_hidden or top.currentOutput() != output) return null;+ if (top.isFullscreen() or coversOutput(top, output)) return top;+ return null;+}++/// Borderless windowed, the default of many games: an undecorated window the+/// client placed itself (not maximized or tiled) whose frame is the output.+fn coversOutput(top: *Toplevel, output: *Output) bool {+ if (top.hasServerDecorations() or top.isMaximized() or top.forcedGeometry() != null) return false;+ var box: wlr.Box = undefined;+ output.server.output_layout.getBox(output.wlr_output, &box);+ if (box.width <= 0 or box.height <= 0) return false;+ const world = &output.server.world;+ const a = top.frameWorld(0, 0);+ const b = top.frameWorld(@floatFromInt(top.chrome_width), @floatFromInt(top.chrome_height));+ const start = world.toLayout(a.x, a.y);+ const end = world.toLayout(b.x, b.y);+ return near(start.x, box.x) and near(start.y, box.y) and+ near(end.x, box.x + box.width) and near(end.y, box.y + box.height);+}++fn near(value: f64, edge: i32) bool {+ return @abs(value - @as(f64, @floatFromInt(edge))) < 1.0;+}diff --git a/src/output/tearing.zig b/src/output/tearing.zignew file mode 100644index 0000000..555c384--- /dev/null+++ b/src/output/tearing.zig@@ -0,0 +1,93 @@+//! Tearing on an `Output`: asynchronous page flips for a game window+//! (`game.zig`) that asks for them with the `wp_tearing_control_v1` hint+//! `async`, while `[compositor] allow_tearing` is on. Refused flips fall back+//! to a synchronous flip for that frame; `tearing_policy.zig` decides when a+//! run of refusals pauses attempts.++const std = @import("std");+const wl = @import("wayland").server.wl;+const wlr = @import("wlroots");+const Output = @import("../Output.zig");+const game = @import("game.zig");+const tearing_policy = @import("tearing_policy.zig");+const stats = @import("../ipc/stats.zig");+const extra_protocols = @import("../extra_protocols.zig");+const log = std.log.scoped(.output);++pub const State = struct {+ backoff: tearing_policy.Backoff = .{},+ /// The last committed buffer was flipped asynchronously.+ active: bool = false,+ idle: ?*wl.EventSource = null,+};++/// The policy alone: a game window on this output asks to tear and nothing+/// forbids it. Refusals by the driver do not change this (`allowed` does).+pub fn wanted(output: *Output) bool {+ const server = output.server;+ if (!server.config.compositor.allow_tearing or server.locker != null or server.polkit_dialog != null or+ server.greeter_mode or output.power_off or !output.wlr_output.enabled) return false;+ const top = game.window(output) orelse return false;+ return extra_protocols.rediwm_protocols_tearing(server.extra_protocols, top.surface());+}++/// Whether this output tries asynchronous flips now: wanted, and not paused+/// after a run of refusals.+pub fn allowed(output: *Output) bool {+ if (!wanted(output)) return false;+ const backoff = &output.tearing.backoff;+ return backoff.paused_until_ns == 0 or !backoff.paused(stats.nowNs());+}++/// Whether this frame may flip asynchronously at all. Atomic async flips may+/// change only the primary plane's buffer, so a frame that also changes the+/// mode, colour, image description or hardware cursor would be refused:+/// flip it synchronously without spending a test commit.+pub fn frameCanTear(output: *Output, state: *const wlr.Output.State) bool {+ const c = state.committed;+ if (!c.buffer or c.mode or c.enabled or c.scale or c.transform or c.adaptive_sync_enabled or+ c.render_format or c.color_transform or c.image_description) return false;+ return std.meta.eql(Output.CursorState.of(output.wlr_output), output.committed_cursor);+}++/// The driver refused an asynchronous flip (test or commit).+pub fn refused(output: *Output) void {+ stats.global_stats.tearing_refused_flips +%= 1;+ const pause = output.tearing.backoff.failed(stats.nowNs()) orelse return;+ // Once per run: later pauses of the same run are only debug noise.+ if (pause == tearing_policy.tuning.first_pause_ns) {+ log.info("output '{s}': {d} asynchronous page flips refused in a row; tearing paused, retrying with backoff", .{+ output.wlr_output.name, tearing_policy.tuning.failures_before_pause,+ });+ } else {+ log.debug("output '{s}': tearing paused for {d} ms", .{ output.wlr_output.name, pause / std.time.ns_per_ms });+ }+}++/// A frame state was committed.+pub fn committed(output: *Output, state: *const wlr.Output.State) void {+ if (!state.committed.buffer) return;+ output.tearing.active = state.tearing_page_flip;+ if (state.tearing_page_flip) {+ output.tearing.backoff.succeeded();+ stats.global_stats.tearing_async_flips +%= 1;+ }+}++// A client commit can render before the next vblank when the previous flip is+// complete. Coalesce commits at idle, after wlroots has updated scene damage.+pub fn queue(output: *Output) void {+ if (output.tearing.idle != null or !allowed(output)) return;+ output.tearing.idle = output.server.wl_server.getEventLoop().addIdle(*Output, onIdle, output) catch null;+}++fn onIdle(output: *Output) void {+ output.tearing.idle = null;+ if (!allowed(output) or output.wlr_output.frame_pending or output.vblank_armed) return;+ output.runFrame();+}++pub fn deinit(output: *Output) void {+ if (output.tearing.idle) |source| source.remove();+ output.tearing.idle = null;+}diff --git a/src/output/tearing_policy.zig b/src/output/tearing_policy.zignew file mode 100644index 0000000..852ea6a--- /dev/null+++ b/src/output/tearing_policy.zig@@ -0,0 +1,92 @@+//! Tearing backoff: how an output reacts when the driver refuses an+//! asynchronous page flip. Plain data and a caller-supplied clock, so the+//! cases are tested without wlroots; `tearing.zig` connects it to an `Output`.+//!+//! A refused flip only makes that frame synchronous. Atomic async flips may+//! change nothing but the primary plane's buffer, so single frames fail for+//! passing reasons (a cursor move the pre-check could not see, a buffer+//! modifier the driver cannot flip asynchronously). A long run of refusals+//! means the driver will not take this kind of buffer at all: then attempts+//! stop for a while, since each one costs an extra test commit, and resume+//! by themselves with a growing pause. No timer: the next client commit after+//! the pause tries again.++const std = @import("std");++const s = std.time.ns_per_s;++pub const tuning = struct {+ /// Refusals in a row before attempts pause.+ pub const failures_before_pause = 30;+ pub const first_pause_ns = 2 * s;+ pub const max_pause_ns = 30 * s;+};++pub const Backoff = struct {+ failures: u16 = 0,+ /// Zero when not paused.+ paused_until_ns: u64 = 0,+ next_pause_ns: u64 = tuning.first_pause_ns,++ /// Whether attempts are paused at `now`. Ending a pause clears it, so+ /// callers can skip the clock read while `paused_until_ns` is zero.+ pub fn paused(self: *Backoff, now_ns: u64) bool {+ if (self.paused_until_ns == 0) return false;+ if (now_ns < self.paused_until_ns) return true;+ self.paused_until_ns = 0;+ return false;+ }++ /// An asynchronous flip went through: start over.+ pub fn succeeded(self: *Backoff) void {+ self.failures = 0;+ self.next_pause_ns = tuning.first_pause_ns;+ }++ /// The driver refused an asynchronous flip. Returns the pause this+ /// refusal starts, if any.+ pub fn failed(self: *Backoff, now_ns: u64) ?u64 {+ self.failures += 1;+ if (self.failures < tuning.failures_before_pause) return null;+ self.failures = 0;+ const pause = self.next_pause_ns;+ self.paused_until_ns = now_ns + pause;+ self.next_pause_ns = @min(pause * 2, tuning.max_pause_ns);+ return pause;+ }+};++test "isolated refusals never pause" {+ var b: Backoff = .{};+ for (0..1000) |i| {+ for (0..tuning.failures_before_pause - 1) |_| try std.testing.expectEqual(null, b.failed(i));+ b.succeeded();+ try std.testing.expect(!b.paused(i));+ }+}++test "a run of refusals pauses, resumes and backs off" {+ var b: Backoff = .{};+ var now: u64 = 1000;+ for (0..tuning.failures_before_pause - 1) |_| try std.testing.expectEqual(null, b.failed(now));+ try std.testing.expectEqual(@as(?u64, tuning.first_pause_ns), b.failed(now));+ try std.testing.expect(b.paused(now));+ try std.testing.expect(b.paused(now + tuning.first_pause_ns - 1));+ now += tuning.first_pause_ns;+ try std.testing.expect(!b.paused(now));+ try std.testing.expectEqual(@as(u64, 0), b.paused_until_ns);++ // Still refused after the pause: the next one is longer, up to the cap.+ var expected: u64 = tuning.first_pause_ns;+ for (0..8) |_| {+ expected = @min(expected * 2, tuning.max_pause_ns);+ for (0..tuning.failures_before_pause - 1) |_| _ = b.failed(now);+ try std.testing.expectEqual(@as(?u64, expected), b.failed(now));+ now += expected;+ }++ // One success resets the backoff.+ b.succeeded();+ for (0..tuning.failures_before_pause - 1) |_| _ = b.failed(now);+ try std.testing.expectEqual(@as(?u64, tuning.first_pause_ns), b.failed(now));+}diff --git a/src/scene_outputs.c b/src/scene_outputs.cindex 68e7fd3..b65d5b8 100644--- a/src/scene_outputs.c+++ b/src/scene_outputs.c@@ -83,6 +83,10 @@ bool rediwm_scene_output_has_pending_damage(const struct rediwm_scene_output *oureturn !pixman_region32_empty((pixman_region32_t *)&out->pending_commit_damage);}+bool rediwm_scene_output_direct_scanout(const struct rediwm_scene_output *out) {+ return out->prev_scanout;+}+static void output_commit(struct wl_listener *listener, void *data) {struct rediwm_scene_output *out = wl_container_of(listener, out, output_commit);struct wlr_output_event_commit *event = data;diff --git a/src/scene_outputs.h b/src/scene_outputs.hindex 2c32af8..693a42a 100644--- a/src/scene_outputs.h+++ b/src/scene_outputs.h@@ -88,6 +88,8 @@ void rediwm_scene_output_damage_whole(struct rediwm_scene_output *);// Whether anything asks for a frame: the output itself, or damage not yet committed.bool rediwm_scene_output_needs_frame(const struct rediwm_scene_output *);bool rediwm_scene_output_has_pending_damage(const struct rediwm_scene_output *);+// Whether the last built frame scanned a client buffer out directly.+bool rediwm_scene_output_direct_scanout(const struct rediwm_scene_output *);// Frame timing trace (-Dframe-trace, src/output/frame_trace.zig): when content last asked// this output for a frame. A no-op in every other build.diff --git a/src/scene_outputs.zig b/src/scene_outputs.zigindex efc5bd7..519aee2 100644--- a/src/scene_outputs.zig+++ b/src/scene_outputs.zig@@ -9,6 +9,9 @@ pub const SceneOutput = opaque {pub const needsFrame = rediwm_scene_output_needs_frame;extern fn rediwm_scene_output_has_pending_damage(output: *const SceneOutput) bool;pub const hasPendingDamage = rediwm_scene_output_has_pending_damage;+ extern fn rediwm_scene_output_direct_scanout(output: *const SceneOutput) bool;+ /// Whether the last built frame scanned a client buffer out directly.+ pub const directScanout = rediwm_scene_output_direct_scanout;extern fn rediwm_scene_output_damage_whole(output: *SceneOutput) void;/// Repaints all of the output and asks for a frame.pub const damageWhole = rediwm_scene_output_damage_whole;diff --git a/src/ui_tests.zig b/src/ui_tests.zigindex b16ae89..4581c2e 100644--- a/src/ui_tests.zig+++ b/src/ui_tests.zig@@ -82,6 +82,7 @@ test {_ = @import("ipc/stats.zig");_ = @import("ipc/frame_metrics.zig");_ = @import("output/late_render_tests.zig");+ _ = @import("output/tearing_policy.zig");_ = @import("config").keybinds;_ = @import("osd_paint.zig");_ = @import("osd.zig");diff --git a/tests/control_center.py b/tests/control_center.pyindex 167da78..2a79655 100644--- a/tests/control_center.py+++ b/tests/control_center.py@@ -10,6 +10,7 @@ import osfrom pathlib import Pathimport tempfileimport time+import tomllibfrom PIL import Image, ImageChopsfrom hardware_keys import private_audio, wait@@ -341,6 +342,13 @@ print(f'fixture,backlight,{value},{value}%,100')page("Displays")assert any(w["label"] == "Resolution" for w in widgets())assert not any(w["label"] == "Duplicate" for w in widgets())+ # Tearing is off by default; the switch saves and applies it.+ assert ui.scroll_into_view("allow_tearing")["on"] is False+ click(ui.scroll_into_view("allow_tearing"))+ config = tmp / "rediwm-config.toml"+ wait(lambda: tomllib.loads(config.read_text()).get("compositor", {}).get("allow_tearing") is True, "allow_tearing saved")+ click(ui.scroll_into_view("allow_tearing"))+ wait(lambda: tomllib.loads(config.read_text())["compositor"]["allow_tearing"] is False, "allow_tearing cleared")capture("displays")page("Appearance")assert not any(w["role"] == "swatch" or w.get("label") == "Accent colour" for w in widgets())diff --git a/tests/wlr_protocols.py b/tests/wlr_protocols.pyindex 621ee8d..955cef7 100644--- a/tests/wlr_protocols.py+++ b/tests/wlr_protocols.py@@ -269,6 +269,11 @@ def extra_protocols(tmp):assert window["content_type"] == "video" and window["workspace_id"] == 1, windowrules = s.ipc.request(query="get_window_rules", params={"id": window["id"]})assert rules["live"]["opacity"] == 0.75, rules+ # The focused fullscreen window asks for async presentation: its output+ # (and only that one) may tear. Headless never flips asynchronously.+ tearing = lambda: [o["name"] for o in s.ipc.get_outputs() if o["tearing_allowed"]]+ wait_for(lambda: len(tearing()) == 1, "fullscreen async window did not allow tearing")+ assert not any(o["tearing_active"] or o["tearing_paused"] for o in s.ipc.get_outputs())workspaces = s.ipc.request(query="workspaces")assert workspaces == [{"id": 1, "name": "Canvas", "is_focused": True,"is_visible": True, "output": None, "automatic": False,@@ -277,6 +282,7 @@ def extra_protocols(tmp):expect_line(child, "extras-updated")wait_for(lambda: s.window("rediwm.protocol-extras")["content_type"] == "game", "content hint did not update")assert s.window("rediwm.protocol-extras")["tag"] == "main"+ wait_for(lambda: not tearing(), "a vsync hint still allowed tearing")rules = s.ipc.request(query="get_window_rules", params={"id": window["id"]})assert rules["live"]["opacity"] is None, ruleschild.stdin.write("exit\n"); child.stdin.flush()