RediWM is a Wayland compositor written in Zig (OpenGL ES) that includes everything in one process
VRR: adaptive sync per output (plan P2)
oxydizer8f6f22334349
diff --git a/docs/plans/vrr-tearing.md b/docs/plans/vrr-tearing.mdindex 62dd081..73a10e2 100644--- a/docs/plans/vrr-tearing.md+++ b/docs/plans/vrr-tearing.md@@ -1,7 +1,8 @@# 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.+Status: 2026-11-24. D1–D5 decided (as proposed). P1 committed; P0 run+2026-11-21 (tearing only); P2 built 2026-11-24 (see "P2 as built"); P3–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@@ -316,3 +317,44 @@ with a HEAD worktree.buffers are released and IPC reports `tearing_paused`. No driver list, so afixed kernel needs no change here. Revisit with a DRM run once the i915 fixlands (or wlroots stops writing an unchanged cursor plane in async commits).++## P2 as built (2026-11-24)++* `[[outputs]] adaptive_sync = "off" | "auto" | "always"` (default `auto`,+ D1), `output_config.AdaptiveSync`; `Patch.adaptive_sync`, saved by+ `output_save` like `transform`; IPC `set_output_config` and+ `rediwm-msg output-config --adaptive-sync`.+* `output/vrr_policy.zig`: `wanted(mode, game, blocked)` and the off+ debounce (500 ms; on is immediate), with unit tests. `blocked` is the+ greeter or an output that is off; a locked session has no game window, so+ `auto` turns off by itself.+* `output/vrr.zig`. **Deviation from the design:** the wanted state is+ evaluated in `runFrame` before every frame (`vrr.prepare`) instead of on+ a list of events (focus, fullscreen, workspace, lock, reload). It costs a+ `game.window` check per frame and cannot miss a trigger. A change sets+ `vrr.pending`, which forces that frame's commit (and is registered in+ `commitIsRedundant`); `commitFrameState` tests it on a copy of the state+ first (`vrr.apply`). The debounce arms a timer that schedules a frame.+* Refused toggles: `auto` sets `needs_modeset` and stops switching on this+ output and mode; `always`/`off` retry the test with a modeset of the+ current mode; a switch refused even then, or an enable that commits but+ reads back disabled, sets `refused` for the mode. Both reset when the+ mode or the setting changes.+* wlr-output-management: a head's `adaptive_sync_enabled` that differs from+ the current status becomes `always` or `off`.+* IPC `outputs`: `adaptive_sync` (mode), `adaptive_sync_supported`,+ `_wanted` (policy, regardless of support), `_active`, `_needs_modeset`.+* Settings → Displays: a "Variable refresh rate" row with Off / Automatic /+ Always when the display supports it, "Not supported by this display"+ otherwise, and a status line when Automatic needs a modeset. Search entry.+* Tests: `vrr_policy.zig` unit tests; `tests/wlr_protocols.py` (wanted+ follows the fullscreen game in `auto`, `off` persists and clears it,+ headless refuses `wlr-randr --adaptive-sync enabled`);+ `tests/control_center.py` checks the unsupported row.+* **Not verified on DRM.** Whether i915 toggles VRR_ENABLED without a+ modeset (P0's first question) is still open; the code handles both+ answers. Check on the laptop's VT: a fullscreen `vkcube` with `auto` should+ report `adaptive_sync_active = true` and the panel's OSD/`modetest -p`+ should show VRR_ENABLED=1, and it should return to 0 about 0.5 s after+ leaving the game.+diff --git a/po/de.po b/po/de.poindex 16746b9..bdf0d51 100644--- a/po/de.po+++ b/po/de.po@@ -144,6 +144,10 @@ msgstr "Eine Rohwarteschlange reicht Befehle unverändert durch; zum normalen PDmsgid "A toolkit config folder is a symlink. Apply the colors in its real location, or make it a regular folder."msgstr "Ein Konfigurationsordner des Toolkits ist ein symbolischer Link. Wende die Farben am tatsächlichen Speicherort an oder ersetze den Link durch einen normalen Ordner."+#: src/control_center/sections/display.zig+msgid "Always"+msgstr "Immer"+#: src/control_center/sections/appearance.zigmsgid "APPEARANCE"msgstr "DARSTELLUNG"@@ -3877,6 +3881,10 @@ msgstr "Nicht angegeben"msgid "Not supported"msgstr "Nicht unterstützt"+#: src/control_center/sections/display.zig+msgid "Not supported by this display"+msgstr "Von diesem Bildschirm nicht unterstützt"+#: src/files/app_places.zigmsgid "Nothing to add to Places"msgstr "Nichts zu Orten hinzuzufügen"@@ -6047,6 +6055,10 @@ msgstr "Für diese Fähigkeit bietet der aktuelle Treiber keinen wählbaren Wartmsgid "This connection has no direct presence check."msgstr "Diese Verbindung hat keine direkte Anwesenheitsprüfung."+#: src/control_center/sections/display.zig+msgid "This display changes variable refresh only with a mode switch: choose Always or Off."+msgstr "Dieser Bildschirm ändert die variable Bildwiederholrate nur mit einem Moduswechsel: Wähle Immer oder Aus."+#: src/control_center/sections/printers_tools.zigmsgid "This driver does not expose the suggested resolution as a queue setting. Review its quality or driver choices."msgstr "Der Treiber stellt die vorgeschlagene Auflösung nicht als Warteschlangeneinstellung bereit. Prüfe seine Qualitäts- oder Treiberoptionen."@@ -6503,6 +6515,11 @@ msgstr "Benutzer"msgid "Uses the main theme. Apply again after changing it; restart apps to see the colors."msgstr "Nutzt das Hauptthema. Wende es nach Änderungen erneut an; starte Anwendungen für neue Farben neu."+#: src/control_center/search_index.zig+#: src/control_center/sections/display.zig+msgid "Variable refresh rate"+msgstr "Variable Bildwiederholrate"+#: src/control_center/sections/desktop.zigmsgid "Vertical Pan"msgstr "Vertikal schwenken"@@ -6535,6 +6552,10 @@ msgstr "Lautstärke erhöhen"msgid "Volume, microphones and output devices."msgstr "Lautstärke, Mikrofone und Ausgabegeräte."+#: src/control_center/search_index.zig+msgid "vrr freesync gsync adaptive sync game"+msgstr "vrr freesync gsync adaptive sync spiel bildwiederholrate"+#: src/control_center/sections/network.zigmsgid "WPA2 / WPA3 Personal"msgstr "WPA2 / WPA3 Personal"diff --git a/po/es.po b/po/es.poindex 02d087f..681d325 100644--- a/po/es.po+++ b/po/es.po@@ -141,6 +141,10 @@ msgstr "Una cola sin procesar transmite los comandos sin cambios; imprimir archimsgid "A toolkit config folder is a symlink. Apply the colors in its real location, or make it a regular folder."msgstr "La carpeta de configuración de un toolkit es un enlace simbólico. Aplica los colores en su ubicación real o conviértela en una carpeta normal."+#: src/control_center/sections/display.zig+msgid "Always"+msgstr "Siempre"+#: src/control_center/sections/appearance.zigmsgid "APPEARANCE"msgstr "APARIENCIA"@@ -3874,6 +3878,10 @@ msgstr "Sin especificar"msgid "Not supported"msgstr "No compatible"+#: src/control_center/sections/display.zig+msgid "Not supported by this display"+msgstr "No compatible con esta pantalla"+#: src/files/app_places.zigmsgid "Nothing to add to Places"msgstr "No hay nada que añadir a Lugares"@@ -6044,6 +6052,10 @@ msgstr "Esta función no tiene un valor predeterminado de cola seleccionable enmsgid "This connection has no direct presence check."msgstr "Esta conexión no tiene comprobación directa de presencia."+#: src/control_center/sections/display.zig+msgid "This display changes variable refresh only with a mode switch: choose Always or Off."+msgstr "Esta pantalla solo cambia la frecuencia variable con un cambio de modo: elige Siempre o Desactivado."+#: src/control_center/sections/printers_tools.zigmsgid "This driver does not expose the suggested resolution as a queue setting. Review its quality or driver choices."msgstr "Este controlador no permite configurar la resolución sugerida en la cola. Revisa sus opciones de calidad o controlador."@@ -6500,6 +6512,11 @@ msgstr "Usuarios"msgid "Uses the main theme. Apply again after changing it; restart apps to see the colors."msgstr "Usa el tema principal. Vuelve a aplicar tras cambiarlo; reinicia las aplicaciones para ver los colores."+#: src/control_center/search_index.zig+#: src/control_center/sections/display.zig+msgid "Variable refresh rate"+msgstr "Frecuencia de actualización variable"+#: src/control_center/sections/desktop.zigmsgid "Vertical Pan"msgstr "Desplazamiento vertical"@@ -6532,6 +6549,10 @@ msgstr "Subir volumen"msgid "Volume, microphones and output devices."msgstr "Volumen, micrófonos y dispositivos de salida."+#: src/control_center/search_index.zig+msgid "vrr freesync gsync adaptive sync game"+msgstr "vrr freesync gsync sincronización adaptativa juego"+#: src/control_center/sections/network.zigmsgid "WPA2 / WPA3 Personal"msgstr "WPA2 / WPA3 Personal"diff --git a/po/fr.po b/po/fr.poindex 6ac21bb..40d218a 100644--- a/po/fr.po+++ b/po/fr.po@@ -144,6 +144,10 @@ msgstr "Une file brute transmet les commandes sans modification ; l'impressionmsgid "A toolkit config folder is a symlink. Apply the colors in its real location, or make it a regular folder."msgstr "Un dossier de configuration de la boîte à outils est un lien symbolique. Appliquez les couleurs à son emplacement réel ou remplacez-le par un dossier ordinaire."+#: src/control_center/sections/display.zig+msgid "Always"+msgstr "Toujours"+#: src/control_center/sections/appearance.zigmsgid "APPEARANCE"msgstr "APPARENCE"@@ -3877,6 +3881,10 @@ msgstr "Non précisé"msgid "Not supported"msgstr "Non pris en charge"+#: src/control_center/sections/display.zig+msgid "Not supported by this display"+msgstr "Non pris en charge par cet écran"+#: src/files/app_places.zigmsgid "Nothing to add to Places"msgstr "Rien à ajouter aux emplacements"@@ -6047,6 +6055,10 @@ msgstr "Le pilote actuel ne propose pas de valeur par défaut sélectionnable pomsgid "This connection has no direct presence check."msgstr "Cette connexion ne permet pas de vérifier directement la présence."+#: src/control_center/sections/display.zig+msgid "This display changes variable refresh only with a mode switch: choose Always or Off."+msgstr "Cet écran ne change le rafraîchissement variable qu’avec un changement de mode : choisissez Toujours ou Désactivé."+#: src/control_center/sections/printers_tools.zigmsgid "This driver does not expose the suggested resolution as a queue setting. Review its quality or driver choices."msgstr "Ce pilote ne propose pas la résolution suggérée comme paramètre de file. Vérifiez ses options de qualité ou choisissez un autre pilote."@@ -6503,6 +6515,11 @@ msgstr "Utilisateurs"msgid "Uses the main theme. Apply again after changing it; restart apps to see the colors."msgstr "Utilise le thème principal. Appliquez de nouveau après toute modification ; redémarrez les applications pour voir les couleurs."+#: src/control_center/search_index.zig+#: src/control_center/sections/display.zig+msgid "Variable refresh rate"+msgstr "Taux de rafraîchissement variable"+#: src/control_center/sections/desktop.zigmsgid "Vertical Pan"msgstr "Déplacement vertical"@@ -6535,6 +6552,10 @@ msgstr "Augmenter le volume"msgid "Volume, microphones and output devices."msgstr "Volume, microphones et périphériques de sortie."+#: src/control_center/search_index.zig+msgid "vrr freesync gsync adaptive sync game"+msgstr "vrr freesync gsync synchronisation adaptative jeu"+#: src/control_center/sections/network.zigmsgid "WPA2 / WPA3 Personal"msgstr "WPA2 / WPA3 personnel"diff --git a/po/pt_BR.po b/po/pt_BR.poindex 3f31199..9966238 100644--- a/po/pt_BR.po+++ b/po/pt_BR.po@@ -141,6 +141,10 @@ msgstr "Uma fila sem processamento transmite os comandos sem alterações; imprimsgid "A toolkit config folder is a symlink. Apply the colors in its real location, or make it a regular folder."msgstr "A pasta de configuração de um toolkit é um link simbólico. Aplique as cores no local real ou transforme-a em uma pasta comum."+#: src/control_center/sections/display.zig+msgid "Always"+msgstr "Sempre"+#: src/control_center/sections/appearance.zigmsgid "APPEARANCE"msgstr "APARÊNCIA"@@ -3874,6 +3878,10 @@ msgstr "Não especificado"msgid "Not supported"msgstr "Não suportado"+#: src/control_center/sections/display.zig+msgid "Not supported by this display"+msgstr "Não compatível com esta tela"+#: src/files/app_places.zigmsgid "Nothing to add to Places"msgstr "Nada para adicionar a Locais"@@ -6044,6 +6052,10 @@ msgstr "Este recurso não tem um padrão de fila selecionável no driver atual."msgid "This connection has no direct presence check."msgstr "Esta conexão não tem uma verificação direta de presença."+#: src/control_center/sections/display.zig+msgid "This display changes variable refresh only with a mode switch: choose Always or Off."+msgstr "Esta tela só muda a taxa variável com uma troca de modo: escolha Sempre ou Desativado."+#: src/control_center/sections/printers_tools.zigmsgid "This driver does not expose the suggested resolution as a queue setting. Review its quality or driver choices."msgstr "Este driver não permite configurar a resolução sugerida na fila. Revise suas opções de qualidade ou driver."@@ -6500,6 +6512,11 @@ msgstr "Usuários"msgid "Uses the main theme. Apply again after changing it; restart apps to see the colors."msgstr "Usa o tema principal. Aplique novamente após alterá-lo; reinicie os aplicativos para ver as cores."+#: src/control_center/search_index.zig+#: src/control_center/sections/display.zig+msgid "Variable refresh rate"+msgstr "Taxa de atualização variável"+#: src/control_center/sections/desktop.zigmsgid "Vertical Pan"msgstr "Deslocamento vertical"@@ -6532,6 +6549,10 @@ msgstr "Aumentar volume"msgid "Volume, microphones and output devices."msgstr "Volume, microfones e dispositivos de saída."+#: src/control_center/search_index.zig+msgid "vrr freesync gsync adaptive sync game"+msgstr "vrr freesync gsync sincronização adaptativa jogo"+#: src/control_center/sections/network.zigmsgid "WPA2 / WPA3 Personal"msgstr "WPA2 / WPA3 Pessoal"diff --git a/po/rediwm.pot b/po/rediwm.potindex 4559f0c..1464ff9 100644--- a/po/rediwm.pot+++ b/po/rediwm.pot@@ -342,6 +342,7 @@ msgid "Alt+Shift"msgstr ""#: src/control_center/sections/input_sources.zig+#: src/control_center/sections/display.zigmsgid "Always"msgstr ""@@ -610,6 +611,7 @@ msgid "Auto-join this network"msgstr ""#: src/control_center/sections/input_sources.zig+#: src/control_center/sections/display.zigmsgid "Automatic"msgstr ""@@ -4661,6 +4663,10 @@ msgstr ""msgid "Not supported"msgstr ""+#: src/control_center/sections/display.zig+msgid "Not supported by this display"+msgstr ""+#: src/files/app_places.zigmsgid "Nothing to add to Places"msgstr ""@@ -4702,6 +4708,7 @@ msgid "OK"msgstr ""#: src/control_center/sections/appearance.zig+#: src/control_center/sections/display.zigmsgid "Off"msgstr ""@@ -7136,6 +7143,10 @@ msgstr ""msgid "This connection has no direct presence check."msgstr ""+#: src/control_center/sections/display.zig+msgid "This display changes variable refresh only with a mode switch: choose Always or Off."+msgstr ""+#: src/control_center/sections/printers_tools.zigmsgid "This driver does not expose the suggested resolution as a queue setting. Review its quality or driver choices."msgstr ""@@ -7632,6 +7643,11 @@ msgstr ""msgid "Uses the main theme. Apply again after changing it; restart apps to see the colors."msgstr ""+#: src/control_center/search_index.zig+#: src/control_center/sections/display.zig+msgid "Variable refresh rate"+msgstr ""+#: src/control_center/search_index.zigmsgid "VPN"msgstr ""@@ -7668,6 +7684,10 @@ msgstr ""msgid "Volume, microphones and output devices."msgstr ""+#: src/control_center/search_index.zig+msgid "vrr freesync gsync adaptive sync game"+msgstr ""+#: src/control_center/sections/network.zigmsgid "WPA2 / WPA3 Personal"msgstr ""@@ -8997,4 +9017,3 @@ msgstr ""msgctxt "polkit"msgid "Authentication is required to manage login accounts"msgstr ""-diff --git a/po/ru.po b/po/ru.poindex bee006b..973d7c5 100644--- a/po/ru.po+++ b/po/ru.po@@ -144,6 +144,10 @@ msgstr "Очередь без драйвера передаёт командыmsgid "A toolkit config folder is a symlink. Apply the colors in its real location, or make it a regular folder."msgstr "Папка настроек графического инструментария является символической ссылкой. Примените цвета по её настоящему пути или замените ссылку обычной папкой."+#: src/control_center/sections/display.zig+msgid "Always"+msgstr "Всегда"+#: src/control_center/sections/appearance.zigmsgid "APPEARANCE"msgstr "ОФОРМЛЕНИЕ"@@ -3879,6 +3883,10 @@ msgstr "Не указано"msgid "Not supported"msgstr "Не поддерживается"+#: src/control_center/sections/display.zig+msgid "Not supported by this display"+msgstr "Не поддерживается этим дисплеем"+#: src/files/app_places.zigmsgid "Nothing to add to Places"msgstr "Нет объектов для добавления в «Места»"@@ -6050,6 +6058,10 @@ msgstr "Для этой возможности текущий драйвер нmsgid "This connection has no direct presence check."msgstr "Для этого подключения нет прямой проверки наличия."+#: src/control_center/sections/display.zig+msgid "This display changes variable refresh only with a mode switch: choose Always or Off."+msgstr "Этот дисплей меняет переменную частоту только со сменой режима: выберите «Всегда» или «Выкл.»."+#: src/control_center/sections/printers_tools.zigmsgid "This driver does not expose the suggested resolution as a queue setting. Review its quality or driver choices."msgstr "Этот драйвер не позволяет выбрать предлагаемое разрешение в настройках очереди. Проверьте параметры качества или выберите другой драйвер."@@ -6506,6 +6518,11 @@ msgstr "Пользователи"msgid "Uses the main theme. Apply again after changing it; restart apps to see the colors."msgstr "Используется основная тема. Примените повторно после её изменения; перезапустите приложения, чтобы увидеть цвета."+#: src/control_center/search_index.zig+#: src/control_center/sections/display.zig+msgid "Variable refresh rate"+msgstr "Переменная частота обновления"+#: src/control_center/sections/desktop.zigmsgid "Vertical Pan"msgstr "Вертикальное перемещение"@@ -6538,6 +6555,10 @@ msgstr "Увеличить громкость"msgid "Volume, microphones and output devices."msgstr "Громкость, микрофоны и устройства вывода."+#: src/control_center/search_index.zig+msgid "vrr freesync gsync adaptive sync game"+msgstr "vrr freesync gsync адаптивная синхронизация игра"+#: src/control_center/sections/network.zigmsgid "WPA2 / WPA3 Personal"msgstr "WPA2 / WPA3 Personal"diff --git a/src/Output.zig b/src/Output.zigindex 8f83d65..1f3304a 100644--- a/src/Output.zig+++ b/src/Output.zig@@ -21,6 +21,7 @@ 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");+const output_vrr = @import("output/vrr.zig");pub const wlr_color_transform_init_lut_3x1d = wlr.color.transformInitLut3x1d;pub const wlr_color_transform_unref = wlr.color.transformUnref;@@ -115,6 +116,8 @@ callback_idle: ?*wl.EventSource = null,callback_frame_seq: u64 = 0,/// Asynchronous page flips for a game window (`output/tearing.zig`).tearing: output_tearing.State = .{},+/// Adaptive sync for the `[[outputs]] adaptive_sync` mode (`output/vrr.zig`).+vrr: output_vrr.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@@ -524,6 +527,7 @@ 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);output_tearing.deinit(output);+ output_vrr.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 f3fb75a..ad1601e 100644--- a/src/config/default.zig+++ b/src/config/default.zig@@ -319,6 +319,7 @@ pub const source =\\# enabled = true # set false to keep this monitor disabled\\# primary = true # preferred fallback output\\# transform = "normal" # normal, 90, 180, 270, or flipped variants+ \\# adaptive_sync = "auto" # variable refresh: "auto" while a game fills it, "off", "always"\\#\\# [[outputs]]\\# name = "DP-2"diff --git a/src/config/loader.zig b/src/config/loader.zigindex 9ea2835..a20438c 100644--- a/src/config/loader.zig+++ b/src/config/loader.zig@@ -68,6 +68,7 @@ pub const parseString = loader_fields.parseString;pub const unquoteKey = loader_fields.unquoteKey;pub const outputsLayoutEql = loader_compare.outputsLayoutEql;pub const outputsColorEql = loader_compare.outputsColorEql;+pub const outputsAdaptiveSyncEql = loader_compare.outputsAdaptiveSyncEql;pub const outputsEql = loader_compare.outputsEql;pub const nightLightEql = loader_compare.nightLightEql;pub const wheelAccel = loader_compare.wheelAccel;@@ -306,6 +307,7 @@ pub const OutputConfig = struct {/// Preferred fallback output for placement and desktop ownership.primary: bool = false,transform: output_transform.Transform = .normal,+ adaptive_sync: @import("output_config.zig").AdaptiveSync = .auto,night_light: bool = true,gamma: f32 = 1.0,};diff --git a/src/config/loader_compare.zig b/src/config/loader_compare.zigindex 4c1442d..a02ee33 100644--- a/src/config/loader_compare.zig+++ b/src/config/loader_compare.zig@@ -20,6 +20,14 @@ pub fn outputsLayoutEql(a: []const OutputConfig, b: []const OutputConfig) bool {return true;}+pub fn outputsAdaptiveSyncEql(a: []const OutputConfig, b: []const OutputConfig) bool {+ if (a.len != b.len) return false;+ for (a, b) |left, right| {+ if (!std.mem.eql(u8, left.name, right.name) or left.adaptive_sync != right.adaptive_sync) return false;+ }+ return true;+}+pub fn outputsColorEql(a: []const OutputConfig, b: []const OutputConfig) bool {if (a.len != b.len) return false;for (a, b) |left, right| {diff --git a/src/config/loader_fields.zig b/src/config/loader_fields.zigindex 93075e3..3e920b2 100644--- a/src/config/loader_fields.zig+++ b/src/config/loader_fields.zig@@ -200,6 +200,7 @@ pub const output_rules: std.enums.EnumFieldStruct(std.meta.FieldEnum(OutputConfi.enabled = .boolean,.primary = .boolean,.transform = .output_transform,+ .adaptive_sync = .enumeration,.night_light = .boolean,.gamma = .{ .float = .{ .min = 0.5, .max = 2.0 } },};diff --git a/src/config/output_config.zig b/src/config/output_config.zigindex 1830d09..57e5084 100644--- a/src/config/output_config.zig+++ b/src/config/output_config.zig@@ -1,6 +1,10 @@const std = @import("std");const output_transform = @import("output_transform.zig");+/// Variable refresh rate (FreeSync, G-Sync Compatible, Adaptive-Sync) per+/// output: on only while a game fills it, never, or always.+pub const AdaptiveSync = enum { off, auto, always };+/// Omitted fields retain their saved value. Automatic settings explicitly clear overrides.pub const Patch = struct {output: []const u8 = "",@@ -15,6 +19,7 @@ pub const Patch = struct {enabled: ?bool = null,primary: ?bool = null,transform: ?output_transform.Transform = null,+ adaptive_sync: ?AdaptiveSync = null,pub fn validate(p: Patch) !void {inline for (.{ "width", "height", "refresh_mhz" }) |field| {@@ -30,7 +35,7 @@ pub const Patch = struct {}if (p.width == null and p.height == null and p.refresh_mhz == null andp.x == null and p.y == null and p.scale == null and !p.auto_scale and !p.auto_position and- p.enabled == null and p.primary == null and p.transform == null)+ p.enabled == null and p.primary == null and p.transform == null and p.adaptive_sync == null)return error.EmptyOutputConfig;}};diff --git a/src/config/output_save.zig b/src/config/output_save.zigindex cdacbd8..d82546a 100644--- a/src/config/output_save.zig+++ b/src/config/output_save.zig@@ -43,6 +43,11 @@ pub fn prepare(allocator: std.mem.Allocator, io: Io, path: []const u8, name: []cdefer allocator.free(line);try fields_list.appendSlice(allocator, line);}+ if (patch.adaptive_sync) |value| {+ const line = try std.fmt.allocPrint(allocator, "adaptive_sync = \"{s}\"\n", .{@tagName(value)});+ defer allocator.free(line);+ try fields_list.appendSlice(allocator, line);+ }if (patch.enabled) |value| try fields_list.appendSlice(allocator, if (value) "enabled = true\n" else "enabled = false\n");if (patch.primary) |value| try fields_list.appendSlice(allocator, if (value) "primary = true\n" else "primary = false\n");if (patch.auto_scale) try fields_list.appendSlice(allocator, "scale = \"auto\"\n");@@ -142,6 +147,7 @@ fn appendBlock(allocator: std.mem.Allocator, result: *std.ArrayList(u8), block:if (std.mem.eql(u8, key, field) and @field(patch, field) != null) break :blk true;}if (patch.transform != null and std.mem.eql(u8, key, "transform")) break :blk true;+ if (patch.adaptive_sync != null and std.mem.eql(u8, key, "adaptive_sync")) break :blk true;if (patch.auto_scale and std.mem.eql(u8, key, "scale")) break :blk true;if (patch.auto_position and (std.mem.eql(u8, key, "x") or std.mem.eql(u8, key, "y"))) break :blk true;if (patch.enabled != null and std.mem.eql(u8, key, "enabled")) break :blk true;diff --git a/src/config_runtime/apply.zig b/src/config_runtime/apply.zigindex 6f93485..021b8fa 100644--- a/src/config_runtime/apply.zig+++ b/src/config_runtime/apply.zig@@ -48,6 +48,8 @@ pub fn applyDiff(server: *Server, old: Config, new: Config) void {while (output_it.next()) |output| output.applyConfig();@import("../Output.zig").syncLayout(server);}+ // Adaptive sync is decided per frame (output/vrr.zig); a frame applies it.+ if (!loader.outputsAdaptiveSyncEql(old.outputs, new.outputs)) server.scheduleFrames();if (!outputsColorEql(old.outputs, new.outputs) or !nightLightEql(old.night_light, new.night_light)) {server.night_light.reconfigure(new.night_light);}diff --git a/src/control_center/relayout.zig b/src/control_center/relayout.zigindex e07323e..e4c1062 100644--- a/src/control_center/relayout.zig+++ b/src/control_center/relayout.zig@@ -97,6 +97,12 @@ pub fn applyPending(cc: *ControlCenter) void {cc.relayout();cc.requestRepaint();}+ if (display_section.pendingAdaptiveSync(&cc.display)) |mode| {+ const output = @import("../Output.zig").fromWlr(cc.selectedDisplayOutput() orelse return) orelse return;+ cc.applyOutputPatch(output, .{ .adaptive_sync = mode });+ cc.relayout();+ cc.requestRepaint();+ }}if (cc.pending_page) |page| {cc.pending_page = null;diff --git a/src/control_center/search_index.zig b/src/control_center/search_index.zigindex 2ff7e09..5879cec 100644--- a/src/control_center/search_index.zig+++ b/src/control_center/search_index.zig@@ -72,6 +72,7 @@ const source_entries = [_]SourceEntry{.{ .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("Variable refresh rate"), .target = "adaptive_sync", .keywords = i18n.msg("vrr freesync gsync adaptive sync game") },.{ .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 2d70387..5eab8ad 100644--- a/src/control_center/sections/display.zig+++ b/src/control_center/sections/display.zig@@ -14,6 +14,7 @@ const panel = @import("../panel.zig");const setting_save = @import("config").setting_save;const output_transform = @import("config").output_transform;const Output = @import("../../Output.zig");+const vrr = @import("../../output/vrr.zig");/// Row slots; every access goes through these so inserting a row cannot leave/// a stale index reading a `.select` widget as `.text` (a live-session panic).@@ -23,8 +24,9 @@ const row_refresh = 2;const row_scale = 3;const row_xwayland = 4;const row_transform = 5;-const row_name = 6;-const row_count = 7;+const row_adaptive_sync = 6;+const row_name = 7;+const row_count = 8;const scale_labels = blk: {@setEvalBranchQuota(20000);var labels: [42][]const u8 = undefined;@@ -46,6 +48,8 @@ const LidAction = @import("config").loader.LidAction;/// In `LidAction` order.const lid_labels = [_]i18n.Message{ i18n.msg("Turn off screen"), i18n.msg("Lock"), i18n.msg("Sleep"), i18n.msg("Do nothing") };const transform_labels = [_]i18n.Message{ i18n.msg("Normal"), i18n.msg("90°"), i18n.msg("180°"), i18n.msg("270°"), i18n.msg("Flipped"), i18n.msg("Flipped 90°"), i18n.msg("Flipped 180°"), i18n.msg("Flipped 270°") };+/// In `AdaptiveSync` order: off, auto, always.+const adaptive_sync_labels = [_]i18n.Message{ i18n.msg("Off"), i18n.msg("Automatic"), i18n.msg("Always") };const row_height: f32 = 40;const nl_temp_min: f32 = 1700;const nl_temp_max: f32 = 10000;@@ -61,6 +65,7 @@ pub const Section = struct {initial_scale: ?usize = null,initial_xwayland_scale: ?usize = null,initial_transform: ?usize = null,+ initial_adaptive_sync: ?usize = null,monitor_labels: [][]const u8 = &.{},monitor_names: [][]const u8 = &.{},initial_monitor: ?usize = null,@@ -152,6 +157,7 @@ pub fn build(out: *Section, cc: *panel.ControlCenter, wlr_output: *wlr.Output) vout.initial_resolution = null;out.initial_rate = null;out.initial_transform = null;+ out.initial_adaptive_sync = null;out.monitor_labels = &.{};out.monitor_names = &.{};out.initial_monitor = null;@@ -174,6 +180,7 @@ pub fn build(out: *Section, cc: *panel.ControlCenter, wlr_output: *wlr.Output) vsetRow(out, row_xwayland, i18n.tr("Xwayland scale (global)"), "", .{});const current_transform = transformFromWl(wlr_output.transform);setRow(out, row_transform, i18n.tr("Transform"), "{s}", .{output_transform.name(current_transform)});+ setRow(out, row_adaptive_sync, i18n.tr("Variable refresh rate"), "{s}", .{i18n.tr("Not supported by this display")});setRow(out, row_name, i18n.tr("Output name"), "{s}", .{name});buildScales(out, wlr_output);@@ -182,11 +189,14 @@ pub fn build(out: *Section, cc: *panel.ControlCenter, wlr_output: *wlr.Output) vout.rates = &.{};};buildTransforms(out, current_transform);+ const vrr_output = Output.fromWlr(wlr_output);+ if (vrr_output) |output| buildAdaptiveSync(out, output);+ const vrr_note = if (vrr_output) |output| output.vrr.needs_modeset and vrr.mode(output) == .auto else false;const pal = panel.palette();out.top_children = .{.{ .kind = .{ .text = .{ .content = i18n.tr("DISPLAY"), .font_size = 12, .weight = 700, .color = pal.dim } } },.{ .kind = .container, .direction = .column, .gap = 12, .children = &out.row_storage },- .{ .kind = .{ .text = .{ .content = if (out.failed) i18n.tr("Could not apply that display setting.") else if (out.save_failed) i18n.tr("Could not save the display setting.") else if (wlr_output.modes.empty()) i18n.tr("This output does not advertise editable display modes.") else i18n.tr("Changes are saved automatically. Scroll the lists for more modes."), .font_size = 12, .color = pal.dim } } },+ .{ .kind = .{ .text = .{ .content = if (out.failed) i18n.tr("Could not apply that display setting.") else if (out.save_failed) i18n.tr("Could not save the display setting.") else if (vrr_note) i18n.tr("This display changes variable refresh only with a mode switch: choose Always or Off.") else if (wlr_output.modes.empty()) i18n.tr("This output does not advertise editable display modes.") else i18n.tr("Changes are saved automatically. Scroll the lists for more modes."), .font_size = 12, .color = pal.dim } } },};out.root = .{ .kind = .container, .direction = .column, .gap = 8, .children = &out.top_children };buildNightLight(out);@@ -471,6 +481,23 @@ pub fn pendingTransform(out: *Section) ?output_transform.Transform {return @enumFromInt(selected);}+fn buildAdaptiveSync(out: *Section, output: *Output) void {+ // An unsupported display keeps the text row, unless it is on anyway.+ if (!vrr.supported(output) and !vrr.active(output)) return;+ out.initial_adaptive_sync = @intFromEnum(vrr.mode(output));+ out.row_children[row_adaptive_sync][1] = .{ .name = "adaptive_sync", .kind = .{ .select = .{+ .labels = panel.translatedLabels(&adaptive_sync_labels),+ .selected = out.initial_adaptive_sync,+ } }, .width = .{ .fixed = 190 }, .height = .{ .fixed = row_height } };+}++pub fn pendingAdaptiveSync(out: *Section) ?vrr.Mode {+ if (out.row_children[row_adaptive_sync][1].kind != .select) return null;+ const selected = out.row_children[row_adaptive_sync][1].kind.select.selected orelse return null;+ if (selected == out.initial_adaptive_sync or selected >= adaptive_sync_labels.len) return null;+ return @enumFromInt(selected);+}+pub const ScaleChange = union(enum) { auto, factor: f32 };pub fn pendingScale(out: *Section) ?ScaleChange {diff --git a/src/ipc/commands.zig b/src/ipc/commands.zigindex 1802a30..be8ad8d 100644--- a/src/ipc/commands.zig+++ b/src/ipc/commands.zig@@ -725,11 +725,11 @@ pub const specs = [_]CommandSpec{.{.id = .set_output_config,.kind = .action,- .description = "Apply and persist output mode, transform, position, scale and enable policy; auto clears scale or position overrides",- .params_schema = "{\"output\": string, \"width\"?: number, \"height\"?: number, \"refresh_mhz\"?: number, \"transform\"?: string, \"x\"?: number, \"y\"?: number, \"scale\"?: number | \"auto\", \"position\"?: \"auto\", \"enabled\"?: boolean, \"primary\"?: boolean}",+ .description = "Apply and persist output mode, transform, position, scale, variable refresh and enable policy; auto clears scale or position overrides",+ .params_schema = "{\"output\": string, \"width\"?: number, \"height\"?: number, \"refresh_mhz\"?: number, \"transform\"?: string, \"adaptive_sync\"?: \"off\" | \"auto\" | \"always\", \"x\"?: number, \"y\"?: number, \"scale\"?: number | \"auto\", \"position\"?: \"auto\", \"enabled\"?: boolean, \"primary\"?: boolean}",.units = "width/height: device pixels; refresh_mhz: millihertz; x/y: logical pixels; scale: 1–3",.description_order = 83,- .cli = .{ .name = "output-config", .synopsis = "<output> [--width <PX>] [--height <PX>] [--refresh-mhz <MHZ>] [--transform <normal|90|180|270|flipped|flipped_90|flipped_180|flipped_270>] [--x <X>] [--y <Y>] [--scale <1..3|auto>] [--position auto] [--enabled|--disabled] [--primary|--no-primary]" },+ .cli = .{ .name = "output-config", .synopsis = "<output> [--width <PX>] [--height <PX>] [--refresh-mhz <MHZ>] [--transform <normal|90|180|270|flipped|flipped_90|flipped_180|flipped_270>] [--adaptive-sync <off|auto|always>] [--x <X>] [--y <Y>] [--scale <1..3|auto>] [--position auto] [--enabled|--disabled] [--primary|--no-primary]" },},.{.id = .get_text_input,diff --git a/src/ipc/handlers_data.zig b/src/ipc/handlers_data.zigindex 12c3388..d1fa755 100644--- a/src/ipc/handlers_data.zig+++ b/src/ipc/handlers_data.zig@@ -6,6 +6,7 @@ const Server = @import("../Server.zig");const Output = @import("../Output.zig");const Toplevel = @import("../Toplevel.zig");const output_tearing = @import("../output/tearing.zig");+const output_vrr = @import("../output/vrr.zig");const stats = @import("stats.zig");const protocol = @import("protocol.zig");const ui = @import("ui");@@ -199,6 +200,11 @@ pub fn makeOutputData(server: *Server, output: *Output) protocol.OutputData {.tearing_allowed = output_tearing.wanted(output),.tearing_active = output.tearing.active,.tearing_paused = output_tearing.paused(output),+ .adaptive_sync = @tagName(output_vrr.mode(output)),+ .adaptive_sync_supported = output_vrr.supported(output),+ .adaptive_sync_wanted = output_vrr.wanted(output),+ .adaptive_sync_active = output_vrr.active(output),+ .adaptive_sync_needs_modeset = output.vrr.needs_modeset,.direct_scanout = if (server.scene_outputs.get(output.wlr_output)) |scene_output| scene_output.directScanout() else false,};}diff --git a/src/ipc/protocol_data.zig b/src/ipc/protocol_data.zigindex 84fb4ac..227a302 100644--- a/src/ipc/protocol_data.zig+++ b/src/ipc/protocol_data.zig@@ -179,6 +179,17 @@ pub const OutputData = struct {tearing_paused: bool = false,/// The last frame scanned a client buffer out directly.direct_scanout: bool = false,+ /// `[[outputs]] adaptive_sync`: "off", "auto" or "always".+ adaptive_sync: []const u8 = "auto",+ /// The display and driver can run at a variable refresh rate.+ adaptive_sync_supported: bool = false,+ /// The setting asks for variable refresh now (a game fills the output in+ /// "auto"), whether or not the display can.+ adaptive_sync_wanted: bool = false,+ /// Variable refresh is on.+ adaptive_sync_active: bool = false,+ /// The driver cannot switch it without a modeset, so "auto" leaves it.+ adaptive_sync_needs_modeset: bool = false,};pub const WorkspaceData = struct {diff --git a/src/ipc/protocol_params.zig b/src/ipc/protocol_params.zigindex bbe3f70..e6eec1e 100644--- a/src/ipc/protocol_params.zig+++ b/src/ipc/protocol_params.zig@@ -599,6 +599,10 @@ pub fn parseActionParams(allocator: std.mem.Allocator, command_tag: commands.Rouif (value != .string) return error.InvalidRequest;patch.transform = output_transform.parseName(value.string) catch return error.InvalidRequest;}+ if (p.get("adaptive_sync")) |value| {+ if (value != .string) return error.InvalidRequest;+ patch.adaptive_sync = std.meta.stringToEnum(@import("config").output_config.AdaptiveSync, value.string) orelse return error.InvalidRequest;+ }patch.validate() catch return error.InvalidRequest;return .{ .set_output_config = patch };},diff --git a/src/ipc/protocol_stringify.zig b/src/ipc/protocol_stringify.zigindex 2855a09..4983f22 100644--- a/src/ipc/protocol_stringify.zig+++ b/src/ipc/protocol_stringify.zig@@ -876,6 +876,9 @@ pub fn stringifyOutput(out: OutputData, writer: anytype) !void {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.writeAll(",\"adaptive_sync\":");+ try writer.print("{f}", .{std.json.fmt(out.adaptive_sync, .{})});+ try writer.print(",\"adaptive_sync_supported\":{},\"adaptive_sync_wanted\":{},\"adaptive_sync_active\":{},\"adaptive_sync_needs_modeset\":{}", .{ out.adaptive_sync_supported, out.adaptive_sync_wanted, out.adaptive_sync_active, out.adaptive_sync_needs_modeset });try writer.writeByte('}');}diff --git a/src/ipc_serializers.jsonl b/src/ipc_serializers.jsonlindex eae7365..7a67713 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,"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":{"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,"adaptive_sync":"text \"quoted\"\n\\","adaptive_sync_supported":false,"adaptive_sync_wanted":false,"adaptive_sync_active":false,"adaptive_sync_needs_modeset":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,"adaptive_sync":"text \"quoted\"\n\\","adaptive_sync_supported":true,"adaptive_sync_wanted":true,"adaptive_sync_active":true,"adaptive_sync_needs_modeset":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,"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":{"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,"adaptive_sync":"text \"quoted\"\n\\","adaptive_sync_supported":false,"adaptive_sync_wanted":false,"adaptive_sync_active":false,"adaptive_sync_needs_modeset":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,"adaptive_sync":"text \"quoted\"\n\\","adaptive_sync_supported":true,"adaptive_sync_wanted":true,"adaptive_sync_active":true,"adaptive_sync_needs_modeset":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}}}diff --git a/src/msg/msg_parse.zig b/src/msg/msg_parse.zigindex 8872939..00c57d3 100644--- a/src/msg/msg_parse.zig+++ b/src/msg/msg_parse.zig@@ -270,6 +270,8 @@ pub fn parseCommand(cli: FlagParser, arg: []const u8) !void {patch.auto_position = true;} else if (std.mem.eql(u8, option, "--transform")) {patch.transform = protocol.parseOutputTransform(value) catch return error.InvalidTransform;+ } else if (std.mem.eql(u8, option, "--adaptive-sync")) {+ patch.adaptive_sync = std.meta.stringToEnum(@typeInfo(@TypeOf(patch.adaptive_sync)).optional.child, value) orelse return error.InvalidAdaptiveSync;} else {var matched = false;inline for (.{ "width", "height", "refresh_mhz", "x", "y" }, .{ "--width", "--height", "--refresh-mhz", "--x", "--y" }) |field, flag| {diff --git a/src/msg/msg_request.zig b/src/msg/msg_request.zigindex 89f899b..1773f68 100644--- a/src/msg/msg_request.zig+++ b/src/msg/msg_request.zig@@ -332,6 +332,7 @@ pub fn buildRequest(allocator: std.mem.Allocator, command: Command) !std.ArrayLiif (p.enabled) |value| try bw.print(",\"enabled\":{s}", .{if (value) "true" else "false"});if (p.primary) |value| try bw.print(",\"primary\":{s}", .{if (value) "true" else "false"});if (p.transform) |value| try bw.print(",\"transform\":\"{s}\"", .{protocol.outputTransformName(value)});+ if (p.adaptive_sync) |value| try bw.print(",\"adaptive_sync\":\"{s}\"", .{@tagName(value)});try bw.writeAll("}}\n");},.maximize => |p| {diff --git a/src/output/frame.zig b/src/output/frame.zigindex b247ec4..c433844 100644--- a/src/output/frame.zig+++ b/src/output/frame.zig@@ -12,6 +12,7 @@ const stats = @import("../ipc/stats.zig");const trace = @import("frame_trace.zig");const late = @import("late.zig");const tearing = @import("tearing.zig");+const vrr = @import("vrr.zig");const wlr_color_transform_unref = Output.wlr_color_transform_unref;const log = std.log.scoped(.output);const CursorState = Output.CursorState;@@ -39,6 +40,7 @@ pub fn commitFrameState(output: *Output, state: *wlr.Output.State) bool {}}+ vrr.apply(output, state);const had_transform = state.committed.color_transform;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)) {@@ -51,7 +53,10 @@ pub fn commitFrameState(output: *Output, state: *wlr.Output.State) bool {tearing.refused(output);success = output.wlr_output.commitState(state);}- if (success) tearing.committed(output, state);+ if (success) {+ tearing.committed(output, state);+ vrr.committed(output, state);+ }if (had_transform) {if (success) {output.color.status = if (output.color.transform != null) .applied else .neutral;@@ -86,7 +91,7 @@ pub fn commitFrameState(output: *Output, state: *wlr.Output.State) bool {/// without scene damage is checked here: hardware cursor moves, output/// capture (which holds an attach-render lock) and gamma changes.pub fn commitIsRedundant(output: *Output, scene_output: *SceneOutput) bool {- if (output.vblank_timer == null or output.color.pending) return false;+ if (output.vblank_timer == null or output.color.pending or output.vrr.pending != null) return false;const wlr_output = output.wlr_output;if (!wlr_output.enabled or wlr_output.attach_render_locks > 0) return false;if (scene_output.hasPendingDamage()) return false;@@ -299,7 +304,8 @@ pub fn runFrame(output: *Output) void {const started = stats.nowNs();var state = wlr.Output.State.init();defer state.finish();- var should_commit = scene_output.needsFrame() or output.color.pending;+ const vrr_change = vrr.prepare(output);+ var should_commit = scene_output.needsFrame() or output.color.pending or vrr_change;if (should_commit and commitIsRedundant(output, scene_output)) {// `needs_frame` is a latch only a commit clears; while set,// later cursor moves or capture requests could not schedule.diff --git a/src/output/vrr.zig b/src/output/vrr.zignew file mode 100644index 0000000..b675563--- /dev/null+++ b/src/output/vrr.zig@@ -0,0 +1,145 @@+//! Adaptive sync (VRR) on an `Output`: the `[[outputs]] adaptive_sync` mode+//! applied through `vrr_policy.zig`, decided before each frame and carried by+//! that frame's commit, never a separate one.+//!+//! A driver that cannot switch VRR_ENABLED without a modeset fails the test+//! commit. `auto` then stops switching on this output and mode (reported as+//! `needs_modeset`, Settings recommends Always or Off); an explicit `always`+//! or `off` is applied with a modeset of the current mode. A switch the+//! driver refuses, or enabling that comes back disabled, is remembered per+//! mode.++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 policy = @import("vrr_policy.zig");+const stats = @import("../ipc/stats.zig");+const log = std.log.scoped(.output);++pub const Mode = policy.Mode;++const ModeKey = struct { width: i32 = 0, height: i32 = 0, refresh: i32 = 0 };++pub const State = struct {+ debounce: policy.Debounce = .{},+ /// The adaptive sync state the next commit requests.+ pending: ?bool = null,+ /// `auto` cannot switch here without a modeset (this mode).+ needs_modeset: bool = false,+ /// Switching failed in this mode even with a modeset, or enabling came+ /// back off: no more attempts until the mode or the setting changes.+ refused: bool = false,+ /// The display mode and setting the two flags above belong to.+ key: ModeKey = .{},+ mode: Mode = .auto,+ timer: ?*wl.EventSource = null,+};++/// The configured mode for this output.+pub fn mode(output: *Output) Mode {+ return if (Output.configured(output.server, output.wlr_output)) |config| config.adaptive_sync else .auto;+}++pub fn supported(output: *Output) bool {+ return output.wlr_output.adaptive_sync_supported;+}++pub fn active(output: *Output) bool {+ return output.wlr_output.adaptive_sync_status == .enabled;+}++/// What the setting asks for now, whether or not the display can.+pub fn wanted(output: *Output) bool {+ const server = output.server;+ return policy.wanted(.{+ .mode = mode(output),+ .game = game.window(output) != null,+ .blocked = server.greeter_mode or output.power_off or !output.wlr_output.enabled,+ });+}++/// Before a frame: decides whether its commit changes adaptive sync, and+/// returns true if so (the frame must then commit).+pub fn prepare(output: *Output) bool {+ const state = &output.vrr;+ const wlr_output = output.wlr_output;+ const key: ModeKey = .{ .width = wlr_output.width, .height = wlr_output.height, .refresh = wlr_output.refresh };+ const configured = mode(output);+ if (!std.meta.eql(key, state.key) or configured != state.mode) {+ state.* = .{ .timer = state.timer, .key = key, .mode = configured };+ }+ state.pending = null;+ if (state.refused or (configured == .auto and state.needs_modeset)) return false;+ const want = wanted(output) and (supported(output) or active(output));+ const step = state.debounce.step(want, active(output), stats.nowNs());+ if (step.wake_ns) |due| arm(output, due);+ state.pending = step.apply;+ return state.pending != null;+}++/// Puts the decided change on the frame state, if the driver takes it.+pub fn apply(output: *Output, state: *wlr.Output.State) void {+ const enable = output.vrr.pending orelse return;+ output.vrr.pending = null;+ const wlr_output = output.wlr_output;+ var copy = state.*;+ copy.setAdaptiveSyncEnabled(enable);+ if (wlr_output.testState(©)) {+ state.setAdaptiveSyncEnabled(enable);+ return;+ }+ const name = wlr_output.name;+ if (output.vrr.mode == .auto) {+ output.vrr.needs_modeset = true;+ log.info("output '{s}': adaptive sync cannot be switched without a modeset; Automatic leaves it {s}", .{ name, if (active(output)) "on" else "off" });+ return;+ }+ // An explicit choice may cost a modeset: commit the current mode with it.+ if (wlr_output.current_mode) |current| {+ copy.setMode(current);+ if (wlr_output.testState(©)) {+ state.setMode(current);+ state.setAdaptiveSyncEnabled(enable);+ log.info("output '{s}': adaptive sync {s} with a modeset", .{ name, if (enable) "on" else "off" });+ return;+ }+ }+ // Stop for this mode either way: each retry costs two test commits.+ output.vrr.refused = true;+ log.warn("output '{s}': the driver refused to turn adaptive sync {s} in this mode", .{ name, if (enable) "on" else "off" });+}++/// A frame state was committed.+pub fn committed(output: *Output, state: *const wlr.Output.State) void {+ if (!state.committed.adaptive_sync_enabled) return;+ if (state.adaptive_sync_enabled and !active(output)) {+ output.vrr.refused = true;+ log.warn("output '{s}': adaptive sync was requested but stays off in this mode", .{output.wlr_output.name});+ return;+ }+ log.debug("output '{s}': adaptive sync {s}", .{ output.wlr_output.name, if (active(output)) "on" else "off" });+}++/// Wakes the output when a delayed change falls due (no frames may come).+fn arm(output: *Output, due_ns: u64) void {+ const timer = output.vrr.timer orelse blk: {+ const source = output.server.wl_server.getEventLoop().addTimer(*Output, onTimer, output) catch return;+ output.vrr.timer = source;+ break :blk source;+ };+ const now = stats.nowNs();+ const delay_ms: i32 = @intCast(@min((due_ns -| now) / std.time.ns_per_ms + 1, std.math.maxInt(i32)));+ timer.timerUpdate(delay_ms) catch {};+}++fn onTimer(output: *Output) c_int {+ output.wlr_output.scheduleFrame();+ return 0;+}++pub fn deinit(output: *Output) void {+ if (output.vrr.timer) |source| source.remove();+ output.vrr.timer = null;+}diff --git a/src/output/vrr_policy.zig b/src/output/vrr_policy.zignew file mode 100644index 0000000..e666c57--- /dev/null+++ b/src/output/vrr_policy.zig@@ -0,0 +1,92 @@+//! Variable refresh policy: whether an output should run at a variable rate,+//! and when a change is made. Plain data and a caller-supplied clock, so the+//! cases are tested without wlroots; `vrr.zig` connects it to an `Output`.+//!+//! `auto` turns adaptive sync on while a game fills the output and off+//! otherwise; `always` keeps it on (the desktop then runs at a variable rate+//! too, which makes some panels flicker at their minimum rate); `off` never.+//! Turning on is immediate. Turning off waits `off_delay_ns`, so Alt+Tab to a+//! chat window and back does not toggle twice.++const std = @import("std");++pub const Mode = @import("config").output_config.AdaptiveSync;++pub const off_delay_ns: u64 = 500 * std.time.ns_per_ms;++pub const Inputs = struct {+ mode: Mode,+ /// A game fills the output (`game.zig`).+ game: bool,+ /// The greeter, or an output that is off: never variable.+ blocked: bool,+};++/// What the configuration asks for now, whether or not the display can.+pub fn wanted(in: Inputs) bool {+ if (in.blocked) return false;+ return switch (in.mode) {+ .off => false,+ .always => true,+ .auto => in.game,+ };+}++pub const Step = struct {+ /// The state to request on the next commit, or null to leave it.+ apply: ?bool = null,+ /// When to look again for a delayed change (a monotonic time).+ wake_ns: ?u64 = null,+};++pub const Debounce = struct {+ /// When wanting off began while on; zero when not waiting.+ off_since_ns: u64 = 0,++ pub fn step(self: *Debounce, want: bool, active: bool, now_ns: u64) Step {+ if (want == active) {+ self.off_since_ns = 0;+ return .{};+ }+ if (want) {+ self.off_since_ns = 0;+ return .{ .apply = true };+ }+ if (self.off_since_ns == 0) self.off_since_ns = now_ns;+ const due = self.off_since_ns + off_delay_ns;+ if (now_ns >= due) {+ self.off_since_ns = 0;+ return .{ .apply = false };+ }+ return .{ .wake_ns = due };+ }+};++test "wanted follows the mode, the game and the greeter" {+ try std.testing.expect(!wanted(.{ .mode = .off, .game = true, .blocked = false }));+ try std.testing.expect(wanted(.{ .mode = .always, .game = false, .blocked = false }));+ try std.testing.expect(wanted(.{ .mode = .auto, .game = true, .blocked = false }));+ try std.testing.expect(!wanted(.{ .mode = .auto, .game = false, .blocked = false }));+ try std.testing.expect(!wanted(.{ .mode = .always, .game = true, .blocked = true }));+}++test "turning on is immediate, turning off waits and a return cancels it" {+ const ms = std.time.ns_per_ms;+ var d: Debounce = .{};+ try std.testing.expectEqual(@as(?bool, true), d.step(true, false, 1000 * ms).apply);+ try std.testing.expectEqual(Step{}, d.step(true, true, 1001 * ms));++ // The game loses focus: off is only due after the delay.+ var s = d.step(false, true, 2000 * ms);+ try std.testing.expectEqual(@as(?bool, null), s.apply);+ try std.testing.expectEqual(@as(?u64, 2500 * ms), s.wake_ns);+ s = d.step(false, true, 2300 * ms);+ try std.testing.expectEqual(@as(?u64, 2500 * ms), s.wake_ns);+ // Focus comes back in time: nothing changes, and the wait is forgotten.+ try std.testing.expectEqual(Step{}, d.step(true, true, 2400 * ms));+ s = d.step(false, true, 3000 * ms);+ try std.testing.expectEqual(@as(?u64, 3500 * ms), s.wake_ns);+ try std.testing.expectEqual(@as(?bool, false), d.step(false, true, 3500 * ms).apply);+ try std.testing.expectEqual(@as(u64, 0), d.off_since_ns);+ try std.testing.expectEqual(Step{}, d.step(false, false, 3600 * ms));+}diff --git a/src/output_management.zig b/src/output_management.zigindex f7198d9..8fa9a74 100644--- a/src/output_management.zig+++ b/src/output_management.zig@@ -147,7 +147,7 @@ const Phase = enum {fn isEmpty(p: Patch) bool {return p.enabled == null and p.width == null and p.height == null and p.refresh_mhz == null and- p.x == null and p.y == null and p.scale == null and p.transform == null;+ p.x == null and p.y == null and p.scale == null and p.transform == null and p.adaptive_sync == null;}fn findHead(config: *wlr.OutputConfigurationV1, output: *wlr.Output) ?*wlr.OutputConfigurationV1.Head {@@ -185,6 +185,11 @@ fn diff(server: *Server, output: *Output, state: *const wlr.OutputHeadV1.State)if (state.transform != out.transform) {p.transform = @enumFromInt(@intFromEnum(state.transform));}+ // Heads report whether variable refresh is on now; a client switching it+ // chooses Always or Off (`wlr-randr --adaptive-sync`).+ if (state.adaptive_sync_enabled != (out.adaptive_sync_status == .enabled)) {+ p.adaptive_sync = if (state.adaptive_sync_enabled) .always else .off;+ }return p;}diff --git a/src/ui_tests.zig b/src/ui_tests.zigindex 4581c2e..16dea2c 100644--- a/src/ui_tests.zig+++ b/src/ui_tests.zig@@ -83,6 +83,7 @@ test {_ = @import("ipc/frame_metrics.zig");_ = @import("output/late_render_tests.zig");_ = @import("output/tearing_policy.zig");+ _ = @import("output/vrr_policy.zig");_ = @import("config").keybinds;_ = @import("osd_paint.zig");_ = @import("osd.zig");diff --git a/tests/control_center.py b/tests/control_center.pyindex 2a79655..22e43d6 100644--- a/tests/control_center.py+++ b/tests/control_center.py@@ -342,6 +342,11 @@ 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())+ # Headless cannot run variable refresh: the row says so+ # instead of offering Off/Automatic/Always.+ assert any(w["label"] == "Variable refresh rate" for w in widgets())+ assert any(w["label"] == "Not supported by this display" for w in widgets())+ assert not any(w.get("name") == "adaptive_sync" for w in widgets())# Tearing is off by default; the switch saves and applies it.assert ui.scroll_into_view("allow_tearing")["on"] is Falseclick(ui.scroll_into_view("allow_tearing"))diff --git a/tests/wlr_protocols.py b/tests/wlr_protocols.pyindex 892bfce..654a000 100644--- a/tests/wlr_protocols.py+++ b/tests/wlr_protocols.py@@ -114,6 +114,10 @@ def output_management(tmp):wait_for(lambda: s.output("HEADLESS-1")["scale"] == 1.5, "scale not applied")s.run("wlr-randr", "--output", "HEADLESS-1", "--scale", "0.5", ok=False)assert s.output("HEADLESS-1")["scale"] == 1.5+ # Headless cannot run variable refresh: switching it on is refused,+ # and the mode stays as configured.+ s.run("wlr-randr", "--output", "HEADLESS-1", "--adaptive-sync", "enabled", ok=False)+ assert s.output("HEADLESS-1")["adaptive_sync"] == "auto"# Client changes persist like Settings changes.saved = (tmp / "rediwm-config.toml").read_text()@@ -283,6 +287,19 @@ def extra_protocols(tmp):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())+ # Variable refresh in "auto" (the default) is wanted on the game's+ # output only; headless cannot run it, so it stays off.+ vrr = lambda: [o["name"] for o in s.ipc.get_outputs() if o["adaptive_sync_wanted"]]+ assert vrr() == tearing(), (vrr(), tearing())+ for o in s.ipc.get_outputs():+ assert o["adaptive_sync"] == "auto" and not o["adaptive_sync_supported"], o+ assert not o["adaptive_sync_active"] and not o["adaptive_sync_needs_modeset"], o+ game_output = vrr()[0]+ s.ipc.request(query="set_output_config", params={"output": game_output, "adaptive_sync": "off"})+ wait_for(lambda: not vrr(), "adaptive_sync = off still wanted")+ assert 'adaptive_sync = "off"' in (tmp / "rediwm-config.toml").read_text()+ s.ipc.request(query="set_output_config", params={"output": game_output, "adaptive_sync": "auto"})+ wait_for(lambda: vrr() == [game_output], "adaptive_sync = auto not wanted again")workspaces = s.ipc.request(query="workspaces")assert workspaces == [{"id": 1, "name": "Canvas", "is_focused": True,"is_visible": True, "output": None, "automatic": False,@@ -292,6 +309,8 @@ def extra_protocols(tmp):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")+ # Variable refresh does not depend on the hint: a vsync game still wants it.+ assert vrr() == [game_output], vrr()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()