RediWM is a Wayland compositor written in Zig (OpenGL ES) that includes everything in one process
Persistent per-device pointer settings
oxydizer26e9ff468257
diff --git a/TESTING.md b/TESTING.mdindex ac869a7..b858522 100644--- a/TESTING.md+++ b/TESTING.md@@ -61,3 +61,20 @@ interval; CPU and GPU work overlap, so do not add their timings.Hardware, login, browser/OBS sharing and toolkit IME checks remain manual. See[rendering](docs/agent-notes/rendering.md), [tiling qualification](docs/plans/optional-tiling-qualification.md)and [printer qualification](docs/plans/printers-qualification.md).++Pointer settings: `python3 tests/input_persistence.py` drives the real Settings,+reload, hotplug and restart paths with a noninstalled libinput fixture. Repeat+with `REDIWM_TEST_SCALE=1.5`; set `WLR_RENDER_DRM_DEVICE` on multi-GPU hosts as+above. No host input devices are configured. For manual hardware qualification,+select a touchpad and external mouse in Settings, give them opposite natural+scrolling and different speeds, and verify both in a client. Check tapping,+tap-drag and disable-while-typing on supported hardware. Unplug the selected+mouse with the selector open, reconnect, reload configuration and restart the+compositor; verify each device's values and behavior again. A device identified+by physical path follows its port; see [configuration](README.md#configuration)+for identity limitations.+Check the type icon and friendly name (including a trackball, if available).+An edited control should switch from Default to Custom. Reset one device and+verify that it returns to Default immediately while the others remain unchanged;+then change a global default and check that the reset device inherits it after+reload, reconnection and restart.diff --git a/assets/icons/touchpad.svg b/assets/icons/touchpad.svgnew file mode 100644index 0000000..8b27568--- /dev/null+++ b/assets/icons/touchpad.svg@@ -0,0 +1,4 @@+<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">+ <rect x="3" y="4" width="18" height="16" rx="3"/>+ <path d="M3 15h18M12 15v5"/>+</svg>diff --git a/assets/icons/trackball.svg b/assets/icons/trackball.svgnew file mode 100644index 0000000..a0ac225--- /dev/null+++ b/assets/icons/trackball.svg@@ -0,0 +1,4 @@+<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">+ <path d="M6 8c-1.2 2.1-2 5.1-2 8a4 4 0 0 0 4 4h8a4 4 0 0 0 4-4c0-2.9-.8-5.9-2-8M12 16v4"/>+ <circle cx="12" cy="8" r="5"/>+</svg>diff --git a/build.zig b/build.zigindex eb2e1e6..51c9b2e 100644--- a/build.zig+++ b/build.zig@@ -165,6 +165,7 @@ pub fn build(b: *std.Build) void {// (accel speed, natural scroll, tap-to-click). Header is a clean, glib-free// C API so it's @cInclude'd directly, unlike librsvg (see AGENTS.md, "Build and platform gotchas").compositor.root_module.linkSystemLibrary("libinput", .{});+ compositor.root_module.linkSystemLibrary("libudev", .{});compositor.root_module.linkSystemLibrary("png16", .{});// PipeWire's PulseAudio-compat client library — see src/audio/pipewire.zig.compositor.root_module.linkSystemLibrary("libpulse", .{});diff --git a/build/support.zig b/build/support.zigindex 8b264de..40206fc 100644--- a/build/support.zig+++ b/build/support.zig@@ -25,7 +25,7 @@ pub fn cHeaders(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.l.libc = cHeader(b, target, optimize, b.path("src/c/libc.h"), &.{}),.gfx = cHeader(b, target, optimize, b.path("src/c/gfx.h"), &gfx_libs),.pulse = cHeader(b, target, optimize, b.path("src/c/pulse.h"), &.{"libpulse"}),- .libinput = cHeader(b, target, optimize, b.path("src/c/libinput.h"), &.{"libinput"}),+ .libinput = cHeader(b, target, optimize, b.path("src/c/libinput.h"), &.{ "libinput", "libudev" }),.png = cHeader(b, target, optimize, b.path("src/c/png.h"), &.{"libpng16"}),.archive = cHeader(b, target, optimize, b.path("src/c/archive.h"), &.{"libarchive"}),};@@ -142,7 +142,7 @@ pub fn addShellUi(b: *std.Build, module: *std.Build.Module) void {pub fn addShellIcons(b: *std.Build, module: *std.Build.Module) void {module.addAnonymousImport("redi-logo", .{ .root_source_file = b.path("assets/redi-logo.svg") });module.addAnonymousImport("rediwm-settings-icon", .{ .root_source_file = b.path("assets/icons/rediwm-settings.png") });- inline for (.{ "git-branch", "home", "folder", "terminal", "settings", "keyboard", "edit", "mouse", "display", "music", "headphones", "wifi", "ethernet", "globe", "bluetooth", "battery", "notification-bell", "speaker", "speaker-xmark", "power-button", "clock", "lock", "logout", "restart", "eye", "eye-off", "refresh", "cut", "copy", "paste", "trash-outline", "trash", "view-grid", "view-list", "sort", "filter", "zoom-in", "zoom-out", "rotate", "crop", "undo", "save", "fit", "print", "open", "usb-stick", "drive", "eject", "users", "squares", "divide" }) |name| {+ inline for (.{ "git-branch", "home", "folder", "terminal", "settings", "keyboard", "edit", "mouse", "touchpad", "trackball", "display", "music", "headphones", "wifi", "ethernet", "globe", "bluetooth", "battery", "notification-bell", "speaker", "speaker-xmark", "power-button", "clock", "lock", "logout", "restart", "eye", "eye-off", "refresh", "cut", "copy", "paste", "trash-outline", "trash", "view-grid", "view-list", "sort", "filter", "zoom-in", "zoom-out", "rotate", "crop", "undo", "save", "fit", "print", "open", "usb-stick", "drive", "eject", "users", "squares", "divide" }) |name| {module.addAnonymousImport("shell-icon-" ++ name, .{ .root_source_file = b.path("assets/icons/" ++ name ++ ".svg") });}}diff --git a/build/tests.zig b/build/tests.zigindex ccd19bf..6d63f93 100644--- a/build/tests.zig+++ b/build/tests.zig@@ -71,6 +71,7 @@ pub fn addZig(ctx: Context, session: Session) ZigTests {ui_tests_module.linkSystemLibrary("fontconfig", .{});ui_tests_module.linkSystemLibrary("librsvg-2.0", .{});ui_tests_module.linkSystemLibrary("libinput", .{});+ ui_tests_module.linkSystemLibrary("libudev", .{});ui_tests_module.linkSystemLibrary("png16", .{});ui_tests_module.linkSystemLibrary("libpulse", .{});inline for (.{ .{ "c_pulse", ctx.c.pulse }, .{ "c_libinput", ctx.c.libinput }, .{ "c_png", ctx.c.png } }) |entry| ui_tests_module.addImport(entry[0], entry[1]);diff --git a/po/de.po b/po/de.poindex c879b22..acbdbe1 100644--- a/po/de.po+++ b/po/de.po@@ -1968,10 +1968,6 @@ msgstr "Drucker deaktivieren"msgid "Disable shortcut"msgstr "Tastenkürzel deaktivieren"-#: src/control_center/search_index.zig-msgid "Disable touchpad while typing"-msgstr "Touchpad beim Tippen deaktivieren"-#: src/control_center/sections/services.zigmsgid "Disabled"msgstr "Deaktiviert"@@ -3412,10 +3408,6 @@ msgstr "Eingebunden"msgid "Mounting…"msgstr "Wird eingebunden…"-#: src/control_center/search_index.zig-msgid "Mouse speed"-msgstr "Mausgeschwindigkeit"-#: src/control_center/sections/shortcuts.zigmsgid "Move To Workspace"msgstr "In Arbeitsbereich verschieben"@@ -6144,10 +6136,6 @@ msgstr "Oben"msgid "Torrent file or magnet link"msgstr "Torrent-Datei oder Magnet-Link"-#: src/control_center/search_index.zig-msgid "Touchpad speed"-msgstr "Touchpad-Geschwindigkeit"-#: src/files/app_torrents.zigmsgid "Transfer"msgstr "Übertragung"@@ -6908,10 +6896,6 @@ msgstr "paket importieren"msgid "keep icons in place"msgstr "symbole fixieren"-#: src/control_center/search_index.zig-msgid "keyboard trackpad"-msgstr "tastatur touchpad"-#: src/control_center/search_index.zigmsgid "laptop suspend sleep"msgstr "laptop bereitschaft schlafen"@@ -7004,10 +6988,6 @@ msgstr "panel oben unten"msgid "panel width"msgstr "panelbreite"-#: src/control_center/search_index.zig-msgid "pointer acceleration sensitivity"-msgstr "zeiger beschleunigung empfindlichkeit"-#: src/control_center/search_index.zigmsgid "pointer mouse"msgstr "zeiger maus"@@ -7152,10 +7132,6 @@ msgstr "oben unten links rechts"msgid "touchpad trackpad"msgstr "touchpad trackpad"-#: src/control_center/search_index.zig-msgid "trackpad acceleration sensitivity"-msgstr "touchpad beschleunigung empfindlichkeit"-#: src/control_center/search_index.zigmsgid "transparency"msgstr "transparenz"@@ -7591,3 +7567,91 @@ msgstr ""#: src/editor/app_search.zigmsgid "Matches replaced: {count}"msgstr ""++#: src/control_center/search_index.zig+msgid "Disable while typing"+msgstr ""++#: src/control_center/search_index.zig+msgid "Left-handed mode"+msgstr ""++#: src/control_center/sections/input.zig+msgid "No devices"+msgstr ""++#: src/control_center/sections/input.zig+msgid "No pointer devices connected."+msgstr ""++#: src/control_center/sections/input.zig+msgid "No unique device identity; settings are unavailable."+msgstr ""++#: src/control_center/search_index.zig+msgid "Pointer device"+msgstr ""++#: src/control_center/search_index.zig+msgid "Pointer speed"+msgstr ""++#: src/control_center/sections/input.zig+msgid "Settings apply only to this device."+msgstr ""++#: src/control_center/search_index.zig+msgid "Tap and drag"+msgstr ""++#: src/control_center/sections/input.zig+msgid "The device could not apply this setting."+msgstr ""++#: src/control_center/sections/input.zig+msgid "This setting is unavailable on the selected device."+msgstr ""++#: src/control_center/search_index.zig+msgid "keyboard touchpad trackpad"+msgstr ""++#: src/control_center/search_index.zig+msgid "mouse buttons swap primary"+msgstr ""++#: src/control_center/search_index.zig+msgid "mouse touchpad trackpad acceleration sensitivity"+msgstr ""++#: src/control_center/search_index.zig+msgid "mouse touchpad trackpad select"+msgstr ""++#: src/control_center/sections/input.zig+msgid "Could not reset or restore the previous settings."+msgstr ""++#: src/control_center/sections/input.zig+msgid "Could not reset. The previous settings were restored."+msgstr ""++#: src/control_center/sections/input.zig+msgid "Could not save or restore the previous settings."+msgstr ""++#: src/control_center/sections/input.zig+msgid "Could not save. The previous settings were restored."+msgstr ""++#: src/control_center/search_index.zig+msgid "Reset pointer settings"+msgstr ""++#: src/control_center/sections/input.zig+msgid "Reset to defaults"+msgstr ""++#: src/control_center/search_index.zig+msgid "mouse touchpad trackball default custom inherit"+msgstr ""diff --git a/po/es.po b/po/es.poindex ff08bd9..37560c3 100644--- a/po/es.po+++ b/po/es.po@@ -1965,10 +1965,6 @@ msgstr "Desactivar impresora"msgid "Disable shortcut"msgstr "Desactivar atajo"-#: src/control_center/search_index.zig-msgid "Disable touchpad while typing"-msgstr "Desactivar el panel táctil al escribir"-#: src/control_center/sections/services.zigmsgid "Disabled"msgstr "Desactivado"@@ -3409,10 +3405,6 @@ msgstr "Montado"msgid "Mounting…"msgstr "Montando…"-#: src/control_center/search_index.zig-msgid "Mouse speed"-msgstr "Velocidad del ratón"-#: src/control_center/sections/shortcuts.zigmsgid "Move To Workspace"msgstr "Mover al espacio de trabajo"@@ -6141,10 +6133,6 @@ msgstr "Arriba"msgid "Torrent file or magnet link"msgstr "Archivo torrent o enlace magnet"-#: src/control_center/search_index.zig-msgid "Touchpad speed"-msgstr "Velocidad del panel táctil"-#: src/files/app_torrents.zigmsgid "Transfer"msgstr "Transferir"@@ -6905,10 +6893,6 @@ msgstr "importar paquete"msgid "keep icons in place"msgstr "mantener iconos fijos"-#: src/control_center/search_index.zig-msgid "keyboard trackpad"-msgstr "teclado panel táctil"-#: src/control_center/search_index.zigmsgid "laptop suspend sleep"msgstr "portátil suspender dormir"@@ -7001,10 +6985,6 @@ msgstr "panel arriba abajo"msgid "panel width"msgstr "panel ancho"-#: src/control_center/search_index.zig-msgid "pointer acceleration sensitivity"-msgstr "puntero aceleración sensibilidad"-#: src/control_center/search_index.zigmsgid "pointer mouse"msgstr "puntero ratón"@@ -7149,10 +7129,6 @@ msgstr "arriba abajo izquierda derecha"msgid "touchpad trackpad"msgstr "panel táctil trackpad"-#: src/control_center/search_index.zig-msgid "trackpad acceleration sensitivity"-msgstr "panel táctil aceleración sensibilidad"-#: src/control_center/search_index.zigmsgid "transparency"msgstr "transparencia"@@ -7588,3 +7564,91 @@ msgstr ""#: src/editor/app_search.zigmsgid "Matches replaced: {count}"msgstr ""++#: src/control_center/search_index.zig+msgid "Disable while typing"+msgstr ""++#: src/control_center/search_index.zig+msgid "Left-handed mode"+msgstr ""++#: src/control_center/sections/input.zig+msgid "No devices"+msgstr ""++#: src/control_center/sections/input.zig+msgid "No pointer devices connected."+msgstr ""++#: src/control_center/sections/input.zig+msgid "No unique device identity; settings are unavailable."+msgstr ""++#: src/control_center/search_index.zig+msgid "Pointer device"+msgstr ""++#: src/control_center/search_index.zig+msgid "Pointer speed"+msgstr ""++#: src/control_center/sections/input.zig+msgid "Settings apply only to this device."+msgstr ""++#: src/control_center/search_index.zig+msgid "Tap and drag"+msgstr ""++#: src/control_center/sections/input.zig+msgid "The device could not apply this setting."+msgstr ""++#: src/control_center/sections/input.zig+msgid "This setting is unavailable on the selected device."+msgstr ""++#: src/control_center/search_index.zig+msgid "keyboard touchpad trackpad"+msgstr ""++#: src/control_center/search_index.zig+msgid "mouse buttons swap primary"+msgstr ""++#: src/control_center/search_index.zig+msgid "mouse touchpad trackpad acceleration sensitivity"+msgstr ""++#: src/control_center/search_index.zig+msgid "mouse touchpad trackpad select"+msgstr ""++#: src/control_center/sections/input.zig+msgid "Could not reset or restore the previous settings."+msgstr ""++#: src/control_center/sections/input.zig+msgid "Could not reset. The previous settings were restored."+msgstr ""++#: src/control_center/sections/input.zig+msgid "Could not save or restore the previous settings."+msgstr ""++#: src/control_center/sections/input.zig+msgid "Could not save. The previous settings were restored."+msgstr ""++#: src/control_center/search_index.zig+msgid "Reset pointer settings"+msgstr ""++#: src/control_center/sections/input.zig+msgid "Reset to defaults"+msgstr ""++#: src/control_center/search_index.zig+msgid "mouse touchpad trackball default custom inherit"+msgstr ""diff --git a/po/fr.po b/po/fr.poindex 0fa0a4c..9cbf4ff 100644--- a/po/fr.po+++ b/po/fr.po@@ -1968,10 +1968,6 @@ msgstr "Désactiver l'imprimante"msgid "Disable shortcut"msgstr "Désactiver le raccourci"-#: src/control_center/search_index.zig-msgid "Disable touchpad while typing"-msgstr "Désactiver le pavé tactile pendant la frappe"-#: src/control_center/sections/services.zigmsgid "Disabled"msgstr "Désactivé"@@ -3412,10 +3408,6 @@ msgstr "Monté"msgid "Mounting…"msgstr "Montage…"-#: src/control_center/search_index.zig-msgid "Mouse speed"-msgstr "Vitesse de la souris"-#: src/control_center/sections/shortcuts.zigmsgid "Move To Workspace"msgstr "Déplacer vers un espace de travail"@@ -6144,10 +6136,6 @@ msgstr "En haut"msgid "Torrent file or magnet link"msgstr "Fichier torrent ou lien magnet"-#: src/control_center/search_index.zig-msgid "Touchpad speed"-msgstr "Vitesse du pavé tactile"-#: src/files/app_torrents.zigmsgid "Transfer"msgstr "Transfert"@@ -6908,10 +6896,6 @@ msgstr "importer paquet"msgid "keep icons in place"msgstr "fixer les icônes"-#: src/control_center/search_index.zig-msgid "keyboard trackpad"-msgstr "clavier pavé tactile"-#: src/control_center/search_index.zigmsgid "laptop suspend sleep"msgstr "portable suspendre veille"@@ -7004,10 +6988,6 @@ msgstr "panneau haut bas"msgid "panel width"msgstr "largeur panneau"-#: src/control_center/search_index.zig-msgid "pointer acceleration sensitivity"-msgstr "pointeur accélération sensibilité"-#: src/control_center/search_index.zigmsgid "pointer mouse"msgstr "pointeur souris"@@ -7152,10 +7132,6 @@ msgstr "haut bas gauche droite"msgid "touchpad trackpad"msgstr "pavé tactile trackpad"-#: src/control_center/search_index.zig-msgid "trackpad acceleration sensitivity"-msgstr "pavé tactile accélération sensibilité"-#: src/control_center/search_index.zigmsgid "transparency"msgstr "transparence"@@ -7591,3 +7567,91 @@ msgstr ""#: src/editor/app_search.zigmsgid "Matches replaced: {count}"msgstr ""++#: src/control_center/search_index.zig+msgid "Disable while typing"+msgstr ""++#: src/control_center/search_index.zig+msgid "Left-handed mode"+msgstr ""++#: src/control_center/sections/input.zig+msgid "No devices"+msgstr ""++#: src/control_center/sections/input.zig+msgid "No pointer devices connected."+msgstr ""++#: src/control_center/sections/input.zig+msgid "No unique device identity; settings are unavailable."+msgstr ""++#: src/control_center/search_index.zig+msgid "Pointer device"+msgstr ""++#: src/control_center/search_index.zig+msgid "Pointer speed"+msgstr ""++#: src/control_center/sections/input.zig+msgid "Settings apply only to this device."+msgstr ""++#: src/control_center/search_index.zig+msgid "Tap and drag"+msgstr ""++#: src/control_center/sections/input.zig+msgid "The device could not apply this setting."+msgstr ""++#: src/control_center/sections/input.zig+msgid "This setting is unavailable on the selected device."+msgstr ""++#: src/control_center/search_index.zig+msgid "keyboard touchpad trackpad"+msgstr ""++#: src/control_center/search_index.zig+msgid "mouse buttons swap primary"+msgstr ""++#: src/control_center/search_index.zig+msgid "mouse touchpad trackpad acceleration sensitivity"+msgstr ""++#: src/control_center/search_index.zig+msgid "mouse touchpad trackpad select"+msgstr ""++#: src/control_center/sections/input.zig+msgid "Could not reset or restore the previous settings."+msgstr ""++#: src/control_center/sections/input.zig+msgid "Could not reset. The previous settings were restored."+msgstr ""++#: src/control_center/sections/input.zig+msgid "Could not save or restore the previous settings."+msgstr ""++#: src/control_center/sections/input.zig+msgid "Could not save. The previous settings were restored."+msgstr ""++#: src/control_center/search_index.zig+msgid "Reset pointer settings"+msgstr ""++#: src/control_center/sections/input.zig+msgid "Reset to defaults"+msgstr ""++#: src/control_center/search_index.zig+msgid "mouse touchpad trackball default custom inherit"+msgstr ""diff --git a/po/pt_BR.po b/po/pt_BR.poindex c14e4aa..9c4db83 100644--- a/po/pt_BR.po+++ b/po/pt_BR.po@@ -1965,10 +1965,6 @@ msgstr "Desativar impressora"msgid "Disable shortcut"msgstr "Desativar atalho"-#: src/control_center/search_index.zig-msgid "Disable touchpad while typing"-msgstr "Desativar o touchpad ao digitar"-#: src/control_center/sections/services.zigmsgid "Disabled"msgstr "Desativado"@@ -3409,10 +3405,6 @@ msgstr "Montado"msgid "Mounting…"msgstr "Montando…"-#: src/control_center/search_index.zig-msgid "Mouse speed"-msgstr "Velocidade do mouse"-#: src/control_center/sections/shortcuts.zigmsgid "Move To Workspace"msgstr "Mover para o espaço de trabalho"@@ -6141,10 +6133,6 @@ msgstr "Superior"msgid "Torrent file or magnet link"msgstr "Arquivo torrent ou link magnet"-#: src/control_center/search_index.zig-msgid "Touchpad speed"-msgstr "Velocidade do touchpad"-#: src/files/app_torrents.zigmsgid "Transfer"msgstr "Transferir"@@ -6905,10 +6893,6 @@ msgstr "importar pacote"msgid "keep icons in place"msgstr "manter ícones fixos"-#: src/control_center/search_index.zig-msgid "keyboard trackpad"-msgstr "teclado touchpad"-#: src/control_center/search_index.zigmsgid "laptop suspend sleep"msgstr "laptop suspender dormir"@@ -7001,10 +6985,6 @@ msgstr "painel superior inferior"msgid "panel width"msgstr "painel largura"-#: src/control_center/search_index.zig-msgid "pointer acceleration sensitivity"-msgstr "ponteiro aceleração sensibilidade"-#: src/control_center/search_index.zigmsgid "pointer mouse"msgstr "ponteiro mouse"@@ -7149,10 +7129,6 @@ msgstr "superior inferior esquerda direita"msgid "touchpad trackpad"msgstr "touchpad trackpad"-#: src/control_center/search_index.zig-msgid "trackpad acceleration sensitivity"-msgstr "touchpad aceleração sensibilidade"-#: src/control_center/search_index.zigmsgid "transparency"msgstr "transparência"@@ -7588,3 +7564,91 @@ msgstr ""#: src/editor/app_search.zigmsgid "Matches replaced: {count}"msgstr ""++#: src/control_center/search_index.zig+msgid "Disable while typing"+msgstr ""++#: src/control_center/search_index.zig+msgid "Left-handed mode"+msgstr ""++#: src/control_center/sections/input.zig+msgid "No devices"+msgstr ""++#: src/control_center/sections/input.zig+msgid "No pointer devices connected."+msgstr ""++#: src/control_center/sections/input.zig+msgid "No unique device identity; settings are unavailable."+msgstr ""++#: src/control_center/search_index.zig+msgid "Pointer device"+msgstr ""++#: src/control_center/search_index.zig+msgid "Pointer speed"+msgstr ""++#: src/control_center/sections/input.zig+msgid "Settings apply only to this device."+msgstr ""++#: src/control_center/search_index.zig+msgid "Tap and drag"+msgstr ""++#: src/control_center/sections/input.zig+msgid "The device could not apply this setting."+msgstr ""++#: src/control_center/sections/input.zig+msgid "This setting is unavailable on the selected device."+msgstr ""++#: src/control_center/search_index.zig+msgid "keyboard touchpad trackpad"+msgstr ""++#: src/control_center/search_index.zig+msgid "mouse buttons swap primary"+msgstr ""++#: src/control_center/search_index.zig+msgid "mouse touchpad trackpad acceleration sensitivity"+msgstr ""++#: src/control_center/search_index.zig+msgid "mouse touchpad trackpad select"+msgstr ""++#: src/control_center/sections/input.zig+msgid "Could not reset or restore the previous settings."+msgstr ""++#: src/control_center/sections/input.zig+msgid "Could not reset. The previous settings were restored."+msgstr ""++#: src/control_center/sections/input.zig+msgid "Could not save or restore the previous settings."+msgstr ""++#: src/control_center/sections/input.zig+msgid "Could not save. The previous settings were restored."+msgstr ""++#: src/control_center/search_index.zig+msgid "Reset pointer settings"+msgstr ""++#: src/control_center/sections/input.zig+msgid "Reset to defaults"+msgstr ""++#: src/control_center/search_index.zig+msgid "mouse touchpad trackball default custom inherit"+msgstr ""diff --git a/po/rediwm.pot b/po/rediwm.potindex fc8ab4b..bb827b7 100644--- a/po/rediwm.pot+++ b/po/rediwm.pot@@ -1565,6 +1565,14 @@ msgstr ""msgid "Could not request authentication. Check that polkit is running."msgstr ""+#: src/control_center/sections/input.zig+msgid "Could not reset or restore the previous settings."+msgstr ""++#: src/control_center/sections/input.zig+msgid "Could not reset. The previous settings were restored."+msgstr ""+#: src/images/app_input.zigmsgid "Could not rotate: not enough memory."msgstr ""@@ -1589,6 +1597,10 @@ msgstr ""msgid "Could not save floating apps."msgstr ""+#: src/control_center/sections/input.zig+msgid "Could not save or restore the previous settings."+msgstr ""+#: src/control_center/sections/portals.zigmsgid "Could not save portal preferences. Check your configuration directory."msgstr ""@@ -1629,6 +1641,10 @@ msgstr ""msgid "Could not save. Check the folder and permissions."msgstr ""+#: src/control_center/sections/input.zig+msgid "Could not save. The previous settings were restored."+msgstr ""+#: src/printing/admin.zigmsgid "Could not send printer administration request."msgstr ""@@ -1972,7 +1988,7 @@ msgid "Disable shortcut"msgstr ""#: src/control_center/search_index.zig-msgid "Disable touchpad while typing"+msgid "Disable while typing"msgstr ""#: src/control_center/sections/services.zig@@ -3151,8 +3167,8 @@ msgstr ""msgid "Left"msgstr ""-#: src/control_center/sections/input.zig-msgid "Left-handed mouse"+#: src/control_center/search_index.zig+msgid "Left-handed mode"msgstr ""#: src/control_center/search_index.zig@@ -3443,10 +3459,6 @@ msgstr ""msgid "Mounting…"msgstr ""-#: src/control_center/search_index.zig-msgid "Mouse speed"-msgstr ""-#: src/control_center/sections/shortcuts.zigmsgid "Move To Workspace"msgstr ""@@ -3687,6 +3699,10 @@ msgstr ""msgid "No changes were made. Authentication was cancelled or the request failed."msgstr ""+#: src/control_center/sections/input.zig+msgid "No devices"+msgstr ""+#: src/pdf/app_paint.zigmsgid "No document open. Click 'Open' or press Ctrl+O."msgstr ""@@ -3747,6 +3763,10 @@ msgstr ""msgid "No paired devices. Choose Pair New Device to get started."msgstr ""+#: src/control_center/sections/input.zig+msgid "No pointer devices connected."+msgstr ""+#: src/battery_popup.zigmsgid "No power profile service is running."msgstr ""@@ -3807,6 +3827,10 @@ msgstr ""msgid "No unambiguous automatic driver match. Choose a listed driver, check an IPP address, or explicitly choose a raw queue."msgstr ""+#: src/control_center/sections/input.zig+msgid "No unique device identity; settings are unavailable."+msgstr ""+#: src/control_center/sections/printers.zigmsgid "No usblp node was found; CUPS may still use libusb or ipp-usb."msgstr ""@@ -3895,7 +3919,7 @@ msgstr ""msgid "Not specified"msgstr ""-#: src/session/power_capabilities.zig+#: src/control_center/sections/input.zigmsgid "Not supported"msgstr ""@@ -4271,6 +4295,14 @@ msgstr ""msgid "Plugged In"msgstr ""+#: src/control_center/search_index.zig+msgid "Pointer device"+msgstr ""++#: src/control_center/search_index.zig+msgid "Pointer speed"+msgstr ""+#: src/control_center/sections/desktop.zigmsgid "Position"msgstr ""@@ -4811,6 +4843,10 @@ msgstr ""msgid "Reserved folder name"msgstr ""+#: src/control_center/search_index.zig+msgid "Reset pointer settings"+msgstr ""+#: src/control_center/search_index.zigmsgid "Reset theme"msgstr ""@@ -4823,6 +4859,10 @@ msgstr ""msgid "Reset to default"msgstr ""+#: src/control_center/sections/input.zig+msgid "Reset to defaults"+msgstr ""+#: src/control_center/sections/appearance_sections.zigmsgid "Reset to theme"msgstr ""@@ -5295,6 +5335,10 @@ msgstr ""msgid "Settings"msgstr ""+#: src/control_center/sections/input.zig+msgid "Settings apply only to this device."+msgstr ""+#: src/control_center/sections/appearance_rows.zigmsgid "Shadow"msgstr ""@@ -5707,6 +5751,10 @@ msgstr ""msgid "Takes effect at next boot. The keyring will not unlock automatically."msgstr ""+#: src/control_center/search_index.zig+msgid "Tap and drag"+msgstr ""+#: src/control_center/search_index.zigmsgid "Tap to click"msgstr ""@@ -5867,6 +5915,10 @@ msgstr ""msgid "The device address matches; successful communication has not been confirmed."msgstr ""+#: src/control_center/sections/input.zig+msgid "The device could not apply this setting."+msgstr ""+#: src/pdf/client_print.zigmsgid "The document could not be printed."msgstr ""@@ -6115,6 +6167,10 @@ msgstr ""msgid "This security type needs a network configuration tool."msgstr ""+#: src/control_center/sections/input.zig+msgid "This setting is unavailable on the selected device."+msgstr ""+#: src/control_center/tree.zigmsgid "This setting is unavailable on this device or in the current mode."msgstr ""@@ -6211,10 +6267,6 @@ msgstr ""msgid "Torrent file or magnet link"msgstr ""-#: src/control_center/search_index.zig-msgid "Touchpad speed"-msgstr ""-#: src/files/app_torrents.zigmsgid "Transfer"msgstr ""@@ -6976,7 +7028,7 @@ msgid "keep icons in place"msgstr ""#: src/control_center/search_index.zig-msgid "keyboard trackpad"+msgid "keyboard touchpad trackpad"msgstr ""#: src/control_center/search_index.zig@@ -7031,6 +7083,22 @@ msgstr ""msgid "motion duration"msgstr ""+#: src/control_center/search_index.zig+msgid "mouse buttons swap primary"+msgstr ""++#: src/control_center/search_index.zig+msgid "mouse touchpad trackball default custom inherit"+msgstr ""++#: src/control_center/search_index.zig+msgid "mouse touchpad trackpad acceleration sensitivity"+msgstr ""++#: src/control_center/search_index.zig+msgid "mouse touchpad trackpad select"+msgstr ""+#: src/notifications/toast.zigmsgid "now"msgstr ""@@ -7075,10 +7143,6 @@ msgstr ""msgid "panel width"msgstr ""-#: src/control_center/search_index.zig-msgid "pointer acceleration sensitivity"-msgstr ""-#: src/control_center/search_index.zigmsgid "pointer mouse"msgstr ""@@ -7227,10 +7291,6 @@ msgstr ""msgid "touchpad trackpad"msgstr ""-#: src/control_center/search_index.zig-msgid "trackpad acceleration sensitivity"-msgstr ""-#: src/control_center/search_index.zigmsgid "transparency"msgstr ""diff --git a/po/ru.po b/po/ru.poindex 6016063..282ae53 100644--- a/po/ru.po+++ b/po/ru.po@@ -1970,10 +1970,6 @@ msgstr "Отключить принтер"msgid "Disable shortcut"msgstr "Отключить сочетание"-#: src/control_center/search_index.zig-msgid "Disable touchpad while typing"-msgstr "Отключать сенсорную панель при вводе"-#: src/control_center/sections/services.zigmsgid "Disabled"msgstr "Отключено"@@ -3414,10 +3410,6 @@ msgstr "Подключено"msgid "Mounting…"msgstr "Подключение…"-#: src/control_center/search_index.zig-msgid "Mouse speed"-msgstr "Скорость мыши"-#: src/control_center/sections/shortcuts.zigmsgid "Move To Workspace"msgstr "Переместить в рабочее пространство"@@ -6146,10 +6138,6 @@ msgstr "Вверху"msgid "Torrent file or magnet link"msgstr "Файл торрента или magnet-ссылка"-#: src/control_center/search_index.zig-msgid "Touchpad speed"-msgstr "Скорость сенсорной панели"-#: src/files/app_torrents.zigmsgid "Transfer"msgstr "Передача"@@ -6910,10 +6898,6 @@ msgstr "импорт набор"msgid "keep icons in place"msgstr "закрепить значки"-#: src/control_center/search_index.zig-msgid "keyboard trackpad"-msgstr "клавиатура сенсорная панель"-#: src/control_center/search_index.zigmsgid "laptop suspend sleep"msgstr "ноутбук приостановить сон"@@ -7006,10 +6990,6 @@ msgstr "панель вверху внизу"msgid "panel width"msgstr "ширина панели"-#: src/control_center/search_index.zig-msgid "pointer acceleration sensitivity"-msgstr "указатель ускорение чувствительность"-#: src/control_center/search_index.zigmsgid "pointer mouse"msgstr "указатель мышь"@@ -7154,10 +7134,6 @@ msgstr "вверху внизу слева справа"msgid "touchpad trackpad"msgstr "сенсорная панель трекпад"-#: src/control_center/search_index.zig-msgid "trackpad acceleration sensitivity"-msgstr "сенсорная панель ускорение чувствительность"-#: src/control_center/search_index.zigmsgid "transparency"msgstr "прозрачность"@@ -7603,3 +7579,91 @@ msgstr ""#: src/editor/app_search.zigmsgid "Matches replaced: {count}"msgstr ""++#: src/control_center/search_index.zig+msgid "Disable while typing"+msgstr ""++#: src/control_center/search_index.zig+msgid "Left-handed mode"+msgstr ""++#: src/control_center/sections/input.zig+msgid "No devices"+msgstr ""++#: src/control_center/sections/input.zig+msgid "No pointer devices connected."+msgstr ""++#: src/control_center/sections/input.zig+msgid "No unique device identity; settings are unavailable."+msgstr ""++#: src/control_center/search_index.zig+msgid "Pointer device"+msgstr ""++#: src/control_center/search_index.zig+msgid "Pointer speed"+msgstr ""++#: src/control_center/sections/input.zig+msgid "Settings apply only to this device."+msgstr ""++#: src/control_center/search_index.zig+msgid "Tap and drag"+msgstr ""++#: src/control_center/sections/input.zig+msgid "The device could not apply this setting."+msgstr ""++#: src/control_center/sections/input.zig+msgid "This setting is unavailable on the selected device."+msgstr ""++#: src/control_center/search_index.zig+msgid "keyboard touchpad trackpad"+msgstr ""++#: src/control_center/search_index.zig+msgid "mouse buttons swap primary"+msgstr ""++#: src/control_center/search_index.zig+msgid "mouse touchpad trackpad acceleration sensitivity"+msgstr ""++#: src/control_center/search_index.zig+msgid "mouse touchpad trackpad select"+msgstr ""++#: src/control_center/sections/input.zig+msgid "Could not reset or restore the previous settings."+msgstr ""++#: src/control_center/sections/input.zig+msgid "Could not reset. The previous settings were restored."+msgstr ""++#: src/control_center/sections/input.zig+msgid "Could not save or restore the previous settings."+msgstr ""++#: src/control_center/sections/input.zig+msgid "Could not save. The previous settings were restored."+msgstr ""++#: src/control_center/search_index.zig+msgid "Reset pointer settings"+msgstr ""++#: src/control_center/sections/input.zig+msgid "Reset to defaults"+msgstr ""++#: src/control_center/search_index.zig+msgid "mouse touchpad trackball default custom inherit"+msgstr ""diff --git a/src/Input.zig b/src/Input.zigindex 20a4407..abe7ad3 100644--- a/src/Input.zig+++ b/src/Input.zig@@ -122,6 +122,8 @@ cursor_held: bool = false,cursor_serial: CursorSerial = .{},keyboards: wl.list.Head(Keyboard, .link) = undefined,pointers: wl.list.Head(Pointer, .link) = undefined,+/// Monotonic live tokens keep Settings selection safe across allocator reuse.+next_pointer_id: u64 = 1,// The one open control center, if any (opening/open/closing all count) —// routes pointer gestures and captures keys only while focused.// Output creates it; ControlCenter.destroy clears this reference.diff --git a/src/Pointer.zig b/src/Pointer.zigindex 9067637..d7d8b79 100644--- a/src/Pointer.zig+++ b/src/Pointer.zig@@ -1,30 +1,94 @@-// Tracks a pointer input device for as long as it's plugged in, purely so-// the control center's Input section (src/control_center/sections/input.zig)-// has something to enumerate and hand to src/libinput.zig — cursor motion-// itself is handled by wlr.Cursor directly (see Input.zig's `newInput`),-// this struct adds no behavior of its own.+// Tracks pointer identity and settings for the lifetime of a connected device.+// Cursor motion itself is handled by wlr.Cursor directly.+const std = @import("std");const wl = @import("wayland").server.wl;const wlr = @import("wlroots");const Input = @import("Input.zig");const gpa = @import("main.zig").gpa;+const libinput = @import("libinput.zig");+const identity_mod = @import("pointer_identity.zig");+const config_apply = @import("config_runtime/apply.zig");const Pointer = @This();input: *Input,link: wl.list.Link = undefined,device: *wlr.InputDevice,+id: u64,+identity: ?identity_mod.Identity,+/// Once a key collides, removing one peer cannot prove which device remains.+identity_ambiguous: bool = false,destroy: wl.Listener(*wlr.InputDevice) = .init(handleDestroy),pub fn create(input: *Input, device: *wlr.InputDevice) !void {const pointer = try gpa.create(Pointer);errdefer gpa.destroy(pointer); // listener add below is infallible; this covers any later try- pointer.* = .{ .input = input, .device = device };+ const id = input.next_pointer_id;+ input.next_pointer_id = std.math.add(u64, id, 1) catch return error.PointerIdExhausted;+ pointer.* = .{ .input = input, .device = device, .id = id, .identity = libinput.getIdentity(device) };device.events.destroy.add(&pointer.destroy);input.pointers.append(pointer);- @import("config_runtime/apply.zig").applyPointerDevice(device, input.server.config.input);+ pointer.markIdentityCollisions();+ config_apply.applyPointerDevice(pointer);+ // A second indistinguishable device invalidates the first device's match,+ // too. Reset just those peers to defaults rather than sharing an override.+ pointer.reapplyIdentityPeers();+ refreshSettings(input);+}++pub fn find(input: *Input, id: u64) ?*Pointer {+ var it = input.pointers.iterator(.forward);+ while (it.next()) |pointer| if (pointer.id == id) return pointer;+ return null;+}++/// The returned key borrows this live Pointer, never the configuration arena.+/// Ambiguous keys must neither read nor write a persisted device override.+pub fn persistentId(pointer: *const Pointer) ?[]const u8 {+ if (pointer.identity_ambiguous) return null;+ const identity = if (pointer.identity) |*value| value else return null;+ var it = pointer.input.pointers.iterator(.forward);+ while (it.next()) |other| {+ if (other == pointer) continue;+ if (other.identity) |other_identity| {+ if (std.mem.eql(u8, &identity.key, &other_identity.key)) return null;+ }+ }+ return &identity.key;+}++fn markIdentityCollisions(pointer: *Pointer) void {+ const identity = pointer.identity orelse return;+ var it = pointer.input.pointers.iterator(.forward);+ while (it.next()) |other| {+ if (other == pointer) continue;+ if (other.identity) |other_identity| {+ if (std.mem.eql(u8, &identity.key, &other_identity.key)) {+ pointer.identity_ambiguous = true;+ other.identity_ambiguous = true;+ }+ }+ }+}++fn reapplyIdentityPeers(pointer: *const Pointer) void {+ const identity = pointer.identity orelse return;+ var it = pointer.input.pointers.iterator(.forward);+ while (it.next()) |other| {+ if (other == pointer) continue;+ if (other.identity) |other_identity| {+ if (std.mem.eql(u8, &identity.key, &other_identity.key)) config_apply.applyPointerDevice(other);+ }+ }+}++fn refreshSettings(input: *Input) void {+ if (input.open_control_center) |cc| {+ if (cc.showingPage(.input)) cc.refresh();+ }}fn handleDestroy(listener: *wl.Listener(*wlr.InputDevice), _: *wlr.InputDevice) void {@@ -71,5 +135,10 @@ fn handleDestroy(listener: *wl.Listener(*wlr.InputDevice), _: *wlr.InputDevice)}pointer.link.remove();pointer.destroy.link.remove();+ refreshSettings(pointer.input);gpa.destroy(pointer);}++test {+ _ = @import("pointer_tests.zig");+}diff --git a/src/c/libinput.h b/src/c/libinput.hindex 4f1187e..ce2d5d7 100644--- a/src/c/libinput.h+++ b/src/c/libinput.h@@ -1,2 +1,3 @@/* `c_libinput`: device configuration for the Input settings. */#include <libinput.h>+#include <libudev.h>diff --git a/src/config/default.zig b/src/config/default.zigindex baafa32..39934e9 100644--- a/src/config/default.zig+++ b/src/config/default.zig@@ -106,6 +106,12 @@ pub const source =\\caret_blink_ms = 1060 # full on+off cycle; 0 = never blink\\caret_blink_timeout = 10 # seconds idle before it goes solid; 0 = never\\caret_motion_ms = 80 # glide between positions; 0 = snap+ \\# Pointer values above are defaults. Settings > Input saves only changed+ \\# values in [[input_device]] records keyed by a stable generated id.+ \\# Omitted device fields inherit these defaults; delete a field to reset it.+ \\# Device fields: pointer_speed, natural_scroll, left_handed, tap_to_click,+ \\# tap_drag, disable_while_typing. The latter and speed inherit the *_touchpad+ \\# defaults on touchpads. invert_scroll and pan_speed always remain global.\\\\# ───────────────────────────────────────────────\\# Compositor behaviourdiff --git a/src/config/input_device.zig b/src/config/input_device.zignew file mode 100644index 0000000..d0bd1f9--- /dev/null+++ b/src/config/input_device.zig@@ -0,0 +1,177 @@+//! Persistent pointer overrides. Records match exact identities; omitted+//! properties inherit the legacy [input] defaults for the device's kind.+const std = @import("std");+const loader = @import("loader.zig");+const fields = @import("loader_fields.zig");++pub const Record = struct {+ id: []const u8 = "",+ pointer_speed: ?f32 = null,+ natural_scroll: ?bool = null,+ left_handed: ?bool = null,+ tap_to_click: ?bool = null,+ tap_drag: ?bool = null,+ disable_while_typing: ?bool = null,+};++pub const Effective = struct {+ pointer_speed: f32,+ natural_scroll: bool,+ left_handed: bool,+ tap_to_click: bool,+ tap_drag: bool,+ disable_while_typing: bool,+};++/// Keys are generated by the backend identity module, never display labels.+/// Do not accept escaping: the config's small string parser does not decode it.+pub fn validId(id: []const u8) bool {+ if (id.len == 0 or id.len > 1024) return false;+ for (id) |ch| if (ch < 0x21 or ch > 0x7e or ch == '"' or ch == '\\') return false;+ return true;+}++pub fn resolve(defaults: loader.InputConfig, records: []const Record, id: ?[]const u8, touchpad: bool) Effective {+ var effective: Effective = .{+ .pointer_speed = if (touchpad) defaults.pointer_speed_touchpad else defaults.pointer_speed,+ .natural_scroll = defaults.natural_scroll,+ .left_handed = defaults.left_handed,+ .tap_to_click = defaults.tap_to_click,+ .tap_drag = defaults.tap_drag,+ .disable_while_typing = if (touchpad) defaults.disable_while_typing_touchpad else defaults.disable_while_typing,+ };+ const identity = id orelse return effective;+ const record = find(records, identity) orelse return effective;+ inline for (@typeInfo(Effective).@"struct".field_names) |key| {+ if (@field(record, key)) |value| @field(effective, key) = value;+ }+ return effective;+}++/// Fail closed even for callers supplying unvalidated, hand-built records.+pub fn find(records: []const Record, id: []const u8) ?Record {+ if (!validId(id)) return null;+ var found: ?Record = null;+ for (records) |record| {+ if (!std.mem.eql(u8, record.id, id)) continue;+ if (found != null) return null;+ found = record;+ }+ return found;+}++/// Explicit values remain overrides even when equal to today's default.+pub fn isOverridden(records: []const Record, id: ?[]const u8, comptime key: []const u8) bool {+ _ = Value(key);+ const record = find(records, id orelse return false) orelse return false;+ return @field(record, key) != null;+}++pub fn hasOverrides(records: []const Record, id: ?[]const u8) bool {+ const record = find(records, id orelse return false) orelse return false;+ inline for (@typeInfo(Effective).@"struct".field_names) |key| {+ if (@field(record, key) != null) return true;+ }+ return false;+}++pub fn eql(a: []const Record, b: []const Record) bool {+ if (a.len != b.len) return false;+ for (a, b) |left, right| {+ if (!std.mem.eql(u8, left.id, right.id)) return false;+ inline for (@typeInfo(Effective).@"struct".field_names) |key| {+ if (@field(left, key) != @field(right, key)) return false;+ }+ }+ return true;+}++pub fn Value(comptime key: []const u8) type {+ return @FieldType(Effective, key);+}++pub fn validateValue(comptime key: []const u8, value: Value(key)) !void {+ if (comptime std.mem.eql(u8, key, "pointer_speed")) {+ if (!std.math.isFinite(value) or value < -1 or value > 1) return error.InvalidValue;+ }+}++pub const Prepared = struct {+ records: []Record,+ index: ?usize,+ record: Record,++ pub fn commit(self: Prepared, cfg: *loader.Config) void {+ if (self.index) |index| self.records[index] = self.record;+ cfg.input_devices = self.records;+ }+};++/// Allocate before touching the backend/file. Commit only after the setting+/// was accepted and saved. Existing records need no allocations, even when a+/// slider emits a stream of changes. New records belong to cfg's arena.+pub fn prepareSet(cfg: *loader.Config, id: []const u8, comptime key: []const u8, value: Value(key)) !Prepared {+ if (!validId(id)) return error.InvalidValue;+ try validateValue(key, value);+ var selected: ?usize = null;+ for (cfg.input_devices, 0..) |record, i| {+ if (!std.mem.eql(u8, record.id, id)) continue;+ if (selected != null) return error.InvalidConfig;+ selected = i;+ }+ var prepared: Prepared = undefined;+ if (selected) |index| {+ prepared = .{ .records = cfg.input_devices, .index = index, .record = cfg.input_devices[index] };+ } else {+ const a = cfg.arena.allocator();+ const records = try a.alloc(Record, cfg.input_devices.len + 1);+ @memcpy(records[0..cfg.input_devices.len], cfg.input_devices);+ prepared = .{ .records = records, .index = cfg.input_devices.len, .record = .{ .id = try a.dupe(u8, id) } };+ }+ @field(prepared.record, key) = value;+ return prepared;+}++/// Reset inherits future defaults as well as today's. Keep an existing id-only+/// record so file comments and record order can survive; never create a record+/// merely to reset a device that already inherits everything.+pub fn prepareReset(cfg: *loader.Config, id: []const u8) !Prepared {+ if (!validId(id)) return error.InvalidValue;+ var selected: ?usize = null;+ var empty: Record = .{};+ for (cfg.input_devices, 0..) |record, i| {+ if (!std.mem.eql(u8, record.id, id)) continue;+ if (selected != null) return error.InvalidConfig;+ selected = i;+ empty.id = record.id;+ }+ return .{ .records = cfg.input_devices, .index = selected, .record = empty };+}++/// Parser state deliberately notices empty records and duplicate fields, so+/// neither an incomplete matcher nor last-write-wins can target another device.+pub const Parser = struct {+ records: std.ArrayList(Record) = .empty,+ current: Record = .{},+ seen: std.enums.EnumSet(std.meta.FieldEnum(Record)) = .empty,++ pub fn apply(self: *Parser, a: std.mem.Allocator, key: []const u8, value: []const u8) !void {+ const field = std.meta.stringToEnum(std.meta.FieldEnum(Record), key) orelse return error.UnknownField;+ if (self.seen.contains(field)) return error.DuplicateField;+ const known = try fields.applyField(&self.current, a, fields.input_device_rules, key, value);+ if (!known) return error.UnknownField;+ self.seen.insert(field);+ }++ pub fn flush(self: *Parser, a: std.mem.Allocator) !void {+ if (!validId(self.current.id)) return error.InvalidIdentity;+ for (self.records.items) |record| if (std.mem.eql(u8, record.id, self.current.id)) return error.DuplicateIdentity;+ try self.records.append(a, self.current);+ self.current = .{};+ self.seen = .empty;+ }+};++test {+ _ = @import("input_device_tests.zig");+}diff --git a/src/config/input_device_save.zig b/src/config/input_device_save.zignew file mode 100644index 0000000..2c22d42--- /dev/null+++ b/src/config/input_device_save.zig@@ -0,0 +1,135 @@+//! Patch one property in one [[input_device]] record, preserving the rest of+//! the file byte-for-byte. Both versions must validate before atomic publish.+const std = @import("std");+const Io = std.Io;+const loader = @import("loader.zig");+const device = @import("input_device.zig");+const theme = @import("ui").theme;+const setting_save = @import("setting_save.zig");++pub fn save(allocator: std.mem.Allocator, io: Io, path: []const u8, id: []const u8, comptime key: []const u8, value: device.Value(key)) !void {+ if (path.len == 0) return error.NoConfigPath;+ const original = try Io.Dir.cwd().readFileAlloc(io, path, allocator, .limited(1 << 20));+ defer allocator.free(original);+ const result = try patch(allocator, original, id, key, value);+ defer allocator.free(result);+ try setting_save.writeValidated(allocator, io, path, result);+}++pub fn reset(allocator: std.mem.Allocator, io: Io, path: []const u8, id: []const u8) !void {+ if (path.len == 0) return error.NoConfigPath;+ const original = try Io.Dir.cwd().readFileAlloc(io, path, allocator, .limited(1 << 20));+ defer allocator.free(original);+ const result = try resetPatch(allocator, original, id);+ defer allocator.free(result);+ if (std.mem.eql(u8, original, result)) return;+ try setting_save.writeValidated(allocator, io, path, result);+}++pub fn patch(a: std.mem.Allocator, original: []const u8, id: []const u8, comptime key: []const u8, value: device.Value(key)) ![]u8 {+ if (!device.validId(id)) return error.InvalidValue;+ try device.validateValue(key, value);+ var old = try loader.parse(a, original, "input-device-save");+ defer old.deinit();+ const serialized = if (@TypeOf(value) == bool)+ try std.fmt.allocPrint(a, "{}", .{value})+ else+ try std.fmt.allocPrint(a, "{d}", .{value});+ defer a.free(serialized);+ return rewrite(a, original, id, .{ .setting = .{ .key = key, .value = serialized } });+}++pub fn resetPatch(a: std.mem.Allocator, original: []const u8, id: []const u8) ![]u8 {+ if (!device.validId(id)) return error.InvalidValue;+ var old = try loader.parse(a, original, "input-device-reset");+ defer old.deinit();+ return rewrite(a, original, id, .reset);+}++const Change = union(enum) {+ setting: struct { key: []const u8, value: []const u8 },+ reset,+};++fn rewrite(a: std.mem.Allocator, original: []const u8, id: []const u8, change: Change) ![]u8 {+ var result: std.ArrayList(u8) = .empty;+ errdefer result.deinit(a);+ var start: usize = 0;+ var offset: usize = 0;+ var device_block = false;+ var matched = false;+ var lines = std.mem.splitScalar(u8, original, '\n');+ while (lines.next()) |raw| {+ const line = theme.stripComment(std.mem.trim(u8, raw, " \t\r"));+ if (std.mem.startsWith(u8, line, "[")) {+ matched = try appendBlock(a, &result, original[start..offset], device_block, id, change) or matched;+ start = offset;+ device_block = std.mem.eql(u8, line, "[[input_device]]");+ }+ offset = @min(original.len, offset + raw.len + 1);+ }+ matched = try appendBlock(a, &result, original[start..], device_block, id, change) or matched;+ if (!matched and change == .setting) {+ const block = try std.fmt.allocPrint(a, "\n[[input_device]]\nid = \"{s}\"\n{s} = {s}\n", .{ id, change.setting.key, change.setting.value });+ defer a.free(block);+ try result.appendSlice(a, block);+ }+ return result.toOwnedSlice(a);+}++fn appendBlock(a: std.mem.Allocator, out: *std.ArrayList(u8), block: []const u8, is_device: bool, id: []const u8, change: Change) !bool {+ var target = false;+ var lines = std.mem.splitScalar(u8, block, '\n');+ if (is_device) while (lines.next()) |raw| {+ const line = theme.stripComment(std.mem.trim(u8, raw, " \t\r"));+ const eq = std.mem.indexOfScalar(u8, line, '=') orelse continue;+ const field = loader.unquoteKey(std.mem.trim(u8, line[0..eq], " \t"));+ if (!std.mem.eql(u8, field, "id")) continue;+ const identity = try theme.unquote(std.mem.trim(u8, line[eq + 1 ..], " \t"));+ target = std.mem.eql(u8, identity, id);+ };+ if (!target) {+ try out.appendSlice(a, block);+ return false;+ }+ lines = std.mem.splitScalar(u8, block, '\n');+ var offset: usize = 0;+ var replaced = false;+ while (lines.next()) |raw| {+ const end = @min(block.len, offset + raw.len + 1);+ const line = theme.stripComment(std.mem.trim(u8, raw, " \t\r"));+ const eq = std.mem.indexOfScalar(u8, line, '=');+ const field = if (eq) |i| loader.unquoteKey(std.mem.trim(u8, line[0..i], " \t")) else "";+ if (change == .reset and std.meta.stringToEnum(std.meta.FieldEnum(device.Effective), field) != null) {+ // Strip the assignment, retaining any inline comment and its line+ // ending. Standalone comments and the identity stay byte-for-byte.+ if (std.mem.indexOfScalar(u8, raw, '#')) |comment| {+ const indent = raw.len - std.mem.trimStart(u8, raw, " \t").len;+ try out.appendSlice(a, raw[0..indent]);+ try out.appendSlice(a, block[offset + comment .. end]);+ }+ } else if (change == .setting and std.mem.eql(u8, field, change.setting.key)) {+ const raw_eq = std.mem.indexOfScalar(u8, raw, '=').?;+ const comment = std.mem.indexOfScalar(u8, raw, '#') orelse raw.len;+ const old_value = std.mem.trim(u8, raw[raw_eq + 1 .. comment], " \t\r");+ const value_start = @intFromPtr(old_value.ptr) - @intFromPtr(raw.ptr);+ try out.appendSlice(a, raw[0..value_start]);+ try out.appendSlice(a, change.setting.value);+ try out.appendSlice(a, block[offset + value_start + old_value.len .. end]);+ replaced = true;+ } else try out.appendSlice(a, block[offset..end]);+ offset = end;+ }+ if (!replaced and change == .setting) {+ if (out.items.len > 0 and out.items[out.items.len - 1] != '\n') try out.append(a, '\n');+ try out.appendSlice(a, change.setting.key);+ try out.appendSlice(a, " = ");+ try out.appendSlice(a, change.setting.value);+ try out.append(a, '\n');+ }+ return true;+}++test {+ _ = @import("input_device_save_tests.zig");+}diff --git a/src/config/input_device_save_tests.zig b/src/config/input_device_save_tests.zignew file mode 100644index 0000000..044e98e--- /dev/null+++ b/src/config/input_device_save_tests.zig@@ -0,0 +1,146 @@+const std = @import("std");+const loader = @import("loader.zig");+const device = @import("input_device.zig");+const save = @import("input_device_save.zig");++test "saving a pointer field preserves other records global settings and comments" {+ const a = std.testing.allocator;+ const original = "# preferences\n[input]\nnatural_scroll = false\npointer_speed = 0.1\n" +++ "[[input_device]] # mouse\n \"natural_scroll\" = false # wheel direction\nid = \"mouse\"\npointer_speed = 0.7\n" +++ "[[input_device]]\nid = \"pad\"\nnatural_scroll = true\n# keep this\n" +++ "[theme]\nfont = \"Example\"\n[[outputs]]\nname = \"DP-1\"\nscale = 1.5\n";+ const updated = try save.patch(a, original, "mouse", "natural_scroll", true);+ defer a.free(updated);+ const expected = try std.mem.replaceOwned(u8, a, original, "\"natural_scroll\" = false # wheel", "\"natural_scroll\" = true # wheel");+ defer a.free(expected);+ try std.testing.expectEqualStrings(expected, updated);+ const crlf = try std.mem.replaceOwned(u8, a, original, "\n", "\r\n");+ defer a.free(crlf);+ const crlf_updated = try save.patch(a, crlf, "mouse", "natural_scroll", true);+ defer a.free(crlf_updated);+ const crlf_expected = try std.mem.replaceOwned(u8, a, expected, "\n", "\r\n");+ defer a.free(crlf_expected);+ try std.testing.expectEqualStrings(crlf_expected, crlf_updated);+ var cfg = try loader.parse(a, updated, "saved");+ defer cfg.deinit();+ try std.testing.expect(!cfg.input.natural_scroll);+ try std.testing.expectEqual(@as(?bool, true), cfg.input_devices[0].natural_scroll);+ try std.testing.expectEqual(@as(?f32, 0.7), cfg.input_devices[0].pointer_speed);+ try std.testing.expectEqual(@as(?bool, true), cfg.input_devices[1].natural_scroll);+ try std.testing.expectEqualStrings("Example", cfg.theme.font);+ try std.testing.expectEqual(@as(?f32, 1.5), cfg.outputs[0].scale);+}++test "pointer persistence adds missing records and fields without replacing records" {+ const a = std.testing.allocator;+ for ([_][]const u8{ "", "[input]\nnatural_scroll = false", "[[input_device]]\nid = \"mouse\"", "[[input_device]]\nid = \"other\"\nnatural_scroll = false\n" }) |original| {+ const speed = try save.patch(a, original, "mouse", "pointer_speed", 0.4);+ defer a.free(speed);+ const natural = try save.patch(a, speed, "mouse", "natural_scroll", true);+ defer a.free(natural);+ const repeated = try save.patch(a, natural, "mouse", "pointer_speed", -0.6);+ defer a.free(repeated);+ var cfg = try loader.parse(a, repeated, "saved");+ defer cfg.deinit();+ const record = device.find(cfg.input_devices, "mouse").?;+ try std.testing.expectEqual(@as(?f32, -0.6), record.pointer_speed);+ try std.testing.expectEqual(@as(?bool, true), record.natural_scroll);+ try std.testing.expectEqual(@as(?bool, null), record.tap_to_click);+ try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, repeated, "id = \"mouse\""));+ }+}++test "invalid pointer save leaves config file untouched and restart restores accepted values" {+ const a = std.testing.allocator;+ const io = std.testing.io;+ var tmp = std.testing.tmpDir(.{});+ defer tmp.cleanup();+ const original = "# preserve\n[input]\nnatural_scroll = false\n[[input_device]]\nid = \"pad\"\nnatural_scroll = true\n";+ try tmp.dir.writeFile(io, .{ .sub_path = "config.toml", .data = original });+ const path = try tmp.dir.realPathFileAlloc(io, "config.toml", a);+ defer a.free(path);+ try std.testing.expectError(error.InvalidValue, save.save(a, io, path, "mouse", "pointer_speed", 2));+ try std.testing.expectError(error.InvalidValue, save.save(a, io, path, "bad\"identity", "natural_scroll", true));+ const unchanged = try tmp.dir.readFileAlloc(io, "config.toml", a, .limited(4096));+ defer a.free(unchanged);+ try std.testing.expectEqualStrings(original, unchanged);+ try save.save(a, io, path, "mouse", "natural_scroll", false);+ try save.save(a, io, path, "mouse", "pointer_speed", 0.7);+ const saved = try tmp.dir.readFileAlloc(io, "config.toml", a, .limited(4096));+ defer a.free(saved);+ // A fresh loader owns no memory or state from either save operation.+ var restarted = try loader.parse(a, saved, path);+ defer restarted.deinit();+ const mouse = device.resolve(restarted.input, restarted.input_devices, "mouse", false);+ const pad = device.resolve(restarted.input, restarted.input_devices, "pad", true);+ try std.testing.expect(!mouse.natural_scroll);+ try std.testing.expect(pad.natural_scroll);+ try std.testing.expectEqual(@as(f32, 0.7), mouse.pointer_speed);+ try std.testing.expect(std.mem.startsWith(u8, saved, original));+ const malformed = "[[input_device]]\nid = \"mouse\"\nid = \"other\"\n";+ try tmp.dir.writeFile(io, .{ .sub_path = "config.toml", .data = malformed });+ try std.testing.expectError(error.InvalidConfig, save.save(a, io, path, "mouse", "natural_scroll", true));+ const invalid_unchanged = try tmp.dir.readFileAlloc(io, "config.toml", a, .limited(4096));+ defer a.free(invalid_unchanged);+ try std.testing.expectEqualStrings(malformed, invalid_unchanged);+}++test "reset removes only selected device overrides while preserving every comment" {+ const a = std.testing.allocator;+ const prefix = "# preferences\n[input]\nnatural_scroll = false\npointer_speed = 0.1\n";+ const suffix = "[[input_device]]\nid = \"pad\"\nnatural_scroll = true\n# keep pad\n[theme]\nfont = \"Example\"\n";+ const original = prefix ++ "[[input_device]] # mouse\n \"natural_scroll\" = false # wheel\nid = \"mouse\" # identity\n" +++ "pointer_speed = 0.7\nleft_handed = true # buttons\ntap_to_click = true\ntap_drag = true\ndisable_while_typing = false\n# keep mouse\n" ++ suffix;+ const expected = prefix ++ "[[input_device]] # mouse\n # wheel\nid = \"mouse\" # identity\n# buttons\n# keep mouse\n" ++ suffix;+ const reset = try save.resetPatch(a, original, "mouse");+ defer a.free(reset);+ try std.testing.expectEqualStrings(expected, reset);+ const crlf = try std.mem.replaceOwned(u8, a, original, "\n", "\r\n");+ defer a.free(crlf);+ const reset_crlf = try save.resetPatch(a, crlf, "mouse");+ defer a.free(reset_crlf);+ const expected_crlf = try std.mem.replaceOwned(u8, a, expected, "\n", "\r\n");+ defer a.free(expected_crlf);+ try std.testing.expectEqualStrings(expected_crlf, reset_crlf);+ const changed_defaults = try std.mem.replaceOwned(u8, a, reset, "pointer_speed = 0.1", "pointer_speed = -0.6");+ defer a.free(changed_defaults);+ var restarted = try loader.parse(a, changed_defaults, "reset-reload");+ defer restarted.deinit();+ try std.testing.expect(!device.hasOverrides(restarted.input_devices, "mouse"));+ try std.testing.expect(device.hasOverrides(restarted.input_devices, "pad"));+ const inherited = device.resolve(restarted.input, restarted.input_devices, "mouse", false);+ try std.testing.expectEqual(@as(f32, -0.6), inherited.pointer_speed);+ try std.testing.expect(!inherited.natural_scroll);+}++test "reset persists inheritance leaves absent devices alone and refuses invalid files" {+ const a = std.testing.allocator;+ const io = std.testing.io;+ var tmp = std.testing.tmpDir(.{});+ defer tmp.cleanup();+ const original = "[input]\nnatural_scroll = false\n[[input_device]]\nid = \"mouse\"\nnatural_scroll = true # direction";+ try tmp.dir.writeFile(io, .{ .sub_path = "config.toml", .data = original });+ const path = try tmp.dir.realPathFileAlloc(io, "config.toml", a);+ defer a.free(path);+ // An absent device must not even attempt an atomic rewrite.+ try tmp.dir.writeFile(io, .{ .sub_path = "config.toml.setting-save.tmp", .data = "reserved" });+ try save.reset(a, io, path, "absent");+ try tmp.dir.deleteFile(io, "config.toml.setting-save.tmp");+ const unchanged = try tmp.dir.readFileAlloc(io, "config.toml", a, .limited(4096));+ defer a.free(unchanged);+ try std.testing.expectEqualStrings(original, unchanged);+ try save.reset(a, io, path, "mouse");+ const reset = try tmp.dir.readFileAlloc(io, "config.toml", a, .limited(4096));+ defer a.free(reset);+ try std.testing.expectEqualStrings("[input]\nnatural_scroll = false\n[[input_device]]\nid = \"mouse\"\n# direction", reset);+ var restarted = try loader.parse(a, reset, path);+ defer restarted.deinit();+ try std.testing.expect(!device.hasOverrides(restarted.input_devices, "mouse"));+ try std.testing.expectError(error.InvalidValue, save.reset(a, io, path, "bad\"id"));+ const malformed = "[[input_device]]\nid = \"mouse\"\nid = \"other\"\n";+ try tmp.dir.writeFile(io, .{ .sub_path = "config.toml", .data = malformed });+ try std.testing.expectError(error.InvalidConfig, save.reset(a, io, path, "mouse"));+ const invalid_unchanged = try tmp.dir.readFileAlloc(io, "config.toml", a, .limited(4096));+ defer a.free(invalid_unchanged);+ try std.testing.expectEqualStrings(malformed, invalid_unchanged);+}diff --git a/src/config/input_device_tests.zig b/src/config/input_device_tests.zignew file mode 100644index 0000000..e252669--- /dev/null+++ b/src/config/input_device_tests.zig@@ -0,0 +1,140 @@+const std = @import("std");+const loader = @import("loader.zig");+const device = @import("input_device.zig");++test "pointer overrides keep devices independent and inherit kind defaults" {+ var cfg = try loader.parse(std.testing.allocator,+ \\[input]+ \\pointer_speed = 0.2+ \\pointer_speed_touchpad = -0.4+ \\disable_while_typing = false+ \\disable_while_typing_touchpad = true+ \\natural_scroll = false+ \\tap_drag = false+ \\[[input_device]]+ \\id = "mouse-a"+ \\pointer_speed = 0.8+ \\[[input_device]]+ \\id = "touchpad-a"+ \\natural_scroll = true+ , "test");+ defer cfg.deinit();+ const mouse = device.resolve(cfg.input, cfg.input_devices, "mouse-a", false);+ const touchpad = device.resolve(cfg.input, cfg.input_devices, "touchpad-a", true);+ const other = device.resolve(cfg.input, cfg.input_devices, "mouse-b", false);+ try std.testing.expect(!mouse.natural_scroll);+ try std.testing.expect(touchpad.natural_scroll);+ try std.testing.expectEqual(@as(f32, 0.8), mouse.pointer_speed);+ try std.testing.expectEqual(@as(f32, -0.4), touchpad.pointer_speed);+ try std.testing.expectEqual(@as(f32, 0.2), other.pointer_speed);+ try std.testing.expect(!mouse.disable_while_typing);+ try std.testing.expect(touchpad.disable_while_typing);+ try std.testing.expect(!touchpad.tap_drag);+ try std.testing.expectEqual(@as(?f32, null), cfg.input_devices[1].pointer_speed);+}++test "global-only input files remain backwards compatible" {+ var cfg = try loader.parse(std.testing.allocator, "[input]\nnatural_scroll = false\npointer_speed = 0.6\npointer_speed_touchpad = -0.7\n", "legacy");+ defer cfg.deinit();+ try std.testing.expectEqual(@as(usize, 0), cfg.input_devices.len);+ const mouse = device.resolve(cfg.input, cfg.input_devices, "mouse", false);+ const pad = device.resolve(cfg.input, cfg.input_devices, null, true);+ try std.testing.expect(!mouse.natural_scroll and !pad.natural_scroll);+ try std.testing.expectEqual(@as(f32, 0.6), mouse.pointer_speed);+ try std.testing.expectEqual(@as(f32, -0.7), pad.pointer_speed);+}++test "input device records reject incomplete duplicate and invalid matchers or values" {+ inline for (.{+ "[[input_device]]",+ "[[input_device]]\nnatural_scroll = true\n",+ "[[input_device]]\nid = \"\"\n",+ "[[input_device]]\nid = \"mouse\"\nid = \"other\"\n",+ "[[input_device]]\nid = \"mouse\"\n[[input_device]]\nid = \"mouse\"\n",+ "[[input_device]]\nid = \"mouse\"\npointer_speed = 1.1\n",+ "[[input_device]]\nid = \"mouse\"\npointer_speed = nan\n",+ "[[input_device]]\nid = \"mouse\"\npointer_speed = inf\n",+ "[[input_device]]\nid = \"mouse\"\nnatural_scroll = 1\n",+ "[[input_device]]\nid = \"mouse\"\nnatural_scroll = true\nnatural_scroll = false\n",+ "[[input_device]]\nid = \"mouse\"\nunknown = true\n",+ "[[input_device]]\nid = \"mouse\"\ninvert_scroll = true\n",+ "[input_device]\nid = \"mouse\"\n",+ "[[input_device]]\nid = 'mouse'\n",+ "[[input_device]]\n'id' = \"mouse\"\n",+ }) |bytes| try std.testing.expectError(error.InvalidConfig, loader.parse(std.testing.allocator, bytes, "invalid-device"));+}++test "unidentified or duplicate devices cannot obtain an arbitrary matching override" {+ const records: []const device.Record = &.{+ .{ .id = "collision", .natural_scroll = false, .pointer_speed = 0.9 },+ .{ .id = "collision", .natural_scroll = true, .pointer_speed = -0.9 },+ };+ const defaults: loader.InputConfig = .{ .natural_scroll = false, .pointer_speed = 0.1 };+ for ([_]?[]const u8{ null, "", "collision", "different" }) |id| {+ const effective = device.resolve(defaults, records, id, false);+ try std.testing.expect(!effective.natural_scroll);+ try std.testing.expectEqual(@as(f32, 0.1), effective.pointer_speed);+ }+}++test "prepared pointer changes are unpublished and only modify one field of one record" {+ var cfg = try loader.parse(std.testing.allocator, "[[input_device]]\nid = \"mouse\"\nnatural_scroll = false\n[[input_device]]\nid = \"pad\"\nnatural_scroll = true\n", "test");+ defer cfg.deinit();+ const prepared = try device.prepareSet(&cfg, "mouse", "pointer_speed", 0.6);+ try std.testing.expect(device.eql(cfg.input_devices, cfg.input_devices));+ try std.testing.expectEqual(@as(?f32, null), cfg.input_devices[0].pointer_speed);+ prepared.commit(&cfg);+ try std.testing.expectEqual(@as(?f32, 0.6), cfg.input_devices[0].pointer_speed);+ try std.testing.expectEqual(@as(?bool, false), cfg.input_devices[0].natural_scroll);+ try std.testing.expectEqual(@as(?bool, true), cfg.input_devices[1].natural_scroll);+ const added = try device.prepareSet(&cfg, "second-mouse", "natural_scroll", true);+ try std.testing.expectEqual(@as(usize, 3), added.records.len);+ try std.testing.expectEqualStrings("second-mouse", added.record.id);+ try std.testing.expectEqual(@as(?f32, null), added.record.pointer_speed);+ try std.testing.expectEqual(@as(usize, 2), cfg.input_devices.len);+ added.commit(&cfg);+ try std.testing.expectEqual(@as(usize, 3), cfg.input_devices.len);+ try std.testing.expectError(error.InvalidValue, device.prepareSet(&cfg, "mouse", "pointer_speed", std.math.nan(f32)));+}++test "reloading new defaults retains per-device overrides" {+ const records: []const device.Record = &.{.{ .id = "mouse", .natural_scroll = false }};+ const before = device.resolve(.{ .natural_scroll = true, .pointer_speed = 0.1 }, records, "mouse", false);+ const after = device.resolve(.{ .natural_scroll = true, .pointer_speed = 0.7 }, records, "mouse", false);+ try std.testing.expect(!before.natural_scroll and !after.natural_scroll);+ try std.testing.expectEqual(@as(f32, 0.1), before.pointer_speed);+ try std.testing.expectEqual(@as(f32, 0.7), after.pointer_speed);+}++test "reset clears explicit overrides while inheritance indicators reflect presence not equality" {+ var cfg = try loader.parse(+ std.testing.allocator,+ "[input]\nnatural_scroll = false\npointer_speed = 0.2\n" +++ "[[input_device]]\nid = \"mouse\"\nnatural_scroll = false\npointer_speed = 0.2\n" +++ "[[input_device]]\nid = \"pad\"\ntap_to_click = false\n",+ "test",+ );+ defer cfg.deinit();+ try std.testing.expect(device.hasOverrides(cfg.input_devices, "mouse"));+ try std.testing.expect(device.isOverridden(cfg.input_devices, "mouse", "natural_scroll"));+ try std.testing.expect(device.isOverridden(cfg.input_devices, "mouse", "pointer_speed"));+ try std.testing.expect(!device.isOverridden(cfg.input_devices, "mouse", "tap_to_click"));+ try std.testing.expect(!device.hasOverrides(cfg.input_devices, null));+ try std.testing.expect(!device.isOverridden(cfg.input_devices, "absent", "natural_scroll"));+ const reset = try device.prepareReset(&cfg, "mouse");+ try std.testing.expect(device.hasOverrides(cfg.input_devices, "mouse"));+ reset.commit(&cfg);+ try std.testing.expect(!device.hasOverrides(cfg.input_devices, "mouse"));+ try std.testing.expect(!device.isOverridden(cfg.input_devices, "mouse", "natural_scroll"));+ try std.testing.expect(device.hasOverrides(cfg.input_devices, "pad"));+ cfg.input.natural_scroll = true;+ cfg.input.pointer_speed = 0.6;+ const inherited = device.resolve(cfg.input, cfg.input_devices, "mouse", false);+ try std.testing.expect(inherited.natural_scroll);+ try std.testing.expectEqual(@as(f32, 0.6), inherited.pointer_speed);+ const absent = try device.prepareReset(&cfg, "absent");+ try std.testing.expectEqual(@as(?usize, null), absent.index);+ absent.commit(&cfg);+ try std.testing.expectEqual(@as(usize, 2), cfg.input_devices.len);+ try std.testing.expectError(error.InvalidValue, device.prepareReset(&cfg, ""));+}diff --git a/src/config/loader.zig b/src/config/loader.zigindex 8091e6d..89f2341 100644--- a/src/config/loader.zig+++ b/src/config/loader.zig@@ -16,6 +16,7 @@ pub const window_rules = @import("window_rules.zig");pub const WindowRule = window_rules.WindowRule;pub const sandbox_allow = @import("sandbox_allow.zig");pub const SandboxAllowRule = sandbox_allow.SandboxAllowRule;+pub const input_device = @import("input_device.zig");const anim = @import("ui").anim;const anim_cfg = @import("animations.zig");const output_transform = @import("output_transform.zig");@@ -356,6 +357,7 @@ pub const Config = struct {/// Null (no section) follows the main theme. Only taskbar tokens are set.taskbar_theme: ?Theme = null,input: InputConfig = .{},+ input_devices: []input_device.Record = &.{},input_method: struct { env: types.InputMethod = .none } = .{},keyboard_keymap: ?*xkb.Keymap = null,compositor: CompositorConfig = .{},diff --git a/src/config/loader_fields.zig b/src/config/loader_fields.zigindex 8c8d79b..0ff0218 100644--- a/src/config/loader_fields.zig+++ b/src/config/loader_fields.zig@@ -86,6 +86,16 @@ pub const input_rules: std.enums.EnumFieldStruct(std.meta.FieldEnum(InputConfig).caret_motion_ms = .{ .uint = .{ .min = 0, .max = 2000 } },};+pub const input_device_rules: std.enums.EnumFieldStruct(std.meta.FieldEnum(@import("input_device.zig").Record), FieldRule, null) = .{+ .id = .string,+ .pointer_speed = input_rules.pointer_speed,+ .natural_scroll = input_rules.natural_scroll,+ .left_handed = input_rules.left_handed,+ .tap_to_click = input_rules.tap_to_click,+ .tap_drag = input_rules.tap_drag,+ .disable_while_typing = input_rules.disable_while_typing,+};+pub const region_rules: std.enums.EnumFieldStruct(std.meta.FieldEnum(RegionConfig), FieldRule, null) = .{.timezone = .string,.language = .string,diff --git a/src/config/loader_parse.zig b/src/config/loader_parse.zigindex 459bebd..ebe046d 100644--- a/src/config/loader_parse.zig+++ b/src/config/loader_parse.zig@@ -36,79 +36,45 @@ const default_zoom_percents = loader.default_zoom_percents;const OutputConfig = loader.OutputConfig;const NotificationRule = loader.NotificationRule;const Config = loader.Config;+const input_device = @import("input_device.zig");-pub fn parse(allocator: Allocator, bytes: []const u8, path: []const u8) !Config {- var cfg = try initEmpty(allocator);- errdefer cfg.deinit();- cfg.path = try cfg.arena.allocator().dupe(u8, path);+const ParseState = struct {+ seen_keybinds: bool = false,+ seen_frame_radius: bool = false,+ autostart_list: std.ArrayListUnmanaged([]const u8) = .empty,+ bind_list: std.ArrayListUnmanaged(Keybind) = .empty,+ workspace_binds: std.ArrayListUnmanaged(Keybind) = .empty,+ outputs_list: std.ArrayListUnmanaged(OutputConfig) = .empty,+ current_output: OutputConfig = .{},+ have_current_output: bool = false,+ rule_list: std.ArrayListUnmanaged(WindowRule) = .empty,+ current_rule: WindowRule = .{},+ have_current_rule: bool = false,+ notif_rule_list: std.ArrayListUnmanaged(NotificationRule) = .empty,+ current_notif_rule: NotificationRule = .{},+ have_current_notif_rule: bool = false,+ sandbox_allow_list: std.ArrayListUnmanaged(SandboxAllowRule) = .empty,+ current_sandbox_allow: SandboxAllowRule = .{},+ have_current_sandbox_allow: bool = false,+ section: Section = .none,+ pointer_records: input_device.Parser = .{},+ target_flags: [anim.Target.count]anim_cfg.TargetFlags = @splat(.{}),- var seen_keybinds = false;- var seen_frame_radius = false;- var autostart_list: std.ArrayListUnmanaged([]const u8) = .empty;- var bind_list: std.ArrayListUnmanaged(Keybind) = .empty;- var workspace_binds: std.ArrayListUnmanaged(Keybind) = .empty;- var outputs_list: std.ArrayListUnmanaged(OutputConfig) = .empty;- var current_output: OutputConfig = .{};- var have_current_output = false;- var rule_list: std.ArrayListUnmanaged(WindowRule) = .empty;- var current_rule: WindowRule = .{};- var have_current_rule = false;- var notif_rule_list: std.ArrayListUnmanaged(NotificationRule) = .empty;- var current_notif_rule: NotificationRule = .{};- var have_current_notif_rule = false;- var sandbox_allow_list: std.ArrayListUnmanaged(SandboxAllowRule) = .empty;- var current_sandbox_allow: SandboxAllowRule = .{};- var have_current_sandbox_allow = false;- var section: Section = .none;- var target_flags: [anim.Target.count]anim_cfg.TargetFlags = @splat(.{});- var line_no: usize = 0;-- var lines = std.mem.splitScalar(u8, bytes, '\n');- while (lines.next()) |raw_line| {- line_no += 1;- const line = theme_mod.stripComment(std.mem.trim(u8, raw_line, " \t\r"));- if (line.len == 0) continue;-- if (line[0] == '[') {- try flushArrayTables(&cfg, path, line_no, section, &outputs_list, ¤t_output, &have_current_output, &rule_list, ¤t_rule, &have_current_rule, ¬if_rule_list, ¤t_notif_rule, &have_current_notif_rule, &sandbox_allow_list, ¤t_sandbox_allow, &have_current_sandbox_allow);- section = parseSection(line) catch |err| {- if (err == error.UnknownAnimationTarget) {- const close = std.mem.indexOfScalar(u8, line, ']') orelse line.len;- const name = if (line.len > 1 and close > 1) line[1..close] else line;- const target = if (std.mem.startsWith(u8, name, "animations.")) name["animations.".len..] else name;- fail(path, line_no, "unknown animation target '{s}'", .{target});- } else {- fail(path, line_no, "invalid section header", .{});- }- return error.InvalidConfig;- };- if (section == .keybinds) seen_keybinds = true;- // Its presence alone chooses a taskbar theme, even with no keys.- if (section == .taskbar_theme and cfg.taskbar_theme == null) cfg.taskbar_theme = .{};- continue;- }-- const eq = std.mem.indexOfScalar(u8, line, '=') orelse {- fail(path, line_no, "expected key = value", .{});- return error.InvalidConfig;- };- const key = unquoteKey(std.mem.trim(u8, line[0..eq], " \t"));- const value = std.mem.trim(u8, line[eq + 1 ..], " \t");-- switch (section) {+ fn apply(state: *ParseState, cfg: *Config, path: []const u8, line_no: usize, key: []const u8, value: []const u8) !void {+ switch (state.section) {.none => {},.theme => {if (std.mem.eql(u8, key, "base")) {const id = try theme_mod.unquote(value);if (id.len > 0 and !@import("theme_pack.zig").validId(id)) return error.InvalidConfig;cfg.theme_base = try cfg.arena.allocator().dupe(u8, id);- continue;+ return;}theme_mod.applyKey(cfg.arena.allocator(), &cfg.theme, key, value) catch |err| {fail(path, line_no, "invalid theme field '{s}': {s}", .{ key, @errorName(err) });return error.InvalidConfig;};- if (std.mem.eql(u8, key, "radius_lg")) seen_frame_radius = true;+ if (std.mem.eql(u8, key, "radius_lg")) state.seen_frame_radius = true;},.taskbar_theme => {// Other theme keys are ignored, so a whole theme file's body can be pasted in.@@ -126,6 +92,10 @@ pub fn parse(allocator: Allocator, bytes: []const u8, path: []const u8) !Configfail(path, line_no, "invalid input field '{s}': {s}", .{ key, @errorName(err) });return error.InvalidConfig;},+ .input_device => state.pointer_records.apply(cfg.arena.allocator(), key, value) catch |err| {+ fail(path, line_no, "invalid input_device field '{s}': {s}", .{ key, @errorName(err) });+ return error.InvalidConfig;+ },.compositor => applyCompositorKey(&cfg.compositor, cfg.arena.allocator(), key, value) catch |err| {fail(path, line_no, "invalid compositor field '{s}': {s}", .{ key, @errorName(err) });return error.InvalidConfig;@@ -140,14 +110,14 @@ pub fn parse(allocator: Allocator, bytes: []const u8, path: []const u8) !Configfail(path, line_no, "autostart cmd must be a quoted string", .{});return error.InvalidConfig;};- autostart_list.append(cfg.arena.allocator(), cmd) catch {+ state.autostart_list.append(cfg.arena.allocator(), cmd) catch {return error.OutOfMemory;};}},.outputs => {- have_current_output = true;- const known = applyField(¤t_output, cfg.arena.allocator(), output_rules, key, value) catch {+ state.have_current_output = true;+ const known = applyField(&state.current_output, cfg.arena.allocator(), output_rules, key, value) catch {fail(path, line_no, "outputs {s} must be {s}", .{ key, fieldHint(OutputConfig, output_rules, key) });return error.InvalidConfig;};@@ -157,15 +127,15 @@ pub fn parse(allocator: Allocator, bytes: []const u8, path: []const u8) !Config}},.window_rules => {- have_current_rule = true;- window_rules.applyRuleKey(¤t_rule, cfg.arena.allocator(), key, value) catch |err| {+ state.have_current_rule = true;+ window_rules.applyRuleKey(&state.current_rule, cfg.arena.allocator(), key, value) catch |err| {fail(path, line_no, "invalid window_rules field '{s}': {s}", .{ key, @errorName(err) });return error.InvalidConfig;};},.sandbox_allow => {- have_current_sandbox_allow = true;- sandbox_allow.applyKey(¤t_sandbox_allow, cfg.arena.allocator(), key, value, path, line_no) catch |err| {+ state.have_current_sandbox_allow = true;+ sandbox_allow.applyKey(&state.current_sandbox_allow, cfg.arena.allocator(), key, value, path, line_no) catch |err| {fail(path, line_no, "invalid sandbox_allow field '{s}': {s}", .{ key, @errorName(err) });return error.InvalidConfig;};@@ -203,7 +173,7 @@ pub fn parse(allocator: Allocator, bytes: []const u8, path: []const u8) !Configfail(path, line_no, "invalid action '{s}'", .{action_str});return error.InvalidConfig;};- const list = if (section == .workspace_keybinds) &workspace_binds else &bind_list;+ const list = if (state.section == .workspace_keybinds) &state.workspace_binds else &state.bind_list;list.append(cfg.arena.allocator(), .{.modifiers = spec.modifiers,.sym = spec.sym,@@ -215,8 +185,8 @@ pub fn parse(allocator: Allocator, bytes: []const u8, path: []const u8) !Configreturn error.InvalidConfig;},.notification_rules => {- have_current_notif_rule = true;- applyNotificationRuleKey(¤t_notif_rule, cfg.arena.allocator(), key, value) catch |err| {+ state.have_current_notif_rule = true;+ applyNotificationRuleKey(&state.current_notif_rule, cfg.arena.allocator(), key, value) catch |err| {fail(path, line_no, "invalid notification_rules field '{s}': {s}", .{ key, @errorName(err) });return error.InvalidConfig;};@@ -226,7 +196,7 @@ pub fn parse(allocator: Allocator, bytes: []const u8, path: []const u8) !Configreturn error.InvalidConfig;},.animation_target => |target| {- anim_cfg.applyTargetKey(&cfg.animations, target, &target_flags[@intFromEnum(target)], key, value) catch |err| {+ anim_cfg.applyTargetKey(&cfg.animations, target, &state.target_flags[@backingInt(target)], key, value) catch |err| {fail(path, line_no, "invalid animations.{s} field '{s}': {s}", .{ @tagName(target), key, @errorName(err) });return error.InvalidConfig;};@@ -234,88 +204,146 @@ pub fn parse(allocator: Allocator, bytes: []const u8, path: []const u8) !Config}}- // Legacy frame geometry is a fallback; theme numbers take precedence,- // including a REDIWM_THEME overlay applied after this parse.- if (!seen_frame_radius) cfg.theme.radius_lg = @floatFromInt(cfg.compositor.border_radius);-- try flushArrayTables(&cfg, path, line_no, section, &outputs_list, ¤t_output, &have_current_output, &rule_list, ¤t_rule, &have_current_rule, ¬if_rule_list, ¤t_notif_rule, &have_current_notif_rule, &sandbox_allow_list, ¤t_sandbox_allow, &have_current_sandbox_allow);+ fn finish(state: *ParseState, cfg: *Config, allocator: Allocator, path: []const u8, line_no: usize) !void {+ // Legacy frame geometry is a fallback; theme numbers take precedence,+ // including a REDIWM_THEME overlay applied after this parse.+ if (!state.seen_frame_radius) cfg.theme.radius_lg = @floatFromInt(cfg.compositor.border_radius);+ if (state.section == .input_device) try flushInputDevices(&state.pointer_records, cfg, path, line_no);+ cfg.input_devices = state.pointer_records.records.items;- if (cfg.idle.blank_after_seconds > 0 and cfg.idle.suspend_after_seconds > 0 and cfg.idle.suspend_after_seconds <= cfg.idle.blank_after_seconds) {- fail(path, line_no, "suspend_after_seconds must be greater than blank_after_seconds", .{});- return error.InvalidConfig;- }+ try flushArrayTables(cfg, path, line_no, state.section, &state.outputs_list, &state.current_output, &state.have_current_output, &state.rule_list, &state.current_rule, &state.have_current_rule, &state.notif_rule_list, &state.current_notif_rule, &state.have_current_notif_rule, &state.sandbox_allow_list, &state.current_sandbox_allow, &state.have_current_sandbox_allow);- if (cfg.night_light.start == cfg.night_light.end) {- fail(path, line_no, "night_light start cannot equal end", .{});- return error.InvalidConfig;- }+ if (cfg.idle.blank_after_seconds > 0 and cfg.idle.suspend_after_seconds > 0 and cfg.idle.suspend_after_seconds <= cfg.idle.blank_after_seconds) {+ fail(path, line_no, "suspend_after_seconds must be greater than blank_after_seconds", .{});+ return error.InvalidConfig;+ }- const nl_night_span = @mod(@as(i32, cfg.night_light.end) - @as(i32, cfg.night_light.start) + 1440, 1440);- const nl_day_span = 1440 - nl_night_span;- if (cfg.night_light.transition_minutes >= nl_night_span or cfg.night_light.transition_minutes >= nl_day_span) {- fail(path, line_no, "night_light transition_minutes must be shorter than both night and day spans", .{});- return error.InvalidConfig;- }+ if (cfg.night_light.start == cfg.night_light.end) {+ fail(path, line_no, "night_light start cannot equal end", .{});+ return error.InvalidConfig;+ }- if (cfg.night_light.schedule == .sun) {- if (cfg.night_light.latitude == null or cfg.night_light.longitude == null) {- fail(path, line_no, "night_light schedule 'sun' requires both latitude and longitude", .{});+ const nl_night_span = @mod(@as(i32, cfg.night_light.end) - @as(i32, cfg.night_light.start) + 1440, 1440);+ const nl_day_span = 1440 - nl_night_span;+ if (cfg.night_light.transition_minutes >= nl_night_span or cfg.night_light.transition_minutes >= nl_day_span) {+ fail(path, line_no, "night_light transition_minutes must be shorter than both night and day spans", .{});return error.InvalidConfig;}- }- if (seen_keybinds) {- // Keep laptop controls, System Monitor, nested-session switching and- // the way out of an inhibiting client available in existing configs too.- // Explicit bindings (including noop) always take precedence.- const defaults = try parseKeybindsOnly(cfg.arena.allocator(), default_file.source);- for (defaults) |bind| {- const nested_switcher = bind.modifiers.ctrl and (bind.action == .focus_next or bind.action == .focus_prev);- if (!keybinds.isHardwareAction(bind.action) and !nested_switcher and bind.action != .restore_shortcuts and bind.action != .open_system_monitor) continue;- const key = keybinds.pack(bind.modifiers, bind.sym);- var overridden = false;- for (bind_list.items) |custom| {- if (keybinds.pack(custom.modifiers, custom.sym) == key) {- overridden = true;- break;+ if (cfg.night_light.schedule == .sun) {+ if (cfg.night_light.latitude == null or cfg.night_light.longitude == null) {+ fail(path, line_no, "night_light schedule 'sun' requires both latitude and longitude", .{});+ return error.InvalidConfig;+ }+ }++ if (state.seen_keybinds) {+ // Keep laptop controls, System Monitor, nested-session switching and+ // the way out of an inhibiting client available in existing configs too.+ // Explicit bindings (including noop) always take precedence.+ const defaults = try parseKeybindsOnly(cfg.arena.allocator(), default_file.source);+ for (defaults) |bind| {+ const nested_switcher = bind.modifiers.ctrl and (bind.action == .focus_next or bind.action == .focus_prev);+ if (!keybinds.isHardwareAction(bind.action) and !nested_switcher and bind.action != .restore_shortcuts and bind.action != .open_system_monitor) continue;+ const key = keybinds.pack(bind.modifiers, bind.sym);+ var overridden = false;+ for (state.bind_list.items) |custom| {+ if (keybinds.pack(custom.modifiers, custom.sym) == key) {+ overridden = true;+ break;+ }}+ if (!overridden) try state.bind_list.append(cfg.arena.allocator(), bind);}- if (!overridden) try bind_list.append(cfg.arena.allocator(), bind);+ cfg.keybinds = state.bind_list.items;+ } else {+ try applyDefaultKeybinds(cfg);}- cfg.keybinds = bind_list.items;- } else {- try applyDefaultKeybinds(&cfg);- }- try applyWorkspaceKeybinds(&cfg, workspace_binds);- cfg.autostart = autostart_list.items;- cfg.outputs = outputs_list.items;- var have_primary = false;- for (cfg.outputs) |output| {- if (!output.primary) continue;- if (have_primary) {- fail(path, line_no, "outputs may contain only one primary monitor", .{});- return error.InvalidConfig;+ try applyWorkspaceKeybinds(cfg, state.workspace_binds);+ cfg.autostart = state.autostart_list.items;+ cfg.outputs = state.outputs_list.items;+ var have_primary = false;+ for (cfg.outputs) |output| {+ if (!output.primary) continue;+ if (have_primary) {+ fail(path, line_no, "outputs may contain only one primary monitor", .{});+ return error.InvalidConfig;+ }+ have_primary = true;}- have_primary = true;+ cfg.window_rules = state.rule_list.items;+ cfg.notification_rules = state.notif_rule_list.items;+ cfg.sandbox_allow = state.sandbox_allow_list.items;+ try rebuildLookup(cfg);+ finishCompositor(cfg);+ // An explicit [animations.camera_desktop] table wins over the settings value.+ if (std.meta.eql(state.target_flags[@backingInt(anim.Target.camera_desktop)], anim_cfg.TargetFlags{})) {+ cfg.animations.targets[@backingInt(anim.Target.camera_desktop)].curve = anim.desktopSwitchCurve(cfg.compositor.desktop_switch_ms);+ }+ cfg.keyboard_keymap = @import("keymap.zig").compile(allocator, cfg.input) catch return error.InvalidConfig;}- cfg.window_rules = rule_list.items;- cfg.notification_rules = notif_rule_list.items;- cfg.sandbox_allow = sandbox_allow_list.items;- try rebuildLookup(&cfg);- finishCompositor(&cfg);- // An explicit [animations.camera_desktop] table wins over the settings value.- if (std.meta.eql(target_flags[@intFromEnum(anim.Target.camera_desktop)], anim_cfg.TargetFlags{})) {- cfg.animations.targets[@intFromEnum(anim.Target.camera_desktop)].curve = anim.desktopSwitchCurve(cfg.compositor.desktop_switch_ms);+};++pub fn parse(allocator: Allocator, bytes: []const u8, path: []const u8) !Config {+ var cfg = try initEmpty(allocator);+ errdefer cfg.deinit();+ cfg.path = try cfg.arena.allocator().dupe(u8, path);++ var state: ParseState = .{};+ var line_no: usize = 0;++ var lines = std.mem.splitScalar(u8, bytes, '\n');+ while (lines.next()) |raw_line| {+ line_no += 1;+ const line = theme_mod.stripComment(std.mem.trim(u8, raw_line, " \t\r"));+ if (line.len == 0) continue;++ if (line[0] == '[') {+ if (state.section == .input_device) try flushInputDevices(&state.pointer_records, &cfg, path, line_no);+ try flushArrayTables(&cfg, path, line_no, state.section, &state.outputs_list, &state.current_output, &state.have_current_output, &state.rule_list, &state.current_rule, &state.have_current_rule, &state.notif_rule_list, &state.current_notif_rule, &state.have_current_notif_rule, &state.sandbox_allow_list, &state.current_sandbox_allow, &state.have_current_sandbox_allow);+ state.section = parseSection(line) catch |err| {+ if (err == error.UnknownAnimationTarget) {+ const close = std.mem.indexOfScalar(u8, line, ']') orelse line.len;+ const name = if (line.len > 1 and close > 1) line[1..close] else line;+ const target = if (std.mem.startsWith(u8, name, "animations.")) name["animations.".len..] else name;+ fail(path, line_no, "unknown animation target '{s}'", .{target});+ } else {+ fail(path, line_no, "invalid section header", .{});+ }+ return error.InvalidConfig;+ };+ if (state.section == .keybinds) state.seen_keybinds = true;+ // Its presence alone chooses a taskbar theme, even with no keys.+ if (state.section == .taskbar_theme and cfg.taskbar_theme == null) cfg.taskbar_theme = .{};+ continue;+ }++ const eq = std.mem.indexOfScalar(u8, line, '=') orelse {+ fail(path, line_no, "expected key = value", .{});+ return error.InvalidConfig;+ };+ const key = unquoteKey(std.mem.trim(u8, line[0..eq], " \t"));+ const value = std.mem.trim(u8, line[eq + 1 ..], " \t");++ try state.apply(&cfg, path, line_no, key, value);}- cfg.keyboard_keymap = @import("keymap.zig").compile(allocator, cfg.input) catch return error.InvalidConfig;+ try state.finish(&cfg, allocator, path, line_no);return cfg;}+fn flushInputDevices(parser: *input_device.Parser, cfg: *Config, path: []const u8, line_no: usize) !void {+ parser.flush(cfg.arena.allocator()) catch |err| {+ fail(path, line_no, "invalid input_device record: {s}", .{@errorName(err)});+ return error.InvalidConfig;+ };+}+pub const Section = union(enum) {none,theme,taskbar_theme,input,+ input_device,input_method,compositor,region,@@ -388,13 +416,14 @@ pub fn flushArrayTables(pub fn parseSection(line: []const u8) !Section {if (std.mem.startsWith(u8, line, "[[")) {- inline for (.{ .autostart, .outputs, .window_rules, .notification_rules, .sandbox_allow }) |tag| {+ inline for (.{ .autostart, .outputs, .window_rules, .notification_rules, .sandbox_allow, .input_device }) |tag| {if (std.mem.eql(u8, line, "[[" ++ @tagName(tag) ++ "]]")) return tag;}return error.InvalidConfig;}const close = std.mem.indexOfScalar(u8, line, ']') orelse return error.InvalidConfig;const name = line[1..close];+ if (std.mem.eql(u8, name, "input_device")) return error.InvalidConfig;if (std.mem.eql(u8, name, "keybinds.workspace")) return .workspace_keybinds;// Array tables and internal tags are deliberately not accepted here.inline for (.{ .theme, .taskbar_theme, .input, .input_method, .compositor, .region, .keybinds, .polkit, .idle, .night_light, .notifications, .desktop, .ipc, .animations }) |tag| {diff --git a/src/config/mod.zig b/src/config/mod.zigindex c2a2e46..6afca89 100644--- a/src/config/mod.zig+++ b/src/config/mod.zig@@ -2,6 +2,7 @@pub const animations = @import("animations.zig");pub const app_theme = @import("app_theme.zig");pub const default = @import("default.zig");+pub const input_device = @import("input_device.zig");pub const keybinds = @import("keybinds.zig");pub const keymap = @import("keymap.zig");pub const loader = @import("loader.zig");diff --git a/src/config/setting_save.zig b/src/config/setting_save.zigindex e6aebe1..cc97939 100644--- a/src/config/setting_save.zig+++ b/src/config/setting_save.zig@@ -4,6 +4,8 @@ const std = @import("std");const Io = std.Io;const loader = @import("loader.zig");const theme = @import("ui").theme;+pub const saveInputDevice = @import("input_device_save.zig").save;+pub const resetInputDevice = @import("input_device_save.zig").reset;pub fn saveInput(allocator: std.mem.Allocator, io: Io, path: []const u8, comptime key: []const u8, value: @FieldType(loader.InputConfig, key)) !void {try save(allocator, io, path, "input", key, value);@@ -113,7 +115,7 @@ pub fn saveCanvas(allocator: std.mem.Allocator, io: Io, path: []const u8, columntry writeValidated(allocator, io, path, result);}-fn writeValidated(allocator: std.mem.Allocator, io: Io, path: []const u8, result: []const u8) !void {+pub fn writeValidated(allocator: std.mem.Allocator, io: Io, path: []const u8, result: []const u8) !void {var checked = try loader.parse(allocator, result, path);defer checked.deinit();const stat = try Io.Dir.cwd().statFile(io, path, .{});diff --git a/src/config_runtime/apply.zig b/src/config_runtime/apply.zigindex e2be022..bed9de9 100644--- a/src/config_runtime/apply.zig+++ b/src/config_runtime/apply.zig@@ -1,6 +1,6 @@//! Apply parsed configuration to the running compositor. Kept outside the config module.const std = @import("std");-const wlr = @import("wlroots");+const Pointer = @import("../Pointer.zig");const Server = @import("../Server.zig");const loader = @import("config").loader;const Config = loader.Config;@@ -76,7 +76,7 @@ pub fn applyDiff(server: *Server, old: Config, new: Config) void {}}- if (!inputEql(old.input, new.input)) {+ if (!inputEql(old.input, new.input) or !@import("config").input_device.eql(old.input_devices, new.input_devices)) {applyInputConfig(server, new.input);}if (!@import("config").keymap.namesEqual(old.input, new.input)) {@@ -284,7 +284,7 @@ pub fn applyInputConfig(server: *Server, cfg: InputConfig) void {server.input.updateAccel(cfg.accel_profile, cfg.accel_p1, cfg.accel_p2, cfg.accel_max_speed);var pit = server.input.pointers.iterator(.forward);- while (pit.next()) |pointer| applyPointerDevice(pointer.device, cfg);+ while (pit.next()) |pointer| applyPointerDevice(pointer);var kit = server.input.keyboards.iterator(.forward);while (kit.next()) |kb| {@@ -292,18 +292,24 @@ pub fn applyInputConfig(server: *Server, cfg: InputConfig) void {}}-pub fn applyPointerDevice(device: *wlr.InputDevice, cfg: InputConfig) void {- if (libinput.isTouchpad(device)) {- libinput.setPointerSpeed(device, cfg.pointer_speed_touchpad);- libinput.setDisableWhileTyping(device, cfg.disable_while_typing_touchpad);- } else {- libinput.setPointerSpeed(device, cfg.pointer_speed);- libinput.setDisableWhileTyping(device, cfg.disable_while_typing);- }- libinput.setNaturalScroll(device, cfg.natural_scroll);- libinput.setLeftHanded(device, cfg.left_handed);- libinput.setTapToClick(device, cfg.tap_to_click);- libinput.setTapDrag(device, cfg.tap_drag);+pub fn applyPointerDevice(pointer: *Pointer) void {+ const config = &pointer.input.server.config;+ const device = pointer.device;+ const effective = @import("config").input_device.resolve(config.input, config.input_devices, pointer.persistentId(), libinput.isTouchpad(device));+ inline for (.{+ .{ "pointer_speed", libinput.setPointerSpeed },+ .{ "natural_scroll", libinput.setNaturalScroll },+ .{ "left_handed", libinput.setLeftHanded },+ .{ "tap_to_click", libinput.setTapToClick },+ .{ "tap_drag", libinput.setTapDrag },+ .{ "disable_while_typing", libinput.setDisableWhileTyping },+ }) |setting| {+ // Unsupported settings inherit harmlessly; rejected supported values+ // are logged, and Settings reads the actual backend state.+ if (setting[1](device, @field(effective, setting[0])) == .failed) {+ log.warn("could not apply pointer setting '{s}' to '{s}'", .{ setting[0], libinput.getName(device) orelse "pointer" });+ }+ }}pub fn applyWindowOpacity(server: *Server) void {diff --git a/src/control_center/ControlCenter.zig b/src/control_center/ControlCenter.zigindex 508065b..8f91e41 100644--- a/src/control_center/ControlCenter.zig+++ b/src/control_center/ControlCenter.zig@@ -140,7 +140,7 @@ desktop: desktop_section.Section = .{},region: region_section.Section = .{},portals: portal_section.Section = .{},default_apps: default_apps_section.Section = .{},-input: input_section.Section = undefined,+input: input_section.Section = .{},users: users_section.Section = .{},network: network_section.Section = .{},bluetooth: bluetooth_section.Section = .{},@@ -239,6 +239,7 @@ pub fn destroy(cc: *ControlCenter) void {if (cc.systemd_client) |client| client.detachSettings();cc.welcome.deinit();cc.search.deinit();+ cc.input.arena.deinit();cc.services.deinit();cc.printers.deinit();cc.network.deinit();diff --git a/src/control_center/keys.zig b/src/control_center/keys.zigindex 70b162c..c2ef211 100644--- a/src/control_center/keys.zig+++ b/src/control_center/keys.zig@@ -82,7 +82,7 @@ pub fn focusSearch(cc: *ControlCenter) void {pub fn selectKey(cc: *ControlCenter, key: ui.input.Key, shift: bool) bool {if (settings_search.key(cc, key, shift)) return true;- if (cc.page != .displays and cc.page != .appearance and cc.page != .desktop and cc.page != .general and cc.page != .users and cc.page != .services and cc.page != .printers and cc.page != .network and cc.page != .bluetooth and cc.page != .region) return false;+ if (cc.page != .input and cc.page != .displays and cc.page != .appearance and cc.page != .desktop and cc.page != .general and cc.page != .users and cc.page != .services and cc.page != .printers and cc.page != .network and cc.page != .bluetooth and cc.page != .region) return false;const dispatcher = &ui.input.current;if (cc.page == .appearance) {if (appearance_section.itemKey(&cc.appearance, key)) return true;@@ -99,7 +99,7 @@ pub fn selectKey(cc: *ControlCenter, key: ui.input.Key, shift: bool) bool {}}}- if (cc.is_welcome or cc.page == .users or cc.page == .services or cc.page == .printers or cc.page == .network or cc.page == .bluetooth or cc.page == .region) {+ if (cc.is_welcome or cc.page == .input or cc.page == .users or cc.page == .services or cc.page == .printers or cc.page == .network or cc.page == .bluetooth or cc.page == .region) {const focused = dispatcher.focused;if (cc.page == .bluetooth and bluetooth_section.key(cc, key)) return true;if (cc.page == .network and (focused == null or focused.?.kind != .select or !focused.?.kind.select.open)) {diff --git a/src/control_center/search_index.zig b/src/control_center/search_index.zigindex d400276..fa6ebaa 100644--- a/src/control_center/search_index.zig+++ b/src/control_center/search_index.zig@@ -34,9 +34,12 @@ const source_entries = [_]SourceEntry{.{ .page = .services, .title = i18n.msg("Services"), .target = "", .keywords = i18n.msg("") },.{ .page = .general, .title = i18n.msg("Brightness"), .target = "@Brightness", .heading = i18n.msg("Brightness"), .keywords = i18n.msg("backlight screen light") },.{ .page = .general, .title = i18n.msg("Open files with a single click"), .target = "files_single_click_open", .keywords = i18n.msg("double click folders") },- .{ .page = .input, .title = i18n.msg("Mouse speed"), .target = "mouse_speed", .keywords = i18n.msg("pointer acceleration sensitivity") },- .{ .page = .input, .title = i18n.msg("Touchpad speed"), .target = "touchpad_speed", .keywords = i18n.msg("trackpad acceleration sensitivity") },- .{ .page = .input, .title = i18n.msg("Disable touchpad while typing"), .target = "touchpad_disable_while_typing", .keywords = i18n.msg("keyboard trackpad") },+ .{ .page = .input, .title = i18n.msg("Pointer device"), .target = "pointer_device", .keywords = i18n.msg("mouse touchpad trackpad select") },+ .{ .page = .input, .title = i18n.msg("Reset pointer settings"), .target = "pointer_reset", .keywords = i18n.msg("mouse touchpad trackball default custom inherit") },+ .{ .page = .input, .title = i18n.msg("Pointer speed"), .target = "pointer_speed", .keywords = i18n.msg("mouse touchpad trackpad acceleration sensitivity") },+ .{ .page = .input, .title = i18n.msg("Disable while typing"), .target = "disable_while_typing", .keywords = i18n.msg("keyboard touchpad trackpad") },+ .{ .page = .input, .title = i18n.msg("Left-handed mode"), .target = "left_handed", .keywords = i18n.msg("mouse buttons swap primary") },+ .{ .page = .input, .title = i18n.msg("Tap and drag"), .target = "tap_drag", .keywords = i18n.msg("touchpad trackpad") },.{ .page = .input, .title = i18n.msg("Natural scroll"), .target = "natural_scroll", .keywords = i18n.msg("scrolling direction reverse invert mouse touchpad") },.{ .page = .input, .title = i18n.msg("Tap to click"), .target = "tap_to_click", .keywords = i18n.msg("touchpad trackpad") },.{ .page = .input, .title = i18n.msg("Canvas pan speed"), .target = "pan_speed", .keywords = i18n.msg("desktop panning") },diff --git a/src/control_center/sections/input.zig b/src/control_center/sections/input.zigindex e89a45f..564bc92 100644--- a/src/control_center/sections/input.zig+++ b/src/control_center/sections/input.zig@@ -1,21 +1,23 @@const i18n = @import("i18n");-// Control center "Input" section: mouse/touchpad pointer accel speed, natural-// scroll, tap-to-click (all via libinput device config, applied immediately-// to every pointer device) and keyboard repeat delay/rate (design doc Part 3,-// Section 3).+// Pointer controls read and change only the selected live device. Its stable+// identity selects a partial configuration record; keyboard and canvas controls+// remain global.//// Widget callbacks carry their owning Section explicitly.const std = @import("std");-const wlr = @import("wlroots");const layout = @import("ui").layout;const ui_slider = @import("ui").widgets.slider;-const theme = @import("ui").theme;const panel = @import("../panel.zig");const Widget = layout.Widget;const Input = @import("../../Input.zig");+const Pointer = @import("../../Pointer.zig");+const gpa = @import("../../main.zig").gpa;+const config = @import("config");const libinput = @import("../../libinput.zig");+const bool_keys = [_][]const u8{ "natural_scroll", "left_handed", "tap_to_click", "tap_drag", "disable_while_typing" };+const default_speed_step: f32 = 0.1;const default_delay_step: f32 = 50;const default_rate_step: f32 = 5;@@ -57,136 +59,401 @@ fn keyboardLayoutIndex(cfg: anytype) ?usize {return null;}-const PointerKind = enum { mouse, touchpad };-pub const Section = struct {root: Widget = undefined,top_children: [2]Widget = undefined,- row_storage: [10]Widget = undefined,+ row_storage: [12]Widget = undefined,row_count: usize = 0,- mouse_speed_group_children: [2]Widget = undefined,- mouse_speed_header_children: [2]Widget = undefined,- touchpad_speed_group_children: [2]Widget = undefined,- touchpad_speed_header_children: [2]Widget = undefined,- touchpad_dwt_row_children: [2]Widget = undefined,+ selector_children: [3]Widget = undefined,+ selector_header_children: [2]Widget = undefined,+ speed_group_children: [2]Widget = undefined,+ speed_header_children: [2]Widget = undefined,+ speed_label_children: [2]Widget = undefined,+ bool_row_children: [5][2]Widget = undefined,+ bool_label_children: [5][2]Widget = undefined,speed_value_buf: [16]u8 = undefined,- touchpad_speed_value_buf: [16]u8 = undefined,- natural_row_children: [2]Widget = undefined,- tap_row_children: [2]Widget = undefined,- left_row_children: [2]Widget = undefined,layout_row_children: [2]Widget = undefined,pan_speed_row_children: [2]Widget = undefined,delay_row_children: [2]Widget = undefined,rate_row_children: [2]Widget = undefined,+ // Labels and token arrays belong to the section, never to a device or to+ // the replaceable configuration arena. Tokens are resolved again on use.+ arena: std.heap.ArenaAllocator = .init(gpa),+ device_ids: []u64 = &.{},+ device_labels: [][]const u8 = &.{},+ device_icons: []layout.IconId = &.{},+ selected_id: ?u64 = null,+ status: enum { none, unavailable, apply_failed, save_failed, rollback_failed, reset_failed, reset_restore_failed } = .none,input: *Input = undefined,};fn dimLabel(content: []const u8) Widget {- const t = panel.palette();- return .{ .kind = .{ .text = .{ .content = content, .font_size = 13, .color = t.dim } } };+ return .{ .kind = .{ .text = .{ .content = content, .font_size = 13, .color = panel.palette().dim } } };}fn fgLabel(content: []const u8) Widget {- const t = panel.palette();- return .{ .kind = .{ .text = .{ .content = content, .font_size = 13, .weight = 600, .color = t.fg } } };+ return .{ .kind = .{ .text = .{ .content = content, .font_size = 13, .weight = 600, .color = panel.palette().fg } } };}-fn firstPointerValue(input: *Input, comptime getter: fn (*wlr.InputDevice) ?bool, fallback: bool) bool {- var it = input.pointers.iterator(.forward);- while (it.next()) |pointer| {- if (getter(pointer.device)) |v| return v;- }- return fallback;+fn row(children: []Widget) Widget {+ return .{ .kind = .container, .direction = .row, .justify = .space_between, .@"align" = .center, .children = children };}-fn firstPointerValueForKind(input: *Input, kind: PointerKind, comptime getter: fn (*wlr.InputDevice) ?bool) ?bool {- var it = input.pointers.iterator(.forward);- while (it.next()) |pointer| {- const is_touchpad = libinput.isTouchpad(pointer.device);- if ((kind == .touchpad) != is_touchpad) continue;- if (getter(pointer.device)) |v| return v;- }- return null;+fn refresh(s: *Section) void {+ if (s.input.server.input.open_control_center) |cc| cc.refresh();}-fn firstPointerSpeedFor(input: *Input, kind: PointerKind) ?f32 {- var it = input.pointers.iterator(.forward);- while (it.next()) |pointer| {- const is_touchpad = libinput.isTouchpad(pointer.device);- if ((kind == .touchpad) != is_touchpad) continue;- if (libinput.getPointerSpeed(pointer.device)) |v| return @floatCast(v);- }- return null;+fn selected(s: *Section, id: usize) ?*Pointer {+ // A queued callback from the old selection must not edit the new one.+ if (s.selected_id != id) return null;+ return Pointer.find(s.input, @intCast(id));}-fn indexOfNearest(values: []const f32, v: f32) usize {- var best: usize = 0;- var best_d = @abs(values[0] - v);- for (values, 0..) |candidate, i| {- const d = @abs(candidate - v);- if (d < best_d) {- best_d = d;- best = i;+fn enumerate(s: *Section) void {+ _ = s.arena.reset(.retain_capacity);+ const a = s.arena.allocator();+ s.device_ids = &.{};+ s.device_labels = &.{};+ s.device_icons = &.{};+ const previous_selection = s.selected_id;+ s.selected_id = null;+ const count = s.input.pointers.length();+ const ids = a.alloc(u64, count) catch return;+ const labels = a.alloc([]const u8, count) catch return;+ const icons = a.alloc(layout.IconId, count) catch return;+ const duplicate = a.alloc(bool, count) catch return;+ var it = s.input.pointers.iterator(.forward);+ var n: usize = 0;+ var preferred: ?u64 = null;+ while (it.next()) |pointer| {+ const friendly = libinput.getFriendlyName(a, pointer.device) catch null;+ const raw_name = if (pointer.device.name) |p| std.mem.span(p) else "";+ const fallback_name = if (raw_name.len > 0) raw_name else i18n.tr("Pointer device");+ const label = friendly orelse (a.dupe(u8, fallback_name) catch break);+ ids[n] = pointer.id;+ labels[n] = label;+ icons[n] = switch (libinput.getKind(pointer.device)) {+ .mouse, .pointer => .mouse,+ .touchpad => .touchpad,+ .trackball => .trackball,+ };+ n += 1;+ if (preferred == null and pointer.persistentId() != null and+ (libinput.getPointerSpeed(pointer.device) != null or+ libinput.getNaturalScroll(pointer.device) != null or+ libinput.getLeftHanded(pointer.device) != null or+ libinput.getTapToClick(pointer.device) != null or+ libinput.getDisableWhileTyping(pointer.device) != null))+ {+ preferred = pointer.id;}}- return best;+ // Keep everyday names clean. Only simultaneous name collisions need a+ // live suffix; these labels never participate in configuration matching.+ @memset(duplicate[0..n], false);+ for (labels[0..n], 0..) |name, i| {+ for (labels[i + 1 .. n], i + 1..) |other, j| {+ if (std.mem.eql(u8, name, other)) {+ duplicate[i] = true;+ duplicate[j] = true;+ }+ }+ }+ for (duplicate[0..n], 0..) |collides, i| {+ if (!collides) continue;+ const pointer = Pointer.find(s.input, ids[i]) orelse continue;+ labels[i] = if (libinput.getSysname(pointer.device)) |sysname|+ std.fmt.allocPrint(a, "{s} ({s})", .{ labels[i], sysname }) catch labels[i]+ else+ std.fmt.allocPrint(a, "{s} ({d})", .{ labels[i], i + 1 }) catch labels[i];+ }+ s.device_ids = ids[0..n];+ s.device_labels = labels[0..n];+ s.device_icons = icons[0..n];+ if (previous_selection) |id| {+ if (std.mem.indexOfScalar(u64, s.device_ids, id) != null) {+ s.selected_id = id;+ return;+ }+ }+ // Automation/nested pointers remain selectable, but should not hide the+ // physical device controls when opening this page for the first time.+ s.selected_id = preferred orelse (if (n > 0) ids[0] else null);+ s.status = .none;}-fn hasTouchpad(input: *Input) bool {- var it = input.pointers.iterator(.forward);- while (it.next()) |pointer| {- if (libinput.isTouchpad(pointer.device)) return true;- }- return false;+fn statusText(s: *Section, pointer: ?*Pointer) []const u8 {+ return switch (s.status) {+ .apply_failed => i18n.tr("The device could not apply this setting."),+ .reset_failed => i18n.tr("Could not reset. The previous settings were restored."),+ .reset_restore_failed => i18n.tr("Could not reset or restore the previous settings."),+ .save_failed => i18n.tr("Could not save. The previous settings were restored."),+ .rollback_failed => i18n.tr("Could not save or restore the previous settings."),+ .unavailable => i18n.tr("This setting is unavailable on the selected device."),+ .none => if (pointer) |p|+ (if (p.persistentId() != null) i18n.tr("Settings apply only to this device.") else i18n.tr("No unique device identity; settings are unavailable."))+ else+ i18n.tr("No pointer devices connected."),+ };}-fn applyPointerSpeedTo(input: *Input, kind: PointerKind, speed: f32) void {- var it = input.pointers.iterator(.forward);- while (it.next()) |pointer| {- const is_touchpad = libinput.isTouchpad(pointer.device);- if ((kind == .touchpad) != is_touchpad) continue;- libinput.setPointerSpeed(pointer.device, speed);- }+fn buildSelector(s: *Section, row_count: *usize) ?*Pointer {+ enumerate(s);+ const pointer = if (s.selected_id) |id| Pointer.find(s.input, id) else null;+ const index = if (s.selected_id) |id| std.mem.indexOfScalar(u64, s.device_ids, id) else null;+ const identity = if (pointer) |p| p.persistentId() else null;+ s.selector_header_children = .{+ fgLabel(i18n.tr("Pointer device")),+ .{ .name = "pointer_reset", .kind = .{ .button = .{+ .label = i18n.tr("Reset to defaults"),+ .owner = s,+ .id = if (pointer) |p| @intCast(p.id) else 0,+ .on_click = &onResetDevice,+ .state = if (config.input_device.hasOverrides(s.input.server.config.input_devices, identity)) .idle else .disabled,+ } }, .height = .{ .fixed = 32 } },+ };+ s.selector_children = .{+ row(&s.selector_header_children),+ .{+ .name = "pointer_device",+ .kind = .{+ .select = .{+ .labels = s.device_labels,+ .icons = s.device_icons,+ // Also invalidate an open menu when replacement devices happen+ // to reuse the same labels and event numbers.+ .id = @intCast(std.hash.Wyhash.hash(0, std.mem.sliceAsBytes(s.device_ids))),+ .selected = index,+ .disabled = s.device_ids.len == 0,+ .placeholder = i18n.tr("No devices"),+ .owner = s,+ .on_change = &onDevicePicked,+ },+ },+ .width = .{ .percent = 1 },+ },+ dimLabel(statusText(s, pointer)),+ };+ layout.appendRow(&s.row_storage, row_count, .{ .kind = .container, .direction = .column, .gap = 8, .children = &s.selector_children });+ return pointer;}-fn applyPointerDisableWhileTypingTo(input: *Input, kind: PointerKind, on: bool) void {- var it = input.pointers.iterator(.forward);- while (it.next()) |pointer| {- const is_touchpad = libinput.isTouchpad(pointer.device);- if ((kind == .touchpad) != is_touchpad) continue;- libinput.setDisableWhileTyping(pointer.device, on);- }+fn onDevicePicked(owner: ?*anyopaque, generation: usize, index: usize) void {+ const s: *Section = @ptrCast(@alignCast(owner orelse return));+ if (generation != std.hash.Wyhash.hash(0, std.mem.sliceAsBytes(s.device_ids))) return;+ if (index >= s.device_ids.len) return;+ const id = s.device_ids[index];+ if (Pointer.find(s.input, id) == null) return refresh(s);+ s.selected_id = id;+ s.status = .none;+ refresh(s);}-fn fallbackMouseSpeed(input: *Input) f32 {- return input.server.config.input.pointer_speed;+fn originLabel(s: *Section, pointer: ?*Pointer, comptime key: []const u8, supported: bool) Widget {+ const identity = if (pointer) |p| p.persistentId() else null;+ const custom = config.input_device.isOverridden(s.input.server.config.input_devices, identity, key);+ var label = dimLabel(if (!supported) i18n.tr("Not supported") else if (custom) i18n.tr("Custom") else i18n.tr("Default"));+ label.name = key ++ "_origin";+ label.kind.text.font_size = 11;+ return label;}-fn fallbackTouchpadSpeed(input: *Input) f32 {- return input.server.config.input.pointer_speed_touchpad;+fn markCustom(s: *Section, comptime key: []const u8) void {+ const label = if (comptime std.mem.eql(u8, key, "pointer_speed")) &s.speed_label_children[1] else blk: {+ inline for (bool_keys, 0..) |candidate, i| {+ if (comptime std.mem.eql(u8, candidate, key)) break :blk &s.bool_label_children[i][1];+ }+ unreachable;+ };+ label.kind.text.content = i18n.tr("Custom");+ label.markDirty();+ s.selector_header_children[1].kind.button.state = .idle;+ s.selector_header_children[1].markDirty();}-fn fallbackMouseDisableWhileTyping(input: *Input) bool {- return input.server.config.input.disable_while_typing;+fn buildSpeed(s: *Section, pointer: ?*Pointer, row_count: *usize) void {+ const speed = if (pointer) |p| libinput.getPointerSpeed(p.device) else null;+ const editable = if (pointer) |p| p.persistentId() != null else false;+ const value: f32 = if (speed) |v| @floatCast(v) else 0;+ const formatted = std.fmt.bufPrint(&s.speed_value_buf, "{d:.1}", .{value}) catch "?";+ s.speed_label_children = .{ fgLabel(i18n.tr("Pointer speed")), originLabel(s, pointer, "pointer_speed", speed != null) };+ s.speed_header_children = .{+ .{ .kind = .container, .direction = .column, .width = .{ .flex = 1 }, .gap = 4, .children = &s.speed_label_children },+ if (speed != null) ui_slider.valuePill(formatted, 13, panel.palette().dim) else dimLabel(""),+ };+ s.speed_group_children[0] = row(&s.speed_header_children);+ var count: usize = 1;+ if (editable and speed != null) {+ s.speed_group_children[1] = .{ .name = "pointer_speed", .kind = .{ .slider = .{+ .value = value,+ .min = -1,+ .max = 1,+ .step = default_speed_step,+ .owner = s,+ .id = @intCast(pointer.?.id),+ .on_change = &onSpeedChanged,+ } } };+ count = 2;+ } else s.speed_header_children[1].name = "pointer_speed";+ layout.appendRow(&s.row_storage, row_count, .{ .kind = .container, .direction = .column, .gap = 8, .children = s.speed_group_children[0..count] });}-fn fallbackTouchpadDisableWhileTyping(input: *Input) bool {- return input.server.config.input.disable_while_typing_touchpad;+fn buildToggle(s: *Section, pointer: ?*Pointer, row_count: *usize, index: usize, comptime key: []const u8, label: []const u8, comptime getter: anytype, comptime setter: anytype) void {+ const value = if (pointer) |p| getter(p.device) else null;+ const editable = if (pointer) |p| p.persistentId() != null else false;+ s.bool_label_children[index] = .{ fgLabel(label), originLabel(s, pointer, key, value != null) };+ s.bool_row_children[index] = .{+ .{ .kind = .container, .direction = .column, .gap = 4, .children = &s.bool_label_children[index] },+ .{+ .name = key,+ .kind = .{+ .toggle = .{+ .on = value orelse false,+ .disabled = value == null or !editable,+ .owner = s,+ .id = if (pointer) |p| @intCast(p.id) else 0,+ .on_change = &struct {+ fn changed(owner: ?*anyopaque, id: usize, on: bool) void {+ const section: *Section = @ptrCast(@alignCast(owner orelse return));+ _ = changeDevice(section, id, key, on, getter, setter);+ // A rejected setter must restore the switch from the+ // backend. Successful changes keep its slide animation.+ if (section.status != .none) refresh(section);+ }+ }.changed,+ },+ },+ },+ };+ layout.appendRow(&s.row_storage, row_count, row(&s.bool_row_children[index]));}-fn pointerSpeedFor(input: *Input, kind: PointerKind) f32 {- return firstPointerSpeedFor(input, kind) orelse switch (kind) {- .mouse => fallbackMouseSpeed(input),- .touchpad => fallbackTouchpadSpeed(input),+/// Prepare memory before touching hardware or disk. Only publish the new+/// record after both operations succeed, so hotplug and reload see one state.+fn changeDevice(s: *Section, id: usize, comptime key: []const u8, value: config.input_device.Value(key), comptime getter: anytype, comptime setter: anytype) bool {+ const pointer = selected(s, id) orelse {+ refresh(s);+ return false;+ };+ const identity = pointer.persistentId() orelse {+ s.status = .unavailable;+ refresh(s);+ return false;+ };+ const previous = getter(pointer.device) orelse {+ s.status = .unavailable;+ refresh(s);+ return false;+ };+ const server = s.input.server;+ const prepared = config.input_device.prepareSet(&server.config, identity, key, value) catch {+ s.status = .apply_failed;+ refresh(s);+ return false;};+ const result = setter(pointer.device, value);+ if (result != .applied) {+ s.status = if (result == .unsupported) .unavailable else .apply_failed;+ refresh(s);+ return false;+ }+ config.setting_save.saveInputDevice(gpa, server.io, server.config.path, identity, key, value) catch |err| {+ std.log.warn("could not save device setting '{s}': {}", .{ key, err });+ s.status = if (setter(pointer.device, previous) == .applied) .save_failed else .rollback_failed;+ refresh(s);+ return false;+ };+ prepared.commit(&server.config);+ markCustom(s, key);+ const clear_error = s.status != .none;+ s.status = .none;+ if (clear_error) refresh(s);+ return true;+}++const reset_fields = .{+ .{ "pointer_speed", libinput.getPointerSpeed, libinput.setPointerSpeed },+ .{ "natural_scroll", libinput.getNaturalScroll, libinput.setNaturalScroll },+ .{ "left_handed", libinput.getLeftHanded, libinput.setLeftHanded },+ .{ "tap_to_click", libinput.getTapToClick, libinput.setTapToClick },+ .{ "tap_drag", libinput.getTapDrag, libinput.setTapDrag },+ .{ "disable_while_typing", libinput.getDisableWhileTyping, libinput.setDisableWhileTyping },+};++const DeviceSnapshot = struct {+ pointer_speed: ?f64 = null,+ natural_scroll: ?bool = null,+ left_handed: ?bool = null,+ tap_to_click: ?bool = null,+ tap_drag: ?bool = null,+ disable_while_typing: ?bool = null,+};++fn restoreDevice(pointer: *Pointer, previous: DeviceSnapshot, changed: u8) bool {+ var restored = true;+ inline for (reset_fields, 0..) |field, i| {+ if (changed & (@as(u8, 1) << i) != 0) {+ if (field[2](pointer.device, @field(previous, field[0]).?) != .applied) restored = false;+ }+ }+ return restored;}-fn pointerDisableWhileTypingFor(input: *Input, kind: PointerKind) bool {- return firstPointerValueForKind(input, kind, libinput.getDisableWhileTyping) orelse switch (kind) {- .mouse => fallbackMouseDisableWhileTyping(input),- .touchpad => fallbackTouchpadDisableWhileTyping(input),+fn onResetDevice(owner: ?*anyopaque, id: usize) void {+ const s: *Section = @ptrCast(@alignCast(owner orelse return));+ const pointer = selected(s, id) orelse return refresh(s);+ const identity = pointer.persistentId() orelse return refresh(s);+ const server = s.input.server;+ if (!config.input_device.hasOverrides(server.config.input_devices, identity)) return refresh(s);+ const prepared = config.input_device.prepareReset(&server.config, identity) catch {+ s.status = .apply_failed;+ return refresh(s);+ };+ var previous: DeviceSnapshot = .{};+ inline for (reset_fields) |field| @field(previous, field[0]) = field[1](pointer.device);+ const defaults = config.input_device.resolve(server.config.input, &.{}, null, libinput.isTouchpad(pointer.device));+ var changed: u8 = 0;+ inline for (reset_fields, 0..) |field, i| {+ if (@field(previous, field[0])) |before| {+ const value = @field(defaults, field[0]);+ if (before != value) {+ if (field[2](pointer.device, value) != .applied) {+ s.status = if (restoreDevice(pointer, previous, changed)) .reset_failed else .reset_restore_failed;+ return refresh(s);+ }+ changed |= @as(u8, 1) << i;+ }+ }+ }+ config.setting_save.resetInputDevice(gpa, server.io, server.config.path, identity) catch |err| {+ std.log.warn("could not reset device settings: {}", .{err});+ s.status = if (restoreDevice(pointer, previous, changed)) .save_failed else .rollback_failed;+ return refresh(s);};+ prepared.commit(&server.config);+ s.status = .none;+ refresh(s);+}++fn onSpeedChanged(owner: ?*anyopaque, id: usize, value: f32) void {+ const s: *Section = @ptrCast(@alignCast(owner orelse return));+ if (!changeDevice(s, id, "pointer_speed", value, libinput.getPointerSpeed, libinput.setPointerSpeed)) return;+ s.speed_header_children[1].kind.text.content = std.fmt.bufPrint(&s.speed_value_buf, "{d:.1}", .{value}) catch "?";+ s.speed_header_children[1].markDirty();+}++fn indexOfNearest(values: []const f32, v: f32) usize {+ var best: usize = 0;+ var best_d = @abs(values[0] - v);+ for (values, 0..) |candidate, i| {+ const d = @abs(candidate - v);+ if (d < best_d) {+ best = i;+ best_d = d;+ }+ }+ return best;}fn firstKeyboardRepeat(input: *Input) struct { delay: f32, rate: f32 } {@@ -199,55 +466,15 @@ fn firstKeyboardRepeat(input: *Input) struct { delay: f32, rate: f32 } {pub fn build(out: *Section, input: *Input) void {out.input = input;-- const show_touchpad = hasTouchpad(input);- const mouse_speed = pointerSpeedFor(input, .mouse);- const touchpad_speed = pointerSpeedFor(input, .touchpad);- const touchpad_disable_while_typing = pointerDisableWhileTypingFor(input, .touchpad);- const natural = firstPointerValue(input, libinput.getNaturalScroll, input.server.config.input.natural_scroll);- const tap = firstPointerValue(input, libinput.getTapToClick, input.server.config.input.tap_to_click);- const left = firstPointerValue(input, libinput.getLeftHanded, input.server.config.input.left_handed);- const repeat = firstKeyboardRepeat(input);-var row_count: usize = 0;-- const mouse_speed_str = std.fmt.bufPrint(&out.speed_value_buf, "{d:.1}", .{mouse_speed}) catch "0.0";- out.mouse_speed_header_children = .{ fgLabel(i18n.tr("Mouse speed")), ui_slider.valuePill(mouse_speed_str, 13, panel.palette().dim) };- const mouse_speed_header: Widget = .{ .kind = .container, .direction = .row, .justify = .space_between, .children = &out.mouse_speed_header_children };- const mouse_speed_slider: Widget = .{ .name = "mouse_speed", .kind = .{ .slider = .{ .value = mouse_speed, .min = -1, .max = 1, .step = default_speed_step, .owner = out, .on_change = &onMouseSpeedChanged } } };- out.mouse_speed_group_children = .{ mouse_speed_header, mouse_speed_slider };- layout.appendRow(&out.row_storage, &row_count, .{ .kind = .container, .direction = .column, .gap = 8, .children = &out.mouse_speed_group_children });-- if (show_touchpad) {- const touchpad_speed_str = std.fmt.bufPrint(&out.touchpad_speed_value_buf, "{d:.1}", .{touchpad_speed}) catch "0.0";- out.touchpad_speed_header_children = .{- fgLabel(i18n.tr("Touchpad speed")),- ui_slider.valuePill(touchpad_speed_str, 13, panel.palette().dim),- };- const touchpad_speed_header: Widget = .{ .kind = .container, .direction = .row, .justify = .space_between, .children = &out.touchpad_speed_header_children };- const touchpad_speed_slider: Widget = .{ .name = "touchpad_speed", .kind = .{ .slider = .{ .value = touchpad_speed, .min = -1, .max = 1, .step = default_speed_step, .owner = out, .on_change = &onTouchpadSpeedChanged } } };- out.touchpad_speed_group_children = .{ touchpad_speed_header, touchpad_speed_slider };- layout.appendRow(&out.row_storage, &row_count, .{ .kind = .container, .direction = .column, .gap = 8, .children = &out.touchpad_speed_group_children });-- out.touchpad_dwt_row_children = .{- fgLabel(i18n.tr("Disable touchpad while typing")),- .{ .name = "touchpad_disable_while_typing", .kind = .{ .toggle = .{ .on = touchpad_disable_while_typing, .owner = out, .on_change = &onTouchpadDisableWhileTypingChanged } } },- };- const touchpad_dwt_row: Widget = .{ .kind = .container, .direction = .row, .justify = .space_between, .@"align" = .center, .children = &out.touchpad_dwt_row_children };- layout.appendRow(&out.row_storage, &row_count, touchpad_dwt_row);- }-- out.left_row_children = .{ fgLabel(i18n.tr("Left-handed mouse")), .{ .name = "left_handed", .kind = .{ .toggle = .{ .on = left, .owner = out, .on_change = &onLeftHandedChanged } } } };- const left_row: Widget = .{ .kind = .container, .direction = .row, .justify = .space_between, .@"align" = .center, .children = &out.left_row_children };- layout.appendRow(&out.row_storage, &row_count, left_row);-- out.natural_row_children = .{ fgLabel(i18n.tr("Natural scroll")), .{ .name = "natural_scroll", .kind = .{ .toggle = .{ .on = natural, .owner = out, .on_change = &onNaturalScrollChanged } } } };- const natural_row: Widget = .{ .kind = .container, .direction = .row, .justify = .space_between, .@"align" = .center, .children = &out.natural_row_children };- layout.appendRow(&out.row_storage, &row_count, natural_row);-- out.tap_row_children = .{ fgLabel(i18n.tr("Tap to click")), .{ .name = "tap_to_click", .kind = .{ .toggle = .{ .on = tap, .owner = out, .on_change = &onTapToClickChanged } } } };- const tap_row: Widget = .{ .kind = .container, .direction = .row, .justify = .space_between, .@"align" = .center, .children = &out.tap_row_children };- layout.appendRow(&out.row_storage, &row_count, tap_row);+ const pointer = buildSelector(out, &row_count);+ buildSpeed(out, pointer, &row_count);+ buildToggle(out, pointer, &row_count, 0, "natural_scroll", i18n.tr("Natural scroll"), libinput.getNaturalScroll, libinput.setNaturalScroll);+ buildToggle(out, pointer, &row_count, 1, "left_handed", i18n.tr("Left-handed mode"), libinput.getLeftHanded, libinput.setLeftHanded);+ buildToggle(out, pointer, &row_count, 2, "tap_to_click", i18n.tr("Tap to click"), libinput.getTapToClick, libinput.setTapToClick);+ buildToggle(out, pointer, &row_count, 3, "tap_drag", i18n.tr("Tap and drag"), libinput.getTapDrag, libinput.setTapDrag);+ buildToggle(out, pointer, &row_count, 4, "disable_while_typing", i18n.tr("Disable while typing"), libinput.getDisableWhileTyping, libinput.setDisableWhileTyping);+ const repeat = firstKeyboardRepeat(input);out.pan_speed_row_children = .{fgLabel(i18n.tr("Pan speed")),@@ -294,44 +521,6 @@ pub fn build(out: *Section, input: *Input) void {out.root = .{ .name = "input", .kind = .container, .direction = .column, .gap = 8, .children = &out.top_children };}-fn onMouseSpeedChanged(owner: ?*anyopaque, _: usize, value: f32) void {- const s: *Section = @ptrCast(@alignCast(owner orelse return));- applyPointerSpeedTo(s.input, .mouse, value);- persist(s, "pointer_speed", value);- const formatted = std.fmt.bufPrint(&s.speed_value_buf, "{d:.1}", .{value}) catch "?";- s.mouse_speed_header_children[1].kind.text.content = formatted;- s.mouse_speed_header_children[1].markDirty();-}--fn onTouchpadSpeedChanged(owner: ?*anyopaque, _: usize, value: f32) void {- const s: *Section = @ptrCast(@alignCast(owner orelse return));- applyPointerSpeedTo(s.input, .touchpad, value);- persist(s, "pointer_speed_touchpad", value);- const formatted = std.fmt.bufPrint(&s.touchpad_speed_value_buf, "{d:.1}", .{value}) catch "?";- s.touchpad_speed_header_children[1].kind.text.content = formatted;- s.touchpad_speed_header_children[1].markDirty();-}--fn onTouchpadDisableWhileTypingChanged(owner: ?*anyopaque, _: usize, on: bool) void {- const s: *Section = @ptrCast(@alignCast(owner orelse return));- applyPointerDisableWhileTypingTo(s.input, .touchpad, on);- persist(s, "disable_while_typing_touchpad", on);-}--fn onNaturalScrollChanged(owner: ?*anyopaque, _: usize, on: bool) void {- const s: *Section = @ptrCast(@alignCast(owner orelse return));- var it = s.input.pointers.iterator(.forward);- while (it.next()) |pointer| libinput.setNaturalScroll(pointer.device, on);- persist(s, "natural_scroll", on);-}--fn onLeftHandedChanged(owner: ?*anyopaque, _: usize, on: bool) void {- const s: *Section = @ptrCast(@alignCast(owner orelse return));- var it = s.input.pointers.iterator(.forward);- while (it.next()) |pointer| libinput.setLeftHanded(pointer.device, on);- persist(s, "left_handed", on);-}-// Only the file is written here: the reload diffs it against the live config// and recompiles the keymap on every keyboard (`config_runtime/apply.zig`).fn onKeyboardLayoutPicked(owner: ?*anyopaque, _: usize, index: usize) void {@@ -350,13 +539,6 @@ fn onKeyboardLayoutPicked(owner: ?*anyopaque, _: usize, index: usize) void {@import("../../config_runtime/watcher.zig").reloadConfig(server);}-fn onTapToClickChanged(owner: ?*anyopaque, _: usize, on: bool) void {- const s: *Section = @ptrCast(@alignCast(owner orelse return));- var it = s.input.pointers.iterator(.forward);- while (it.next()) |pointer| libinput.setTapToClick(pointer.device, on);- persist(s, "tap_to_click", on);-}-fn onPanSpeedChanged(owner: ?*anyopaque, _: usize, index: usize) void {const s: *Section = @ptrCast(@alignCast(owner orelse return));persist(s, "pan_speed", pan_speed_values[index]);diff --git a/src/input/AGENTS.md b/src/input/AGENTS.mdindex 05e7609..26aabc8 100644--- a/src/input/AGENTS.md+++ b/src/input/AGENTS.md@@ -1,5 +1,15 @@# Input+* **Per-device pointer settings:** `Pointer` owns its stable identity and a+ monotonic live token. Settings resolves the token on every callback; no UI+ state may retain a device pointer. `persistentId` rejects missing/ambiguous+ identities. Hotplug and reload both call `applyPointerDevice`, resolving+ `[[input_device]]` overrides over `[input]` defaults. Do not reapply bare+ global pointer values later. Identity collisions reset those peers to+ defaults and stay ambiguous for their remaining connection lifetimes.+ `tests/input_persistence.py` uses a noninstalled backend fixture; physical+ touchpad/mouse scroll feel and libinput DWT pairing still need manual checks.+* **Text input/IME** (`text_input.zig`): `syncFocus` is the only enter path.IM grabs replace client delivery only (bindings, hardware keys andshell/lock UI win); an IM's own virtual keyboard bypasses its grab.diff --git a/src/libinput.zig b/src/libinput.zigindex 2583765..b863b6d 100644--- a/src/libinput.zig+++ b/src/libinput.zig@@ -1,6 +1,5 @@-// Thin wrapper around the subset of libinput's device-config API the control-// center's Input section needs (pointer accel speed, natural scroll,-// tap-to-click). libinput.h is a clean, glib-free C API (unlike librsvg, see+// Pointer identity, presentation and the libinput device-config API used by+// Control Center. libinput.h is a clean, glib-free C API (unlike librsvg, see// AGENTS.md, "Build and platform gotchas") so it's translated directly rather than hand-declared.//// `wlr.InputDevice.getLibinputDevice()` returns a pointer to an opaque type@@ -9,12 +8,106 @@// is safe and avoids needing to name that private type at all.const wlr = @import("wlroots");const c = @import("c_libinput");+const std = @import("std");+const identity = @import("pointer_identity.zig");+const presentation = @import("pointer_presentation.zig");++pub const Identity = identity.Identity;+pub const Kind = presentation.Kind;+pub const SetResult = enum { applied, unsupported, failed };++fn result(status: c.enum_libinput_config_status) SetResult {+ return switch (status) {+ c.LIBINPUT_CONFIG_STATUS_SUCCESS => .applied,+ c.LIBINPUT_CONFIG_STATUS_UNSUPPORTED => .unsupported,+ else => .failed,+ };+}fn handle(device: *wlr.InputDevice) ?*c.libinput_device {const raw = device.getLibinputDevice() orelse return null;return @ptrCast(raw);}+/// Borrowed strings: copy before retaining beyond the live device's lifetime.+pub fn getName(device: *wlr.InputDevice) ?[]const u8 {+ const dev = handle(device) orelse return null;+ return std.mem.span(c.libinput_device_get_name(dev));+}++pub fn getSysname(device: *wlr.InputDevice) ?[]const u8 {+ const dev = handle(device) orelse return null;+ return std.mem.span(c.libinput_device_get_sysname(dev));+}++/// Owned display text; the caller can retain it after removal of the device.+pub fn getFriendlyName(a: std.mem.Allocator, device: *wlr.InputDevice) !?[]const u8 {+ const dev = handle(device) orelse return presentation.friendlyName(a, .{+ .primary = if (device.name) |name| std.mem.span(name) else null,+ });+ const primary = std.mem.span(c.libinput_device_get_name(dev));+ if (try presentation.friendlyName(a, .{ .primary = primary })) |name| return name;+ const udev = c.libinput_device_get_udev_device(dev) orelse return null;+ defer _ = c.udev_device_unref(udev);+ return presentation.friendlyName(a, .{+ .vendor = property(udev, "ID_VENDOR_FROM_DATABASE") orelse property(udev, "ID_VENDOR"),+ .model = property(udev, "ID_MODEL_FROM_DATABASE") orelse property(udev, "ID_MODEL"),+ });+}++/// ID_INPUT_TRACKBALL is supplied by systemd's 70-mouse.hwdb. It recognizes+/// devices such as the Kensington Expert Mouse whose names omit "trackball".+/// Libinput's private ModelTrackball quirks are not a public classification API.+pub fn getKind(device: *wlr.InputDevice) Kind {+ const dev = handle(device) orelse return .pointer;+ var tags: presentation.Tags = .{ .tap = c.libinput_device_config_tap_get_finger_count(dev) > 0 };+ if (c.libinput_device_get_udev_device(dev)) |udev| {+ defer _ = c.udev_device_unref(udev);+ tags.touchpad = propertyFlag(udev, "ID_INPUT_TOUCHPAD");+ tags.trackball = propertyFlag(udev, "ID_INPUT_TRACKBALL");+ tags.mouse = propertyFlag(udev, "ID_INPUT_MOUSE");+ }+ return presentation.classify(tags);+}++/// The returned key owns its bytes and survives removal of the libinput device.+/// No sysname, sysfs input number, pointer address, or connection index is used.+pub fn getIdentity(device: *wlr.InputDevice) ?Identity {+ const dev = handle(device) orelse return null;+ const udev = c.libinput_device_get_udev_device(dev) orelse return null;+ defer _ = c.udev_device_unref(udev);+ return identity.build(.{+ .bus = c.libinput_device_get_id_bustype(dev),+ .vendor = c.libinput_device_get_id_vendor(dev),+ .product = c.libinput_device_get_id_product(dev),+ .name = std.mem.span(c.libinput_device_get_name(dev)),+ .uniq = ancestorAttribute(udev, "uniq"),+ .serial = property(udev, "ID_SERIAL_SHORT"),+ .interface = property(udev, "ID_USB_INTERFACE_NUM") orelse ancestorAttribute(udev, "bInterfaceNumber"),+ .path = property(udev, "ID_PATH"),+ });+}++fn property(device: *c.udev_device, key: [*:0]const u8) ?[]const u8 {+ const value = c.udev_device_get_property_value(device, key) orelse return null;+ return std.mem.span(value);+}++fn propertyFlag(device: *c.udev_device, key: [*:0]const u8) bool {+ return std.mem.eql(u8, property(device, key) orelse "", "1");+}++fn ancestorAttribute(device: *c.udev_device, key: [*:0]const u8) ?[]const u8 {+ var ancestor: ?*c.udev_device = device;+ while (ancestor) |current| : (ancestor = c.udev_device_get_parent(current)) {+ if (c.udev_device_get_sysattr_value(current, key)) |value| {+ const bytes = std.mem.span(value);+ if (bytes.len != 0) return bytes;+ }+ }+ return null;+}+pub fn getPointerSpeed(device: *wlr.InputDevice) ?f64 {const dev = handle(device) orelse return null;if (c.libinput_device_config_accel_is_available(dev) == 0) return null;@@ -22,15 +115,14 @@ pub fn getPointerSpeed(device: *wlr.InputDevice) ?f64 {}pub fn isTouchpad(device: *wlr.InputDevice) bool {- const dev = handle(device) orelse return false;- if (c.libinput_device_config_tap_get_finger_count(dev) > 0) return true;- return c.libinput_device_has_capability(dev, c.LIBINPUT_DEVICE_CAP_TOUCH) != 0;+ return getKind(device) == .touchpad;}-pub fn setPointerSpeed(device: *wlr.InputDevice, speed: f64) void {- const dev = handle(device) orelse return;- if (c.libinput_device_config_accel_is_available(dev) == 0) return;- _ = c.libinput_device_config_accel_set_speed(dev, speed);+pub fn setPointerSpeed(device: *wlr.InputDevice, speed: f64) SetResult {+ const dev = handle(device) orelse return .unsupported;+ if (c.libinput_device_config_accel_is_available(dev) == 0) return .unsupported;+ if (!std.math.isFinite(speed) or speed < -1 or speed > 1) return .failed;+ return result(c.libinput_device_config_accel_set_speed(dev, speed));}pub fn getNaturalScroll(device: *wlr.InputDevice) ?bool {@@ -39,10 +131,10 @@ pub fn getNaturalScroll(device: *wlr.InputDevice) ?bool {return c.libinput_device_config_scroll_get_natural_scroll_enabled(dev) != 0;}-pub fn setNaturalScroll(device: *wlr.InputDevice, on: bool) void {- const dev = handle(device) orelse return;- if (c.libinput_device_config_scroll_has_natural_scroll(dev) == 0) return;- _ = c.libinput_device_config_scroll_set_natural_scroll_enabled(dev, if (on) 1 else 0);+pub fn setNaturalScroll(device: *wlr.InputDevice, on: bool) SetResult {+ const dev = handle(device) orelse return .unsupported;+ if (c.libinput_device_config_scroll_has_natural_scroll(dev) == 0) return .unsupported;+ return result(c.libinput_device_config_scroll_set_natural_scroll_enabled(dev, if (on) 1 else 0));}pub fn getLeftHanded(device: *wlr.InputDevice) ?bool {@@ -51,10 +143,10 @@ pub fn getLeftHanded(device: *wlr.InputDevice) ?bool {return c.libinput_device_config_left_handed_get(dev) != 0;}-pub fn setLeftHanded(device: *wlr.InputDevice, on: bool) void {- const dev = handle(device) orelse return;- if (c.libinput_device_config_left_handed_is_available(dev) == 0) return;- _ = c.libinput_device_config_left_handed_set(dev, if (on) 1 else 0);+pub fn setLeftHanded(device: *wlr.InputDevice, on: bool) SetResult {+ const dev = handle(device) orelse return .unsupported;+ if (c.libinput_device_config_left_handed_is_available(dev) == 0) return .unsupported;+ return result(c.libinput_device_config_left_handed_set(dev, if (on) 1 else 0));}pub fn getTapToClick(device: *wlr.InputDevice) ?bool {@@ -63,24 +155,30 @@ pub fn getTapToClick(device: *wlr.InputDevice) ?bool {return c.libinput_device_config_tap_get_enabled(dev) == c.LIBINPUT_CONFIG_TAP_ENABLED;}+pub fn getTapDrag(device: *wlr.InputDevice) ?bool {+ const dev = handle(device) orelse return null;+ if (c.libinput_device_config_tap_get_finger_count(dev) == 0) return null;+ return c.libinput_device_config_tap_get_drag_enabled(dev) == c.LIBINPUT_CONFIG_DRAG_ENABLED;+}+pub fn getDisableWhileTyping(device: *wlr.InputDevice) ?bool {const dev = handle(device) orelse return null;if (c.libinput_device_config_dwt_is_available(dev) == 0) return null;return c.libinput_device_config_dwt_get_enabled(dev) == c.LIBINPUT_CONFIG_DWT_ENABLED;}-pub fn setTapToClick(device: *wlr.InputDevice, on: bool) void {- const dev = handle(device) orelse return;- if (c.libinput_device_config_tap_get_finger_count(dev) == 0) return;+pub fn setTapToClick(device: *wlr.InputDevice, on: bool) SetResult {+ const dev = handle(device) orelse return .unsupported;+ if (c.libinput_device_config_tap_get_finger_count(dev) == 0) return .unsupported;const state: c.enum_libinput_config_tap_state = if (on) c.LIBINPUT_CONFIG_TAP_ENABLED else c.LIBINPUT_CONFIG_TAP_DISABLED;- _ = c.libinput_device_config_tap_set_enabled(dev, state);+ return result(c.libinput_device_config_tap_set_enabled(dev, state));}-pub fn setTapDrag(device: *wlr.InputDevice, on: bool) void {- const dev = handle(device) orelse return;- if (c.libinput_device_config_tap_get_finger_count(dev) == 0) return;+pub fn setTapDrag(device: *wlr.InputDevice, on: bool) SetResult {+ const dev = handle(device) orelse return .unsupported;+ if (c.libinput_device_config_tap_get_finger_count(dev) == 0) return .unsupported;const state: c.enum_libinput_config_drag_state = if (on) c.LIBINPUT_CONFIG_DRAG_ENABLED else c.LIBINPUT_CONFIG_DRAG_DISABLED;- _ = c.libinput_device_config_tap_set_drag_enabled(dev, state);+ return result(c.libinput_device_config_tap_set_drag_enabled(dev, state));}// DWT runs inside libinput and requires keyboard/touchpad pairing: an enabled@@ -96,9 +194,9 @@ pub fn setTapDrag(device: *wlr.InputDevice, on: bool) void {// --show-keycodes --verbose` while typing and moving on the touchpad's center;// edge-palm rejection alone is not evidence of DWT. This command creates its// own context, so its enabled state does not verify the compositor's setting.-pub fn setDisableWhileTyping(device: *wlr.InputDevice, on: bool) void {- const dev = handle(device) orelse return;- if (c.libinput_device_config_dwt_is_available(dev) == 0) return;+pub fn setDisableWhileTyping(device: *wlr.InputDevice, on: bool) SetResult {+ const dev = handle(device) orelse return .unsupported;+ if (c.libinput_device_config_dwt_is_available(dev) == 0) return .unsupported;const state: c.enum_libinput_config_dwt_state = if (on) c.LIBINPUT_CONFIG_DWT_ENABLED else c.LIBINPUT_CONFIG_DWT_DISABLED;- _ = c.libinput_device_config_dwt_set_enabled(dev, state);+ return result(c.libinput_device_config_dwt_set_enabled(dev, state));}diff --git a/src/pointer_identity.zig b/src/pointer_identity.zignew file mode 100644index 0000000..90ffeef--- /dev/null+++ b/src/pointer_identity.zig@@ -0,0 +1,64 @@+//! Persistent pointer identity, independent of libinput and the event loop.+//! Hardware uniq/serial survives port changes. Without one, ID_PATH identifies+//! the physical connection: identical unnumbered peripherals swapped between+//! ports cannot be distinguished. Callers must reject duplicate live keys.+const std = @import("std");+const Sha256 = std.crypto.hash.sha2.Sha256;++const prefix = "pointer-v1:";+pub const Identity = struct {+ key: [prefix.len + Sha256.digest_length * 2]u8,+ basis: enum { unique, path },+};++pub const Facts = struct {+ bus: u32,+ vendor: u32,+ product: u32,+ name: []const u8,+ uniq: ?[]const u8 = null,+ serial: ?[]const u8 = null,+ interface: ?[]const u8 = null,+ path: ?[]const u8 = null,+};++pub fn build(facts: Facts) ?Identity {+ const source: []const u8, const stable: []const u8 = if (nonempty(facts.uniq)) |value|+ .{ "uniq", value }+ else if (nonempty(facts.serial)) |value|+ .{ "serial", value }+ else if (nonempty(facts.path)) |value|+ .{ "path", value }+ else+ return null;+ var hash = Sha256.init(.{});+ hash.update(prefix);+ var ids: [12]u8 = undefined;+ std.mem.writeInt(u32, ids[0..4], facts.bus, .little);+ std.mem.writeInt(u32, ids[4..8], facts.vendor, .little);+ std.mem.writeInt(u32, ids[8..12], facts.product, .little);+ hash.update(&ids);+ // Length framing prevents hardware strings containing separators from+ // accidentally identifying a different combination of fields.+ for ([_][]const u8{ facts.name, source, stable, nonempty(facts.interface) orelse "" }) |field| {+ var len: [8]u8 = undefined;+ std.mem.writeInt(u64, &len, @intCast(field.len), .little);+ hash.update(&len);+ hash.update(field);+ }+ var digest: [Sha256.digest_length]u8 = undefined;+ hash.final(&digest);+ return .{+ .key = prefix.* ++ std.fmt.bytesToHex(digest, .lower),+ .basis = if (std.mem.eql(u8, source, "path")) .path else .unique,+ };+}++fn nonempty(value: ?[]const u8) ?[]const u8 {+ const bytes = value orelse return null;+ return if (bytes.len != 0) bytes else null;+}++test {+ _ = @import("pointer_identity_tests.zig");+}diff --git a/src/pointer_identity_tests.zig b/src/pointer_identity_tests.zignew file mode 100644index 0000000..67389f1--- /dev/null+++ b/src/pointer_identity_tests.zig@@ -0,0 +1,95 @@+const std = @import("std");+const identity = @import("pointer_identity.zig");+const expect = std.testing.expect;+const expectEqualStrings = std.testing.expectEqualStrings;++const mouse: identity.Facts = .{+ .bus = 3,+ .vendor = 0x046d,+ .product = 0xc077,+ .name = "Example mouse",+ .interface = "00",+};++test "persistent identity requires more than device name and model" {+ try expect(identity.build(mouse) == null);+ var empty = mouse;+ empty.serial = "";+ empty.uniq = "";+ empty.path = "";+ try expect(identity.build(empty) == null);+}++test "serial identity survives reconnect and port changes" {+ var first = mouse;+ first.serial = "A123";+ first.path = "pci-0000:00:14.0-usb-0:1:1.0";+ var reconnect = first;+ reconnect.path = "pci-0000:00:14.0-usb-0:5:1.0";+ const a = identity.build(first).?;+ const b = identity.build(reconnect).?;+ try expectEqualStrings(&a.key, &b.key);+ try expect(a.basis == .unique);+ try expectEqualStrings("pointer-v1:", a.key[0..11]);+ try expect(a.key.len == 75);+}++test "uniq is preferred over serial and changing connection paths" {+ var first = mouse;+ first.uniq = "11:22:33:44:55:66";+ first.serial = "receiver";+ var second = first;+ second.serial = "different-receiver";+ second.path = "different-port";+ const a = identity.build(first).?;+ const b = identity.build(second).?;+ try expectEqualStrings(&a.key, &b.key);+ second.uniq = "11:22:33:44:55:77";+ const other = identity.build(second).?;+ try expect(!std.mem.eql(u8, &a.key, &other.key));+}++test "identical unnumbered mice are distinguished by physical path" {+ var first = mouse;+ first.path = "pci-0000:00:14.0-usb-0:1:1.0";+ var second = first;+ second.path = "pci-0000:00:14.0-usb-0:2:1.0";+ const a = identity.build(first).?;+ const b = identity.build(second).?;+ try expect(a.basis == .path);+ try expect(!std.mem.eql(u8, &a.key, &b.key));+ const reconnected = identity.build(first).?;+ try expectEqualStrings(&a.key, &reconnected.key);+}++test "serials do not alias other models or logical interfaces" {+ var first = mouse;+ first.serial = "123";+ const a = identity.build(first).?;+ inline for (.{ "vendor", "product", "bus" }) |field| {+ var second = first;+ @field(second, field) += 1;+ const b = identity.build(second).?;+ try expect(!std.mem.eql(u8, &a.key, &b.key));+ }+ var second = first;+ second.interface = "01";+ const b = identity.build(second).?;+ try expect(!std.mem.eql(u8, &a.key, &b.key));+ second = first;+ second.name = "Different mouse";+ const c = identity.build(second).?;+ try expect(!std.mem.eql(u8, &a.key, &c.key));+}++test "identity frames strings rather than joining with delimiters" {+ var first = mouse;+ first.serial = "serial:123";+ first.interface = "01";+ var second = first;+ second.serial = "serial";+ second.interface = "123:01";+ const a = identity.build(first).?;+ const b = identity.build(second).?;+ try expect(!std.mem.eql(u8, &a.key, &b.key));+}diff --git a/src/pointer_presentation.zig b/src/pointer_presentation.zignew file mode 100644index 0000000..9d567bf--- /dev/null+++ b/src/pointer_presentation.zig@@ -0,0 +1,62 @@+//! Human-facing device descriptions. These never participate in identity or+//! configuration matching; udev's input tags determine the displayed kind.+const std = @import("std");++pub const Kind = enum { mouse, touchpad, trackball, pointer };++pub const Tags = struct {+ touchpad: bool = false,+ trackball: bool = false,+ mouse: bool = false,+ tap: bool = false,+};++pub fn classify(tags: Tags) Kind {+ if (tags.touchpad) return .touchpad;+ if (tags.trackball) return .trackball;+ if (tags.tap) return .touchpad;+ if (tags.mouse) return .mouse;+ return .pointer;+}++pub const Names = struct {+ primary: ?[]const u8 = null,+ vendor: ?[]const u8 = null,+ model: ?[]const u8 = null,+};++/// Prefer the kernel/libinput's descriptive name. The udev model database is+/// only a fallback for unnamed devices, and never replaces an identity key.+pub fn friendlyName(a: std.mem.Allocator, names: Names) !?[]const u8 {+ if (try clean(a, names.primary, false)) |name| return name;+ const model = (try clean(a, names.model, true)) orelse return null;+ errdefer a.free(model);+ const vendor = (try clean(a, names.vendor, true)) orelse return model;+ defer a.free(vendor);+ if (std.ascii.startsWithIgnoreCase(model, vendor)) return model;+ const combined = try std.fmt.allocPrint(a, "{s} {s}", .{ vendor, model });+ a.free(model);+ return combined;+}++fn clean(a: std.mem.Allocator, input: ?[]const u8, underscores: bool) !?[]u8 {+ const text = input orelse return null;+ var out = std.ArrayList(u8).empty;+ defer out.deinit(a);+ var space = false;+ for (text) |byte| {+ if (byte <= ' ' or byte == 0x7f or (underscores and byte == '_')) {+ space = out.items.len > 0;+ continue;+ }+ if (space) try out.append(a, ' ');+ try out.append(a, byte);+ space = false;+ }+ if (out.items.len == 0) return null;+ return try out.toOwnedSlice(a);+}++test {+ _ = @import("pointer_presentation_tests.zig");+}diff --git a/src/pointer_presentation_tests.zig b/src/pointer_presentation_tests.zignew file mode 100644index 0000000..3db90de--- /dev/null+++ b/src/pointer_presentation_tests.zig@@ -0,0 +1,45 @@+const std = @import("std");+const presentation = @import("pointer_presentation.zig");+const expectEqual = std.testing.expectEqual;+const expectEqualStrings = std.testing.expectEqualStrings;++test "input tags identify touchpads, mice and trackballs without name guesses" {+ try expectEqual(.touchpad, presentation.classify(.{ .touchpad = true, .mouse = true }));+ try expectEqual(.trackball, presentation.classify(.{ .trackball = true, .mouse = true }));+ try expectEqual(.mouse, presentation.classify(.{ .mouse = true }));+ try expectEqual(.touchpad, presentation.classify(.{ .tap = true }));+ try expectEqual(.pointer, presentation.classify(.{}));+}++test "friendly device names retain real product names and have no event suffix" {+ const a = std.testing.allocator;+ const result = (try presentation.friendlyName(a, .{+ .primary = " Logitech MX Master 3S ",+ .vendor = "Generic vendor",+ .model = "USB_receiver",+ })).?;+ defer a.free(result);+ try expectEqualStrings("Logitech MX Master 3S", result);+}++test "unnamed devices use readable udev vendor and model names" {+ const a = std.testing.allocator;+ const result = (try presentation.friendlyName(a, .{+ .primary = " \n\t",+ .vendor = "Kensington",+ .model = "Expert_Mouse",+ })).?;+ defer a.free(result);+ try expectEqualStrings("Kensington Expert Mouse", result);+ const repeated = (try presentation.friendlyName(a, .{ .vendor = "Logitech", .model = "Logitech_MX_Ergo" })).?;+ defer a.free(repeated);+ try expectEqualStrings("Logitech MX Ergo", repeated);+}++test "presentation collapses control whitespace and leaves missing names unset" {+ const a = std.testing.allocator;+ const result = (try presentation.friendlyName(a, .{ .primary = "A\t\n Mouse\x7fDevice" })).?;+ defer a.free(result);+ try expectEqualStrings("A Mouse Device", result);+ try expectEqual(@as(?[]const u8, null), try presentation.friendlyName(a, .{}));+}diff --git a/src/pointer_tests.zig b/src/pointer_tests.zignew file mode 100644index 0000000..1845827--- /dev/null+++ b/src/pointer_tests.zig@@ -0,0 +1,42 @@+const std = @import("std");+const Input = @import("Input.zig");+const Pointer = @import("Pointer.zig");+const identity = @import("pointer_identity.zig");++test "pointer selection tokens do not follow removal or reused storage" {+ var input: Input = undefined;+ input.pointers.init();+ var pointer: Pointer = .{ .input = &input, .device = undefined, .id = 1, .identity = null };+ input.pointers.append(&pointer);+ try std.testing.expect(Pointer.find(&input, 1) == &pointer);+ pointer.link.remove();+ try std.testing.expect(Pointer.find(&input, 1) == null);+ // Reusing exactly the same address must not revive a stale UI selection.+ pointer.id = 2;+ input.pointers.append(&pointer);+ try std.testing.expect(Pointer.find(&input, 1) == null);+ try std.testing.expect(Pointer.find(&input, 2) == &pointer);+ try std.testing.expect(pointer.persistentId() == null);+}++test "pointer identities reject live collisions and match distinct connection paths" {+ var input: Input = undefined;+ input.pointers.init();+ const facts: identity.Facts = .{ .bus = 3, .vendor = 1, .product = 2, .name = "Identical Mouse", .path = "pci-usb-1" };+ var other_facts = facts;+ other_facts.path = "pci-usb-2";+ var first: Pointer = .{ .input = &input, .device = undefined, .id = 1, .identity = identity.build(facts) };+ var second: Pointer = .{ .input = &input, .device = undefined, .id = 2, .identity = identity.build(other_facts) };+ input.pointers.append(&first);+ input.pointers.append(&second);+ try std.testing.expect(first.persistentId() != null);+ try std.testing.expect(second.persistentId() != null);+ try std.testing.expect(!std.mem.eql(u8, first.persistentId().?, second.persistentId().?));+ second.identity = first.identity;+ try std.testing.expect(first.persistentId() == null);+ try std.testing.expect(second.persistentId() == null);+ // Collision state remains conservative after one of the peers goes away.+ first.identity_ambiguous = true;+ second.link.remove();+ try std.testing.expect(first.persistentId() == null);+}diff --git a/src/ui/layout.zig b/src/ui/layout.zigindex 0178c00..a9b6c4b 100644--- a/src/ui/layout.zig+++ b/src/ui/layout.zig@@ -144,6 +144,8 @@ pub const IconId = enum {users,squares,divide,+ touchpad,+ trackball,};pub const ButtonState = enum { idle, hover, press, disabled };@@ -414,6 +416,8 @@ pub const SelectData = struct {/// Visible placeholders that cannot be committed.disabled_options: []const usize = &.{},labels: []const []const u8,+ /// Optional leading glyphs by option index; borrowed like labels.+ icons: []const IconId = &.{},selected: ?usize = null,placeholder: []const u8 = "Select an option",disabled: bool = false,diff --git a/src/ui/measure.zig b/src/ui/measure.zigindex ccac217..b15cf93 100644--- a/src/ui/measure.zig+++ b/src/ui/measure.zig@@ -165,7 +165,7 @@ fn naturalSize(widget: *const Widget) Natural {.swatch => .{ .w = swatch_size, .h = swatch_size },.select => |data| blk: {var width = textNatural(data.placeholder, .sans, 600, theme.global.font_size).w;- for (data.labels) |label| width = @max(width, textNatural(label, .sans, 600, theme.global.font_size).w);+ for (data.labels, 0..) |label, i| width = @max(width, textNatural(label, .sans, 600, theme.global.font_size).w + (if (i < data.icons.len) @as(f32, 24) else 0));break :blk .{ .w = @max(160, width + 52), .h = @max(38, theme.global.font_size * 1.2 + 20) };},.segmented => |data| blk: {diff --git a/src/ui/paint_icons.zig b/src/ui/paint_icons.zigindex 806501b..d0e8ef4 100644--- a/src/ui/paint_icons.zig+++ b/src/ui/paint_icons.zig@@ -266,7 +266,7 @@ pub fn iconDistance(id: IconId, px: f32, py: f32, cx: f32, cy: f32, half: f32, tconst base = @min(ring_open, arrow);break :blk if (id == .restart_shell) @min(base, sdCircle(px, py, cx, cy, half * 0.24)) else base;},- .git_branch, .home, .generic, .folder, .document, .terminal, .settings, .keyboard, .edit, .browser, .wifi, .ethernet, .globe, .mouse, .display, .music, .headphones, .bluetooth, .battery, .notification, .eye, .eye_off, .refresh, .cut, .copy, .paste, .trash, .trash_can, .view_grid, .view_list, .sort, .filter, .zoom_in, .zoom_out, .rotate, .crop, .undo, .save, .fit, .print, .open, .usb_stick, .drive, .eject, .users, .squares => sdCircle(px, py, cx, cy, half * 0.6),+ .git_branch, .home, .generic, .folder, .document, .terminal, .settings, .keyboard, .edit, .browser, .wifi, .ethernet, .globe, .mouse, .touchpad, .trackball, .display, .music, .headphones, .bluetooth, .battery, .notification, .eye, .eye_off, .refresh, .cut, .copy, .paste, .trash, .trash_can, .view_grid, .view_list, .sort, .filter, .zoom_in, .zoom_out, .rotate, .crop, .undo, .save, .fit, .print, .open, .usb_stick, .drive, .eject, .users, .squares => sdCircle(px, py, cx, cy, half * 0.6),};}diff --git a/src/ui/paint_widgets.zig b/src/ui/paint_widgets.zigindex 5f8ebb5..34c26ef 100644--- a/src/ui/paint_widgets.zig+++ b/src/ui/paint_widgets.zig@@ -408,7 +408,9 @@ pub fn paintSelect(widget: *const Widget, data: layout.SelectData, r: *Renderer)const h = widget.computed_height;r.fillRect(x, y, w, h, .{ .color = if (hovered and !data.disabled) t.surface_hover else t.surface, .radius = t.radius, .border_width = 1, .border_color = if (focused or data.open) t.accent else if (hovered and !data.disabled) t.border_hover else t.border });const valid = if (data.selected) |i| i < data.labels.len else false;- r.drawText(x + 12, y, @max(0, w - 48), h, .{ .content = if (valid) data.labels[data.selected.?] else data.placeholder, .font_size = t.font_size, .weight = 600, .color = if (data.disabled) t.faint else if (valid) t.fg else t.dim });+ const icon_width: f32 = if (valid and data.selected.? < data.icons.len) 24 else 0;+ if (icon_width > 0) r.drawIcon(x + 12, y + (h - 16) / 2, 16, 16, .{ .id = data.icons[data.selected.?], .color = if (data.disabled) t.faint else t.dim });+ r.drawText(x + 12 + icon_width, y, @max(0, w - 48 - icon_width), h, .{ .content = if (valid) data.labels[data.selected.?] else data.placeholder, .font_size = t.font_size, .weight = 600, .color = if (data.disabled) t.faint else if (valid) t.fg else t.dim });r.drawIcon(x + w - 28, y + (h - 16) / 2, 16, 16, .{ .id = if (data.open) .chevron_up else .chevron_down, .color = if (data.disabled) t.faint else t.dim });}@@ -428,7 +430,10 @@ pub fn paintOverlays(widget: *const Widget, r: *Renderer) void {for (d.first_visible..end) |i| {const y = b.y + select.padding + @as(f32, @floatFromInt(i - d.first_visible)) * row_h;if (i == d.highlighted) r.fillRect(b.x + 4, y, b.w - 8, row_h, .{ .color = .{ t.accent[0], t.accent[1], t.accent[2], 0.18 }, .radius = @max(0, t.radius - 3) });- r.drawText(b.x + 12, y, @max(0, b.w - 46), row_h, .{ .content = d.labels[i], .font_size = t.font_size, .weight = if (d.selected == i) 600 else 400, .color = if (std.mem.indexOfScalar(usize, d.disabled_options, i) != null) t.faint else t.fg });+ const disabled = std.mem.indexOfScalar(usize, d.disabled_options, i) != null;+ const icon_width: f32 = if (i < d.icons.len) 24 else 0;+ if (icon_width > 0) r.drawIcon(b.x + 12, y + (row_h - 16) / 2, 16, 16, .{ .id = d.icons[i], .color = if (disabled) t.faint else t.dim });+ r.drawText(b.x + 12 + icon_width, y, @max(0, b.w - 46 - icon_width), row_h, .{ .content = d.labels[i], .font_size = t.font_size, .weight = if (d.selected == i) 600 else 400, .color = if (disabled) t.faint else t.fg });if (d.selected == i) r.drawIcon(b.x + b.w - 28, y + (row_h - 16) / 2, 16, 16, .{ .id = .checkmark, .color = t.accent });}if (visible > 0) {diff --git a/src/ui/shell_icons.zig b/src/ui/shell_icons.zigindex 2497477..0c146e7 100644--- a/src/ui/shell_icons.zig+++ b/src/ui/shell_icons.zig@@ -60,6 +60,8 @@ pub fn configure(io: std.Io, root: []const u8) void {.{ IconId.keyboard, "keyboard" },.{ IconId.settings, "settings" },.{ IconId.mouse, "mouse" },+ .{ IconId.touchpad, "touchpad" },+ .{ IconId.trackball, "trackball" },.{ IconId.display, "display" },.{ IconId.headphones, "headphones" },.{ IconId.music, "music" },@@ -118,7 +120,7 @@ fn loadOverride(io: std.Io, root: []const u8, id: IconId, name: []const u8) void};const stat = std.Io.Dir.cwd().statFile(io, path, .{ .follow_symlinks = false }) catch return;if (stat.kind != .file) return;- overrides[@intFromEnum(id)] = std.Io.Dir.cwd().readFileAlloc(io, path, std.heap.c_allocator, .limited(64 * 1024)) catch null;+ overrides[@backingInt(id)] = std.Io.Dir.cwd().readFileAlloc(io, path, std.heap.c_allocator, .limited(64 * 1024)) catch null;}pub fn deinitPack() void {@@ -138,7 +140,7 @@ fn clearPack() void {}fn source(id: IconId) ?[]const u8 {- if (overrides[@intFromEnum(id)]) |bytes| return bytes;+ if (overrides[@backingInt(id)]) |bytes| return bytes;return builtinSource(id);}@@ -152,6 +154,8 @@ fn builtinSource(id: IconId) ?[]const u8 {.keyboard => @embedFile("shell-icon-keyboard"),.settings => @embedFile("shell-icon-settings"),.mouse => @embedFile("shell-icon-mouse"),+ .touchpad => @embedFile("shell-icon-touchpad"),+ .trackball => @embedFile("shell-icon-trackball"),.display => @embedFile("shell-icon-display"),.headphones => @embedFile("shell-icon-headphones"),.music => @embedFile("shell-icon-music"),@@ -254,7 +258,7 @@ fn rasterize(svg: []const u8, size: i32) ?Mask {test "bundled shell SVGs render nonempty transparent masks at fractional scales" {defer deinit();- for ([_]IconId{ .print, .usb_stick, .drive, .eject, .home, .settings, .mouse, .display, .music, .headphones, .wifi, .bluetooth, .battery, .notification, .volume, .volume_muted, .power, .clock, .lock, .logout, .reboot, .divide }) |id| {+ for ([_]IconId{ .print, .usb_stick, .drive, .eject, .home, .settings, .mouse, .touchpad, .trackball, .display, .music, .headphones, .wifi, .bluetooth, .battery, .notification, .volume, .volume_muted, .power, .clock, .lock, .logout, .reboot, .divide }) |id| {for ([_]i32{ 24, 36, 48 }) |size| {const mask = get(id, size) orelse return error.InvalidShellIcon;var visible = false;diff --git a/src/ui/widgets/select.zig b/src/ui/widgets/select.zigindex 7a39be7..c335f21 100644--- a/src/ui/widgets/select.zig+++ b/src/ui/widgets/select.zig@@ -17,7 +17,7 @@ pub const Saved = struct {id: usize = 0,};-fn optionKey(labels: []const []const u8, disabled: []const usize) u64 {+fn optionKey(labels: []const []const u8, disabled: []const usize, icons: []const layout.IconId) u64 {var hash = std.hash.Wyhash.init(0);for (labels) |label| {const len = label.len;@@ -26,7 +26,15 @@ fn optionKey(labels: []const []const u8, disabled: []const usize) u64 {}const count = labels.len;hash.update(std.mem.asBytes(&count));+ const disabled_count = disabled.len;+ hash.update(std.mem.asBytes(&disabled_count));hash.update(std.mem.sliceAsBytes(disabled));+ const icon_count = icons.len;+ hash.update(std.mem.asBytes(&icon_count));+ for (icons) |icon| {+ const tag: u32 = @backingInt(icon);+ hash.update(std.mem.asBytes(&tag));+ }return hash.final();}@@ -46,7 +54,7 @@ pub fn capture(root: *const Widget, saved: *Saved, focused: ?*const Widget) voidsaved.selected = data.selected;saved.highlighted = data.highlighted;saved.first_visible = data.first_visible;- saved.options = optionKey(data.labels, data.disabled_options);+ saved.options = optionKey(data.labels, data.disabled_options, data.icons);saved.owner = data.owner;saved.id = data.id;}@@ -62,7 +70,7 @@ pub fn restore(root: *Widget, saved: *const Saved) ?*Widget {!data.disabled and data.selected == saved.selected anddata.owner == saved.owner and data.id == saved.id anddata.labels.len > saved.highlighted and- optionKey(data.labels, data.disabled_options) == saved.options)+ optionKey(data.labels, data.disabled_options, data.icons) == saved.options){data.open = true;data.highlighted = saved.highlighted;@@ -224,6 +232,9 @@ test "a refreshed dropdown keeps authoritative values and refuses incompatible schanged.kind.select.disabled_options = &.{1};try std.testing.expect(restore(&changed, &saved) == null);changed.kind.select.disabled_options = &.{};+ changed.kind.select.icons = &.{ .mouse, .touchpad };+ try std.testing.expect(restore(&changed, &saved) == null);+ changed.kind.select.icons = &.{};changed.kind.select.disabled = true;try std.testing.expect(restore(&changed, &saved) == null);changed.kind.select.disabled = false;diff --git a/src/ui_tests.zig b/src/ui_tests.zigindex 64518cb..ff4aaa2 100644--- a/src/ui_tests.zig+++ b/src/ui_tests.zig@@ -11,6 +11,8 @@ test {_ = @import("config").keymap;_ = @import("input/repeat_keys.zig");_ = @import("input/wheel_debounce.zig");+ _ = @import("pointer_identity.zig");+ _ = @import("pointer_presentation.zig");_ = @import("ui").key_repeat;_ = @import("ui").hover_glide;_ = @import("input/ime_placement.zig");@@ -96,6 +98,7 @@ test {_ = @import("notifications_tests.zig");_ = @import("notifications/image.zig");_ = @import("Input.zig");+ _ = @import("Pointer.zig");_ = @import("undo.zig");_ = @import("ipc/handlers.zig");_ = @import("ipc/server.zig");diff --git a/tests/input_persistence.py b/tests/input_persistence.pyindex df73b6d..571ca13 100644--- a/tests/input_persistence.py+++ b/tests/input_persistence.py@@ -1,5 +1,15 @@#!/usr/bin/env python3-"""Input settings survive a fresh headless compositor and preserve user config."""+"""Per-device settings through the real UI, reload, hotplug, and restart paths.++The noninstalled preload fixture supplies libinput devices and observes backend+state; no host input hardware or production testing hook is used.+"""+import json+import math+import os+import shlex+import struct+import subprocessimport tempfileimport timeimport tomllib@@ -8,84 +18,400 @@ from pathlib import Pathfrom ipc_client import IPCClient, spawn_compositor, stop_processfrom ui_driver import UIDriver+ROOT = Path(__file__).resolve().parents[1]+INITIAL = '''# keep this comment+[input]+invert_scroll = false+pointer_speed = -0.4+pointer_speed_touchpad = 0.3+natural_scroll = true+left_handed = false+tap_to_click = true+tap_drag = false+disable_while_typing = false+disable_while_typing_touchpad = true++# keep this disconnected device+[[input_device]]+id = "stale-device"+natural_scroll = false # preserve this inline comment++[compositor]+xwayland = false+'''+++def wait(condition, description):+ deadline = time.monotonic() + 10+ while time.monotonic() < deadline:+ result = condition()+ if result:+ return result+ time.sleep(.05)+ raise AssertionError(description)+++class Fixture:+ def __init__(self, directory, hook, config):+ self.directory = directory+ self.fifo = directory / "pointer-commands"+ self.state_file = directory / "pointer-state.json"+ self.config_file = directory / "rediwm-config.toml"+ os.mkfifo(self.fifo, 0o600)+ self.fd = os.open(self.fifo, os.O_RDWR | os.O_NONBLOCK)+ self.connected = []+ self.process, self.log = spawn_compositor(directory, scale=os.getenv("REDIWM_TEST_SCALE", "1"), config_content=config, env_extra={+ "LD_PRELOAD": str(hook),+ "REDIWM_TEST_POINTER_COMMANDS": str(self.fifo),+ "REDIWM_TEST_POINTER_STATE": str(self.state_file),+ "DBUS_SESSION_BUS_ADDRESS": "unix:path=/nonexistent/rediwm-test-bus",+ "PULSE_SERVER": "unix:/nonexistent/rediwm-test-audio",+ "REDIWM_THEME": "",+ "HOME": str(directory / "home"),+ "XDG_CONFIG_HOME": str(directory / "config"),+ "XDG_DATA_HOME": str(directory / "data"),+ "XDG_CACHE_HOME": str(directory / "cache"),+ "REDIWM_APP_SCOPES": "0",+ })++ def close(self):+ stop_process(self.process)+ self.log.close()+ os.close(self.fd)++ def state(self):+ return json.loads(self.state_file.read_text())++ def command(self, command, index):+ os.write(self.fd, struct.pack("II", command, index))+ if command in (1, 2):+ wait(lambda: self.state()[index]["live"] == (command == 1), "pointer hotplug")+ if command == 1:+ self.connected.append(index)+ else:+ self.connected.remove(index)+ else:+ # Commands and IPC use separate fds; wait for a fresh snapshot.+ before = self.state_file.stat().st_mtime_ns+ os.write(self.fd, struct.pack("II", 3, index))+ wait(lambda: self.state_file.stat().st_mtime_ns != before, "fixture command")++ def select(self, ui, ipc, device):+ # IPC automation owns the first (non-libinput) pointer in this headless+ # session. It is shown read-only alongside the fixture's real devices.+ index = self.connected.index(device) + 1+ ui.click(ui.scroll_into_view("pointer_device"), panel="control_center")+ ui.wait_settled("control_center")+ ipc.key_down_up(102) # Home+ for _ in range(index):+ ipc.key_down_up(108) # Down+ ipc.key_down_up(28) # Return+ ui.wait_settled("control_center")+ wait(lambda: ui.find("pointer_device")["selected_index"] == index and not ui.find("pointer_device")["open"], "selected device")++ def click(self, ui, name, fraction=None):+ ui.wait_settled("control_center")+ widget = ui.scroll_into_view(name)+ assert not widget["is_disabled"], widget+ ui.click(widget, panel="control_center", fraction=fraction)+ ui.wait_settled("control_center")++ def saved(self):+ return tomllib.loads(self.config_file.read_text())+++def verify_failures(fixture, ui, ipc):+ # Backend failure must not publish or persist the requested value.+ fixture.select(ui, ipc, 0)+ before = fixture.config_file.read_text()+ fixture.command(4, 0)+ fixture.click(ui, "natural_scroll")+ assert not fixture.state()[0]["natural"]+ assert fixture.state()[0]["failures"] == 1+ assert fixture.config_file.read_text() == before+ assert any(w["label"] == "The device could not apply this setting." for w in ui.widgets())+ assert ui.find("natural_scroll")["on"] is False++ # A failed atomic save rolls back the backend change as well.+ backup = fixture.config_file.with_suffix(".backup")+ fixture.config_file.rename(backup)+ fixture.config_file.mkdir()+ try:+ fixture.click(ui, "natural_scroll")+ assert not fixture.state()[0]["natural"]+ assert any(w["label"] == "Could not save. The previous settings were restored." for w in ui.widgets())+ finally:+ fixture.config_file.rmdir()+ backup.rename(fixture.config_file)+ assert fixture.config_file.read_text() == before+ print("PASS: backend and persistence failures leave the prior setting intact")++++def assert_origins(ui, expected):+ for name, origin in expected.items():+ assert ui.find(name + "_origin")["label"] == origin, (name, ui.find(name + "_origin"))+++def setting_values(device):+ return {key: device[key] for key in ("speed", "natural", "left", "tap", "drag", "dwt")}+++def capture_input(ui, ipc, suffix, menu_open=False):+ preview = os.getenv("REDIWM_SETTINGS_PREVIEW")+ if not preview:+ return+ if not menu_open:+ ui.scroll_into_view("pointer_reset")+ ui.wait_settled("control_center")+ scale = os.getenv("REDIWM_TEST_SCALE", "1")+ path = Path(preview) / f"rediwm-input-{scale}-{suffix}.png"+ path.parent.mkdir(parents=True, exist_ok=True)+ path.unlink(missing_ok=True)+ ipc.screenshot(str(path))+++def verify_trackball_profile(fixture, ui, ipc):+ # udev identifies this unnamed device as a trackball; its display fallback+ # is Kensington Expert Mouse, which deliberately omits the word trackball.+ fixture.command(1, 5)+ fixture.select(ui, ipc, 5)+ before_records = fixture.saved()["input_device"]+ peers = fixture.state()[:5]+ assert_origins(ui, {"pointer_speed": "Default", "natural_scroll": "Default", "left_handed": "Default",+ "tap_to_click": "Not supported", "tap_drag": "Not supported", "disable_while_typing": "Not supported"})+ assert ui.find("pointer_reset")["is_disabled"]+ for name, fraction in (("pointer_speed", .85), ("natural_scroll", None), ("left_handed", None)):+ fixture.click(ui, name, fraction)+ assert_origins(ui, {"pointer_speed": "Custom", "natural_scroll": "Custom", "left_handed": "Custom"})+ assert not ui.find("pointer_reset")["is_disabled"]+ custom = setting_values(fixture.state()[5])+ assert custom["speed"] > .4 and not custom["natural"] and custom["left"]+ assert fixture.state()[:5] == peers, "trackball changes touched another device"+ new_record = next(r for r in fixture.saved()["input_device"] if r["id"] not in {r["id"] for r in before_records})+ profile_id = new_record["id"]+ saved = fixture.config_file.read_text()++ ui.scroll_into_view("pointer_reset")+ ui.click(ui.find("pointer_device"), panel="control_center")+ capture_input(ui, ipc, "devices-open", menu_open=True)+ ipc.key_down_up(1) # Escape closes the dropdown without changing selection.+ ui.wait_settled("control_center")++ # Failing the second setter tests rollback after pointer speed already+ # changed, rather than only refusing a reset before it touches the backend.+ fixture.command(5, 5)+ fixture.click(ui, "pointer_reset")+ assert setting_values(fixture.state()[5]) == custom+ assert fixture.state()[:5] == peers+ assert fixture.config_file.read_text() == saved+ assert_origins(ui, {"pointer_speed": "Custom", "natural_scroll": "Custom", "left_handed": "Custom"})+ assert any(w["label"] == "Could not reset. The previous settings were restored." for w in ui.widgets())++ backup = fixture.config_file.with_suffix(".backup")+ fixture.config_file.rename(backup)+ fixture.config_file.mkdir()+ try:+ fixture.click(ui, "pointer_reset")+ assert setting_values(fixture.state()[5]) == custom+ assert fixture.state()[:5] == peers+ assert any(w["label"] == "Could not save. The previous settings were restored." for w in ui.widgets())+ finally:+ fixture.config_file.rmdir()+ backup.rename(fixture.config_file)+ assert fixture.config_file.read_text() == saved++ fixture.click(ui, "pointer_reset")+ current = fixture.state()[5]+ assert math.isclose(current["speed"], -.4, abs_tol=1e-6) and current["natural"] and not current["left"]+ assert fixture.state()[:5] == peers+ records = fixture.saved()["input_device"]+ assert next(r for r in records if r["id"] == profile_id) == {"id": profile_id}+ assert [r for r in records if r["id"] != profile_id] == before_records+ assert_origins(ui, {"pointer_speed": "Default", "natural_scroll": "Default", "left_handed": "Default"})+ assert ui.find("pointer_reset")["is_disabled"]+ assert "# keep this comment" in fixture.config_file.read_text()+ assert "# preserve this inline comment" in fixture.config_file.read_text()++ # Reset means inheritance, including later defaults and reconnect/restart.+ fixture.config_file.write_text(fixture.config_file.read_text().replace("pointer_speed = -0.4", "pointer_speed = -0.2", 1))+ ipc.reload_config()+ wait(lambda: math.isclose(fixture.state()[5]["speed"], -.2, abs_tol=1e-6), "reset profile inherits reloaded defaults")+ assert fixture.state()[0]["speed"] > .4+ peers = fixture.state()[:5]+ fixture.command(2, 5)+ fixture.command(1, 5)+ fixture.select(ui, ipc, 5)+ assert math.isclose(fixture.state()[5]["speed"], -.2, abs_tol=1e-6)+ assert fixture.state()[:5] == peers+ assert_origins(ui, {"pointer_speed": "Default", "natural_scroll": "Default", "left_handed": "Default"})+ print("PASS: trackball profile, default/custom badges, atomic reset rollback, and reset inheritance after reload/replug")++++def run_session(fixture, restart):+ with IPCClient(fixture.directory, timeout=15) as ipc:+ ipc.wait_for("wallpaper_presented", timeout_ms=10000)+ fixture.command(1, 0) # mouse+ fixture.command(1, 1) # touchpad+ ui = UIDriver(ipc)+ ipc.action("open_control_center")+ ui.wait_settled("control_center")+ ui.click("Input", panel="control_center")+ ui.wait_settled("control_center")+ fixture.select(ui, ipc, 0)+ state = fixture.state()+ if restart:+ assert state[0]["natural"] is False and state[1]["natural"] is True, state+ assert state[0]["speed"] > .4 and math.isclose(state[1]["speed"], .6, abs_tol=1e-6), state+ assert state[0]["left"] is True and state[1]["left"] is False, state+ assert state[1]["tap"] is False and state[1]["drag"] is True and state[1]["dwt"] is False, state+ assert ui.find("natural_scroll")["on"] is False+ fixture.select(ui, ipc, 1)+ assert ui.find("natural_scroll")["on"] is True+ assert ui.find("tap_to_click")["on"] is False+ assert_origins(ui, {"pointer_speed": "Default", "natural_scroll": "Default", "tap_to_click": "Custom"})+ fixture.command(1, 5)+ fixture.select(ui, ipc, 5)+ assert math.isclose(fixture.state()[5]["speed"], -.2, abs_tol=1e-6)+ assert fixture.state()[5]["natural"] and not fixture.state()[5]["left"]+ assert ui.find("pointer_reset")["is_disabled"]+ assert_origins(ui, {"pointer_speed": "Default", "natural_scroll": "Default", "left_handed": "Default"})+ print("PASS: per-device settings and reset-to-default inheritance restored after compositor restart")+ return++ # Global-only configurations still select the appropriate device defaults.+ assert math.isclose(state[0]["speed"], -.4, abs_tol=1e-6) and math.isclose(state[1]["speed"], .3, abs_tol=1e-6), state+ assert state[0]["natural"] and state[1]["natural"], state+ assert state[1]["tap"] and not state[1]["drag"] and state[1]["dwt"], state+ assert ui.find("tap_to_click")["is_disabled"]+ assert ui.find("tap_drag")["is_disabled"]+ assert ui.find("disable_while_typing")["is_disabled"]+ assert_origins(ui, {"pointer_speed": "Default", "natural_scroll": "Default", "left_handed": "Default", "tap_to_click": "Not supported"})+ assert ui.find("pointer_reset")["is_disabled"]+ untouched = state[1].copy()+ fixture.click(ui, "natural_scroll")+ fixture.click(ui, "pointer_speed", .85)+ fixture.click(ui, "left_handed")+ state = fixture.state()+ assert state[0]["natural"] is False and state[0]["speed"] > .4 and state[0]["left"] is True, state+ assert state[1] == untouched, (state[1], untouched)+ assert_origins(ui, {"pointer_speed": "Custom", "natural_scroll": "Custom", "left_handed": "Custom"})+ fixture.select(ui, ipc, 1)+ assert ui.find("natural_scroll")["on"] is True+ assert abs(ui.find("pointer_speed")["value"] - .3) < .001+ for name in ("tap_to_click", "tap_drag", "disable_while_typing"):+ assert not ui.find(name)["is_disabled"]+ fixture.click(ui, name)+ state = fixture.state()+ assert not state[1]["tap"] and state[1]["drag"] and not state[1]["dwt"], state+ assert_origins(ui, {"pointer_speed": "Default", "natural_scroll": "Default", "tap_to_click": "Custom", "tap_drag": "Custom", "disable_while_typing": "Custom"})+ capture_input(ui, ipc, "touchpad")+ saved = fixture.saved()+ records = saved["input_device"]+ assert len(records) == 3, records+ assert next(r for r in records if r["id"] == "stale-device") == {"id": "stale-device", "natural_scroll": False}+ assert saved["input"]["pointer_speed"] == -.4 and saved["input"]["natural_scroll"] is True+ assert "# keep this comment" in fixture.config_file.read_text()+ assert "# preserve this inline comment" in fixture.config_file.read_text()+ print("PASS: independent natural scrolling, speed and touchpad capabilities; partial records preserve unrelated config")++ # Reload changes inherited defaults without erasing either override.+ text = fixture.config_file.read_text().replace("pointer_speed_touchpad = 0.3", "pointer_speed_touchpad = 0.6")+ fixture.config_file.write_text(text.replace("natural_scroll = true", "natural_scroll = false", 1))+ ipc.reload_config()+ wait(lambda: math.isclose(fixture.state()[1]["speed"], .6, abs_tol=1e-6), "inherited pointer speed on reload")+ assert fixture.state()[0]["speed"] == state[0]["speed"]+ assert not fixture.state()[1]["natural"]+ fixture.config_file.write_text(text)+ ipc.reload_config()+ wait(lambda: fixture.state()[1]["natural"], "inherited natural scrolling on reload")+ assert not fixture.state()[0]["natural"]+ print("PASS: configuration reload preserves overrides and updates inherited defaults")++ verify_failures(fixture, ui, ipc)++ # Same labels/model, different physical ports: the new mouse inherits+ # defaults, then has a separate override and leaves the first untouched.+ fixture.command(1, 2)+ fixture.select(ui, ipc, 2)+ assert fixture.state()[2]["natural"] and math.isclose(fixture.state()[2]["speed"], -.4, abs_tol=1e-6)+ original = fixture.state()[0].copy()+ fixture.click(ui, "pointer_speed", .25)+ assert fixture.state()[2]["speed"] < -.45+ assert fixture.state()[0] == original+ assert len(fixture.saved()["input_device"]) == 4++ # Remove the selected device with its dropdown open. Stale live pointer+ # dereferences abort the fixture; reconnect uses a changed event number.+ fixture.select(ui, ipc, 0)+ ui.click(ui.scroll_into_view("pointer_device"), panel="control_center")+ fixture.command(2, 0)+ ui.wait_settled("control_center")+ assert fixture.process.poll() is None+ assert ui.find("pointer_device")["open"] is False+ peer = fixture.state()[1].copy()+ fixture.command(1, 0)+ fixture.select(ui, ipc, 0)+ assert not fixture.state()[0]["natural"] and fixture.state()[0]["speed"] == original["speed"]+ assert fixture.state()[1] == peer+ print("PASS: identical device names use distinct paths; removal and reconnection preserve selection safety and settings")++ # An actual identity collision refuses overrides on both devices. The+ # survivor remains ambiguous until both instances have been disconnected.+ fixture.command(1, 3)+ fixture.select(ui, ipc, 0)+ assert fixture.state()[0]["natural"] and fixture.state()[3]["natural"]+ assert ui.find("natural_scroll")["is_disabled"]+ fixture.command(2, 3)+ ui.wait_settled("control_center")+ assert ui.find("natural_scroll")["is_disabled"]+ fixture.command(2, 0)+ fixture.command(1, 0)+ fixture.select(ui, ipc, 0)+ assert not ui.find("natural_scroll")["is_disabled"]+ assert not fixture.state()[0]["natural"]++ fixture.command(1, 4)+ fixture.select(ui, ipc, 4)+ for name in ("natural_scroll", "left_handed", "tap_to_click", "tap_drag", "disable_while_typing"):+ assert ui.find(name)["is_disabled"]+ assert ui.find("pointer_speed")["role"] != "slider"+ assert fixture.state()[4]["writes"] == 0 and fixture.state()[4]["failures"] == 0+ print("PASS: ambiguous identities and unsupported backend capabilities are unavailable")++ verify_trackball_profile(fixture, ui, ipc)++ # Genuinely global controls still use ordinary [input] persistence.+ for name in ("repeat_delay", "repeat_rate"):+ fixture.click(ui, name, .9)+ saved = fixture.saved()["input"]+ assert saved["key_repeat_delay"] != 400 and saved["key_repeat_rate"] != 25+ assert saved["invert_scroll"] is False and saved["tap_drag"] is False+def run():with tempfile.TemporaryDirectory(prefix="rediwm-input-save-") as directory:root = Path(directory)- config = '# keep this comment\n[input]\ninvert_scroll = false\ntap_drag = false\n'- expected = None+ flags = shlex.split(subprocess.check_output(+ ["pkg-config", "--cflags", "--libs", "wlroots-0.20", "wayland-server", "libinput", "libudev"], text=True))+ hook = root / "pointer-settings.so"+ subprocess.run(["cc", "-shared", "-fPIC", "-Wall", "-Wextra", "-Werror",+ str(ROOT / "tests/pointer_settings_hook.c"), "-o", str(hook), *flags, "-ldl"], check=True)+ config = INITIALfor restart in range(2):runtime = root / str(restart)- runtime.mkdir()- process, log = spawn_compositor(runtime, config_content=config, env_extra={- "DBUS_SESSION_BUS_ADDRESS": "unix:path=/nonexistent/rediwm-test-bus",- "PULSE_SERVER": "unix:/nonexistent/rediwm-test-audio",- "REDIWM_THEME": "",- })+ runtime.mkdir(mode=0o700)+ fixture = Fixture(runtime, hook, config)try:- with IPCClient(runtime, timeout=15) as ipc:- ui = UIDriver(ipc)- ipc.wait_for("wallpaper_presented", timeout_ms=10000)- ipc.action('open_control_center')- ui.wait_settled("control_center")-- def widgets():- return ipc.get_widget_tree("control_center")["widgets"]-- def click(widget, fraction=.5):- box = ipc.get_shell_state()["control_center"]["box"]- rect = widget["box"]- ipc.move_cursor(round(box["x"] + rect["x"] + rect["width"] * fraction),- round(box["y"] + rect["y"] + rect["height"] / 2))- ipc.pointer_button(272, True)- ipc.pointer_button(272, False)- time.sleep(.15)-- def click_named(name, fraction=.5):- # The panel is taller than the headless output: scroll first.- click(ui.scroll_into_view(name), fraction)-- click(next(w for w in widgets() if w["label"] == "Input"))- ui.wait_settled("control_center")- if restart == 0:- click(next(w for w in widgets() if w["role"] == "slider"), .8)- for name in ("left_handed", "natural_scroll", "tap_to_click"):- click_named(name)- for name in ("repeat_delay", "repeat_rate"):- click_named(name, .9)- config = (runtime / "rediwm-config.toml").read_text()- saved = tomllib.loads(config)["input"]- assert saved["pointer_speed"] > 0, saved- assert saved["left_handed"] is True, saved- assert saved["natural_scroll"] is False, saved- assert saved["tap_to_click"] is False, saved- assert saved["key_repeat_delay"] != 400, saved- assert saved["key_repeat_rate"] != 25, saved- assert saved["tap_drag"] is False and saved["invert_scroll"] is False- assert "# keep this comment" in config- # Reopen to compare precisely the same rebuilt widget tree.- ipc.action('open_control_center')- ipc.action('open_control_center')- click(next(w for w in widgets() if w["label"] == "Input"))- expected = [(w["role"], w["label"], w["box"]) for w in widgets()]- else:- assert [(w["role"], w["label"], w["box"]) for w in widgets()] == expected- # Toggle and increment restored values to inspect state that- # the widget-tree protocol does not expose directly.- for name in ("left_handed", "natural_scroll", "tap_to_click"):- click_named(name)- for name in ("repeat_delay", "repeat_rate"):- click_named(name, .9)- restored = tomllib.loads((runtime / "rediwm-config.toml").read_text())["input"]- assert restored["left_handed"] is False- assert restored["natural_scroll"] is True- assert restored["tap_to_click"] is True- assert restored["key_repeat_delay"] == saved["key_repeat_delay"] + 50- assert restored["key_repeat_rate"] == saved["key_repeat_rate"] + 5+ run_session(fixture, restart)+ config = fixture.config_file.read_text()+ except Exception:+ fixture.log.flush()+ print(Path(fixture.log.name).read_text()[-6000:])+ raisefinally:- stop_process(process)- log.close()- print("PASS: Input settings persisted through UI changes and compositor restart")+ fixture.close()if __name__ == "__main__":diff --git a/tests/pointer_settings_hook.c b/tests/pointer_settings_hook.cnew file mode 100644index 0000000..6485f4b--- /dev/null+++ b/tests/pointer_settings_hook.c@@ -0,0 +1,210 @@+// Noninstalled fake libinput backend. Exercises the production pointer lifecycle+// and UI in an isolated headless compositor, without opening host input devices.+#define _GNU_SOURCE+#define WLR_USE_UNSTABLE+#include <assert.h>+#include <dlfcn.h>+#include <fcntl.h>+#include <libinput.h>+#include <libudev.h>+#include <stdbool.h>+#include <stdint.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>+#include <unistd.h>+#include <wayland-server-core.h>+#include <wlr/backend/headless.h>+#include <wlr/backend/libinput.h>+#include <wlr/interfaces/wlr_pointer.h>++struct fake_device {+ struct wlr_pointer pointer;+ bool live, fail_next;+ double speed;+ bool natural, left, tap, drag, dwt;+ unsigned generation, writes, failures;+ unsigned fail_after;+};+static struct fake_device devices[6];+static struct wlr_backend *backend;+static const struct wlr_pointer_impl impl = {.name = "pointer-settings-fixture"};+static const char *names[] = {"Fixture Mouse", "Fixture Touchpad", "Fixture Mouse", "Fixture Mouse", "Fixture Unsupported", ""};+static const char *paths[] = {"pci-fixture-usb-0:1:1.0", "platform-fixture-touchpad", "pci-fixture-usb-0:2:1.0", "pci-fixture-usb-0:1:1.0", NULL, "pci-fixture-usb-0:3:1.0"};+static char sysnames[6][32];++static int index_of(const void *device) {+ for (unsigned i = 0; i < 6; i++) if (device == &devices[i]) return (int)i;+ return -1;+}+static int live_index(const void *device) {+ int i = index_of(device);+ assert(i >= 0 && devices[i].live); // Any stale selected-device access aborts.+ return i;+}+#define REAL(name) __typeof__(&name) real = (__typeof__(&name))dlsym(RTLD_NEXT, #name); assert(real)++static void snapshot(void) {+ const char *path = getenv("REDIWM_TEST_POINTER_STATE");+ assert(path);+ char temporary[4096];+ assert(snprintf(temporary, sizeof(temporary), "%s.tmp", path) < (int)sizeof(temporary));+ FILE *file = fopen(temporary, "w");+ assert(file);+ fputs("[", file);+ for (unsigned i = 0; i < 6; i++) {+ struct fake_device *d = &devices[i];+ fprintf(file, "%s{\"live\":%s,\"speed\":%.9g,\"natural\":%s,\"left\":%s,\"tap\":%s,\"drag\":%s,\"dwt\":%s,\"writes\":%u,\"failures\":%u}",+ i ? "," : "", d->live ? "true" : "false", d->speed,+ d->natural ? "true" : "false", d->left ? "true" : "false",+ d->tap ? "true" : "false", d->drag ? "true" : "false", d->dwt ? "true" : "false", d->writes, d->failures);+ }+ fputs("]\n", file);+ assert(fclose(file) == 0);+ assert(rename(temporary, path) == 0);+}++static int input_ready(int fd, uint32_t mask, void *data) {+ (void)mask; (void)data;+ uint32_t packet[2];+ ssize_t n;+ while ((n = read(fd, packet, sizeof(packet))) == sizeof(packet)) {+ unsigned index = packet[1];+ assert(index < 6);+ struct fake_device *d = &devices[index];+ switch (packet[0]) {+ case 1:+ assert(!d->live);+ d->live = true;+ d->speed = -.2;+ d->natural = d->left = d->tap = d->drag = d->dwt = false;+ d->fail_next = false;+ d->fail_after = 0;+ d->generation++;+ snprintf(sysnames[index], sizeof(sysnames[index]), "event%u", index + d->generation * 10);+ wlr_pointer_init(&d->pointer, &impl, names[index]);+ wl_signal_emit_mutable(&backend->events.new_input, &d->pointer.base);+ break;+ case 2:+ assert(d->live);+ wlr_pointer_finish(&d->pointer);+ d->live = false;+ break;+ case 3: break;+ case 4: d->fail_next = true; break;+ case 5: d->fail_after = 2; break; // Reject the second reset setter.+ default: assert(false);+ }+ snapshot();+ }+ assert(n <= 0);+ return 0;+}+struct wlr_backend *wlr_headless_backend_create(struct wl_event_loop *loop) {+ REAL(wlr_headless_backend_create);+ backend = real(loop);+ const char *path = getenv("REDIWM_TEST_POINTER_COMMANDS");+ assert(path && backend);+ int fd = open(path, O_RDWR | O_NONBLOCK | O_CLOEXEC);+ assert(fd >= 0);+ assert(wl_event_loop_add_fd(loop, fd, WL_EVENT_READABLE, input_ready, NULL));+ snapshot();+ return backend;+}+void wlr_backend_destroy(struct wlr_backend *target) {+ REAL(wlr_backend_destroy);+ if (target == backend) {+ for (unsigned i = 0; i < 6; i++) if (devices[i].live) {+ wlr_pointer_finish(&devices[i].pointer);+ devices[i].live = false;+ }+ }+ real(target);+}+bool wlr_input_device_is_libinput(struct wlr_input_device *device) {+ for (unsigned i = 0; i < 6; i++) if (device == &devices[i].pointer.base) return true;+ REAL(wlr_input_device_is_libinput);+ return real(device);+}+struct libinput_device *wlr_libinput_get_device_handle(struct wlr_input_device *device) {+ for (unsigned i = 0; i < 6; i++) if (device == &devices[i].pointer.base) {+ assert(devices[i].live);+ return (struct libinput_device *)&devices[i];+ }+ REAL(wlr_libinput_get_device_handle);+ return real(device);+}+const char *libinput_device_get_name(struct libinput_device *device) { return names[live_index(device)]; }+const char *libinput_device_get_sysname(struct libinput_device *device) { return sysnames[live_index(device)]; }+unsigned int libinput_device_get_id_bustype(struct libinput_device *device) { live_index(device); return 3; }+unsigned int libinput_device_get_id_vendor(struct libinput_device *device) { live_index(device); return 0x1234; }+unsigned int libinput_device_get_id_product(struct libinput_device *device) { int i = live_index(device); return i == 1 ? 2 : i == 5 ? 3 : 1; }+struct udev_device *libinput_device_get_udev_device(struct libinput_device *device) { live_index(device); return (struct udev_device *)device; }+struct udev_device *udev_device_unref(struct udev_device *device) {+ if (index_of(device) >= 0) return NULL;+ REAL(udev_device_unref); return real(device);+}+struct udev_device *udev_device_get_parent(struct udev_device *device) {+ if (index_of(device) >= 0) return NULL;+ REAL(udev_device_get_parent); return real(device);+}+const char *udev_device_get_sysattr_value(struct udev_device *device, const char *key) {+ if (index_of(device) >= 0) return strcmp(key, "bInterfaceNumber") == 0 ? "00" : NULL;+ REAL(udev_device_get_sysattr_value); return real(device, key);+}+const char *udev_device_get_property_value(struct udev_device *device, const char *key) {+ int i = index_of(device);+ if (i >= 0) {+ if (strcmp(key, "ID_PATH") == 0) return paths[i];+ if (strcmp(key, "ID_SERIAL_SHORT") == 0 && i == 1) return "fixture-touchpad-serial";+ if (strcmp(key, "ID_INPUT_TOUCHPAD") == 0) return i == 1 ? "1" : NULL;+ if (strcmp(key, "ID_INPUT_MOUSE") == 0) return i != 1 && i != 4 ? "1" : NULL;+ if (strcmp(key, "ID_INPUT_TRACKBALL") == 0) return i == 5 ? "1" : NULL;+ if (strcmp(key, "ID_VENDOR_FROM_DATABASE") == 0 && i == 5) return "Kensington";+ if (strcmp(key, "ID_MODEL_FROM_DATABASE") == 0 && i == 5) return "Expert Mouse";+ return NULL;+ }+ REAL(udev_device_get_property_value); return real(device, key);+}+int libinput_device_has_capability(struct libinput_device *device, enum libinput_device_capability cap) {+ live_index(device); return cap == LIBINPUT_DEVICE_CAP_POINTER;+}+int libinput_device_config_accel_is_available(struct libinput_device *device) { return live_index(device) != 4; }+int libinput_device_config_scroll_has_natural_scroll(struct libinput_device *device) { return live_index(device) != 4; }+int libinput_device_config_left_handed_is_available(struct libinput_device *device) { return live_index(device) != 4; }+int libinput_device_config_tap_get_finger_count(struct libinput_device *device) { return live_index(device) == 1 ? 3 : 0; }+int libinput_device_config_dwt_is_available(struct libinput_device *device) { return live_index(device) == 1; }+double libinput_device_config_accel_get_speed(struct libinput_device *device) { return devices[live_index(device)].speed; }+int libinput_device_config_scroll_get_natural_scroll_enabled(struct libinput_device *device) { return devices[live_index(device)].natural; }+int libinput_device_config_left_handed_get(struct libinput_device *device) { return devices[live_index(device)].left; }+enum libinput_config_tap_state libinput_device_config_tap_get_enabled(struct libinput_device *device) { return devices[live_index(device)].tap ? LIBINPUT_CONFIG_TAP_ENABLED : LIBINPUT_CONFIG_TAP_DISABLED; }+enum libinput_config_drag_state libinput_device_config_tap_get_drag_enabled(struct libinput_device *device) { return devices[live_index(device)].drag ? LIBINPUT_CONFIG_DRAG_ENABLED : LIBINPUT_CONFIG_DRAG_DISABLED; }+enum libinput_config_dwt_state libinput_device_config_dwt_get_enabled(struct libinput_device *device) { return devices[live_index(device)].dwt ? LIBINPUT_CONFIG_DWT_ENABLED : LIBINPUT_CONFIG_DWT_DISABLED; }++static enum libinput_config_status can_write(struct fake_device *d, bool supported) {+ assert(d->live);+ if (!supported) { d->failures++; snapshot(); return LIBINPUT_CONFIG_STATUS_UNSUPPORTED; }+ if (d->fail_next || (d->fail_after && --d->fail_after == 0)) {+ d->fail_next = false; d->failures++; snapshot(); return LIBINPUT_CONFIG_STATUS_INVALID;+ }+ d->writes++;+ return LIBINPUT_CONFIG_STATUS_SUCCESS;+}+enum libinput_config_status libinput_device_config_accel_set_speed(struct libinput_device *device, double value) {+ int i = live_index(device); struct fake_device *d = &devices[i];+ enum libinput_config_status status = can_write(d, i != 4);+ if (status == LIBINPUT_CONFIG_STATUS_SUCCESS) d->speed = value;+ snapshot(); return status;+}+#define BOOL_SETTER(name, type, field, support) \+ enum libinput_config_status name(struct libinput_device *device, type value) { \+ int i = live_index(device); struct fake_device *d = &devices[i]; \+ enum libinput_config_status status = can_write(d, (support)); \+ if (status == LIBINPUT_CONFIG_STATUS_SUCCESS) d->field = value != 0; \+ snapshot(); return status; \+ }+BOOL_SETTER(libinput_device_config_scroll_set_natural_scroll_enabled, int, natural, i != 4)+BOOL_SETTER(libinput_device_config_left_handed_set, int, left, i != 4)+BOOL_SETTER(libinput_device_config_tap_set_enabled, enum libinput_config_tap_state, tap, i == 1)+BOOL_SETTER(libinput_device_config_tap_set_drag_enabled, enum libinput_config_drag_state, drag, i == 1)+BOOL_SETTER(libinput_device_config_dwt_set_enabled, enum libinput_config_dwt_state, dwt, i == 1)