From 98120f880b12c1de8a6512a909b620c1008810d6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Berkay=20K=C3=B6sebay?= Date: Tue, 1 Dec 2026 18:02:04 +0100 Subject: [PATCH 01/17] ARMv7: use Orchard Mesa and run Labwc on SGX MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Assisted-by: LLM Signed-off-by: Berkay Kösebay --- desktop/armv7/README.md | 6 +++-- desktop/configuration/login-session | 41 ++++++++++++++++++++++------- system/assemble-rootfs | 9 +++---- system/orchard-packages.txt | 9 ++++--- tests/test_orchard_repository.py | 12 +++++---- 5 files changed, 51 insertions(+), 26 deletions(-) diff --git a/desktop/armv7/README.md b/desktop/armv7/README.md index 5adb02fb..af662d51 100644 --- a/desktop/armv7/README.md +++ b/desktop/armv7/README.md @@ -3,12 +3,14 @@ `python -m release.package --output DIR --architecture armv7h` makes the ARMv7 `omarchy-a` package of the checkout (the keyboard and cursor helper compiled for ARMv7) in the ARMv7 builder. The image installs it, and `wlroots0.20`, `labwc`, -`omafox`, `omactivity`, `folio-touch` (Files) and `omacalc` from the ARMv7 channel of the +`omafox`, `omactivity`, `folio-touch` (Files), `omacalc` and `mesa` from the ARMv7 channel of the [Orchard package repository](https://github.com/OrchardLinux/packages) (`repo-armv7h`), listed before Arch Linux ARM's repositories. Upstream Omarchy publishes no ARMv7 packages, so an ARMv7 image has no `[omarchy]` repository and Omacalc is the Orchard repository's build of upstream's pinned source. -Mesa is Arch Linux ARM's there. +Mesa is the Orchard repository's too: OrchardLinux's fork with the SGX543's +OpenGL ES 2 driver (the A5 and A6) and software OpenGL, in the place of Arch +Linux ARM's. A provisioned native ARMv7 Arch Linux ARM environment can run the recipes with `ORCHARD_BUILD_NATIVE=1` and `ORCHARD_BUILD_ENV_ID` set to its reproducible image diff --git a/desktop/configuration/login-session b/desktop/configuration/login-session index 5d5b98cc..7dab28db 100644 --- a/desktop/configuration/login-session +++ b/desktop/configuration/login-session @@ -34,25 +34,41 @@ export LIBGL_ALWAYS_SOFTWARE=1 LIBSEAT_BACKEND=seatd MOZ_ENABLE_WAYLAND=1 # which (journalctl -t omarchy-gpu-probe). On the GPU desktop the shell and # its apps draw with Qt Quick on the GPU; on the software desktop with Qt's # software renderer. -gpu= +# A board with the A5's or A6's PowerVR SGX543 (kernel driver apple-sgx) has one +# card that is both its display controller and its GPU, and Mesa's sgx driver +# draws OpenGL ES 2 on it: there Labwc draws on wlroots' GLES2 renderer on that +# card and applications get the GPU's OpenGL ES, once gpu-probe has drawn a frame +# that way in this boot. The shell keeps Qt's software renderer: the SGX has +# OpenGL ES 2 only, and Qt Quick on it is untested. +gpu= gpu_driver= for node in /sys/class/drm/renderD*; do - if [[ $(basename "$(readlink -f "$node/device/driver")") == powervr ]]; then gpu=$node; fi + driver=$(basename "$(readlink -f "$node/device/driver")") + if [[ $driver == powervr || $driver == apple-sgx ]]; then gpu=$node gpu_driver=$driver; fi done if [[ -n $gpu ]]; then gpu_probe=/usr/lib/omarchy-a/gpu-probe gpu_log=$XDG_RUNTIME_DIR/omarchy-gpu-probe.log - # The GPU has no display outputs: Labwc must open the display's card only. + # The PowerVR GPU has no display outputs: Labwc must open the display's card + # only. The SGX's card is the display. display= for card in /sys/class/drm/card*; do - if [[ ${card##*/} =~ ^card[0-9]+$ && $(readlink -f "$card/device") != "$(readlink -f "$gpu/device")" ]]; then + [[ ${card##*/} =~ ^card[0-9]+$ ]] || continue + if [[ $gpu_driver == apple-sgx ]]; then + if [[ $(readlink -f "$card/device") == "$(readlink -f "$gpu/device")" ]]; then display=/dev/dri/${card##*/}; fi + elif [[ $(readlink -f "$card/device") != "$(readlink -f "$gpu/device")" ]]; then display=/dev/dri/${card##*/} fi done - # GTK draws with Vulkan: GTK 4 takes its Vulkan renderer by itself only when the driver offers a dma-buf - # modifier other than LINEAR. Where it offers LINEAR alone (the A7), GTK took its GL renderer on Zink, which - # drew text twice and WebKit's pages not at all (Web showed an empty window); Vulkan draws them right. - gpu_desktop=(WLR_RENDERER=gles2 "WLR_RENDER_DRM_DEVICE=/dev/dri/${gpu##*/}" - MESA_LOADER_DRIVER_OVERRIDE=zink PVR_I_WANT_A_BROKEN_VULKAN_DRIVER=1 GSK_RENDERER=vulkan) + if [[ $gpu_driver == apple-sgx ]]; then + # The display's own card renders: wlroots finds the GPU through it. + gpu_desktop=(WLR_RENDERER=gles2) + else + # GTK draws with Vulkan: GTK 4 takes its Vulkan renderer by itself only when the driver offers a dma-buf + # modifier other than LINEAR. Where it offers LINEAR alone (the A7), GTK took its GL renderer on Zink, which + # drew text twice and WebKit's pages not at all (Web showed an empty window); Vulkan draws them right. + gpu_desktop=(WLR_RENDERER=gles2 "WLR_RENDER_DRM_DEVICE=/dev/dri/${gpu##*/}" + MESA_LOADER_DRIVER_OVERRIDE=zink PVR_I_WANT_A_BROKEN_VULKAN_DRIVER=1 GSK_RENDERER=vulkan) + fi if [[ -n $display ]]; then gpu_desktop+=("WLR_DRM_DEVICES=$display") # simpledrm cannot scan out a buffer the GPU drew (it takes no dma-buf), so @@ -64,7 +80,9 @@ if [[ -n $gpu ]]; then gpu_desktop+=(WLR_SCENE_DISABLE_DIRECT_SCANOUT=1) fi fi - if [[ ! -e /usr/share/vulkan/icd.d/powervr_mesa_icd.json ]]; then + if [[ $gpu_driver == apple-sgx && ! -e /usr/lib/dri/apple_sgx_dri.so ]]; then + gpu_verdict='software desktop: this image has no OpenGL ES driver for the GPU' + elif [[ $gpu_driver == powervr && ! -e /usr/share/vulkan/icd.d/powervr_mesa_icd.json ]]; then gpu_verdict='software desktop: this image has no Vulkan driver for the GPU' elif [[ -z $display || ! -x $gpu_probe ]]; then gpu_verdict='software desktop: no display card or no gpu-probe to test the GPU with' @@ -77,6 +95,7 @@ if [[ -n $gpu ]]; then gpu_key= if [[ -n $gpu_cache ]]; then gpu_icd_sig=$(stat -Lc '%Y:%s' /usr/share/vulkan/icd.d/powervr_mesa_icd.json 2>/dev/null || echo icd) + if [[ $gpu_driver == apple-sgx ]]; then gpu_icd_sig=$(stat -Lc '%Y:%s' /usr/lib/libgbm.so.1 2>/dev/null || echo gbm); fi gpu_probe_sig=$(stat -Lc '%Y:%s' "$gpu_probe" 2>/dev/null || echo probe) gpu_key="$(uname -r)|${display_driver:-none}|$gpu_icd_sig|$gpu_probe_sig" fi @@ -86,6 +105,7 @@ if [[ -n $gpu ]]; then export "${gpu_desktop[@]}" MESA_DISK_CACHE_SINGLE_FILE=1 unset LIBGL_ALWAYS_SOFTWARE QT_QUICK_BACKEND export QSG_NO_DEPTH_BUFFER=1 QSG_NO_STENCIL_BUFFER=1 + if [[ $gpu_driver == apple-sgx ]]; then export QT_QUICK_BACKEND=software; fi else # The probe runs with the environment the desktop would get. The login # waits for it 10 s at most and does not depend on it ending: a probe @@ -109,6 +129,7 @@ if [[ -n $gpu ]]; then # keeps a full-size depth/stencil buffer in memory that the UI never # reads (on the iPod touch 6 that is about 50 MB in the shell alone). export QSG_NO_DEPTH_BUFFER=1 QSG_NO_STENCIL_BUFFER=1 + if [[ $gpu_driver == apple-sgx ]]; then export QT_QUICK_BACKEND=software; fi if [[ -n $gpu_cache ]]; then mkdir -p "$(dirname "$gpu_cache")" 2>/dev/null || true printf '%s\n%s\n' "$gpu_key" "$gpu_detail" >"$gpu_cache.tmp" 2>/dev/null && diff --git a/system/assemble-rootfs b/system/assemble-rootfs index 9eff3e29..94af7186 100755 --- a/system/assemble-rootfs +++ b/system/assemble-rootfs @@ -151,11 +151,10 @@ if [[ ! $release =~ ^[0-9] && $architecture == aarch64 ]]; then fi # Every dependency of every installed package is met. pacman --config "$config" --root "$root" --gpgdir "$gpgdir" -Dk -if [[ $architecture == aarch64 ]]; then - # OpenGL, the GPU's Vulkan driver and the GPU probe are the fork's Mesa's. - [[ $(pacman --root "$root" -Qoq "$root/usr/lib/libEGL_mesa.so.0" "$root/usr/lib/libgbm.so.1" \ - "$root/usr/lib/libvulkan_powervr_mesa.so" "$root/usr/lib/orchard/gpu-probe" | sort -u) == mesa ]] -fi +# OpenGL, the GPU's driver (64-bit: its Vulkan driver) and the GPU probe are the fork's Mesa's. +mesa_files=("$root/usr/lib/libEGL_mesa.so.0" "$root/usr/lib/libgbm.so.1") +[[ $architecture != aarch64 ]] || mesa_files+=("$root/usr/lib/libvulkan_powervr_mesa.so") +[[ $(pacman --root "$root" -Qoq "${mesa_files[@]}" "$root/usr/lib/orchard/gpu-probe" | sort -u) == mesa ]] # The home starts as /etc/skel, which the omarchy-a package filled: the tablet # user's defaults, and the record that every migration it ships is done. useradd --root "$root" --create-home --uid 1000 --user-group --shell /bin/bash tablet diff --git a/system/orchard-packages.txt b/system/orchard-packages.txt index 90c5775c..9474410a 100644 --- a/system/orchard-packages.txt +++ b/system/orchard-packages.txt @@ -12,10 +12,11 @@ labwc omafox omactivity folio-touch -# 64-bit boards: Mesa from OrchardLinux's fork in the place of Arch's (OpenGL through Zink or in -# software, the GPU's Vulkan driver, the login's GPU probe), and the VA-API bridge to the hardware -# video decoders. The GPU parts and the bridge sit unused on a board without that hardware. -mesa aarch64 +# Mesa from OrchardLinux's fork in the place of Arch's, with the login's GPU probe: on 64-bit +# boards OpenGL through Zink or in software and the PowerVR GPU's Vulkan driver, on 32-bit boards +# the SGX543's OpenGL ES 2 driver and software OpenGL. 64-bit boards also take the VA-API bridge to +# the hardware video decoders. The GPU parts and the bridge sit unused on a board without that hardware. +mesa libva-v4l2-request aarch64 # Omacalc: upstream Omarchy publishes it for aarch64 only; the Orchard repository has ARMv7's. omacalc armv7h diff --git a/tests/test_orchard_repository.py b/tests/test_orchard_repository.py index 6d8955c1..5d05cea7 100644 --- a/tests/test_orchard_repository.py +++ b/tests/test_orchard_repository.py @@ -28,7 +28,7 @@ Include = /etc/pacman.d/mirrorlist ''' ORCHARD = {'aarch64': ['wlroots0.20', 'labwc', 'omafox', 'omactivity', 'folio-touch', 'mesa', 'libva-v4l2-request'], - 'armv7h': ['wlroots0.20', 'labwc', 'omafox', 'omactivity', 'folio-touch', 'omacalc']} + 'armv7h': ['wlroots0.20', 'labwc', 'omafox', 'omactivity', 'folio-touch', 'mesa', 'omacalc']} def section(start, end): @@ -150,12 +150,14 @@ def test_one_transaction_installs_ours_with_everything_else(self): self.assertFalse([call for call in calls if re.search(r'(^| )-(R|U)', call)]) self.assertNotIn('-U', ASSEMBLE.read_text()) - def test_armv7_takes_files_and_omacalc_from_ours_and_keeps_archs_mesa(self): + def test_armv7_takes_files_omacalc_and_mesa_from_ours(self): code, calls, error = self.install('armv7h') self.assertEqual(code, 0, error) - wanted = 'base labwc wlroots0.20 omafox omactivity folio-touch omacalc omarchy-a' - self.assertEqual(calls, [f'download -Sy --noconfirm {wanted}', f'-S --print --print-format %r/%n {wanted}', - f'-S --noconfirm {wanted}', 'repositories', '-Dk']) + wanted = 'base labwc wlroots0.20 omafox omactivity folio-touch mesa omacalc omarchy-a' + self.assertEqual(calls[:5], [f'download -Sy --noconfirm {wanted}', f'-S --print --print-format %r/%n {wanted}', + f'-S --noconfirm {wanted}', 'repositories', '-Dk']) + self.assertIn('/r/usr/lib/libgbm.so.1 /r/usr/lib/orchard/gpu-probe', calls[5]) + self.assertNotIn('libvulkan_powervr_mesa.so', calls[5]) def test_a_package_of_ours_taken_elsewhere_stops_before_anything_installs(self): for planned in ([name for name in ORCHARD['aarch64'] if name != 'mesa'], # mesa would be Arch's From 7f84e524512e9edbda7318228886770b32cf3959 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Berkay=20K=C3=B6sebay?= Date: Tue, 1 Dec 2026 18:02:06 +0100 Subject: [PATCH 02/17] shell: construct hidden windows on first use MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Keep IPC, gesture listeners and bar buttons alive while their panels are cold. Let the dedicated picker process own its UI, and keep the lock surface ready at login. Assisted-by: LLM Signed-off-by: Berkay Kösebay --- desktop/shell/shell/Ui/LazyKeyboardPanel.qml | 37 +++++ desktop/shell/shell/Ui/OnDemandLoader.qml | 13 ++ desktop/shell/shell/Ui/qmldir | 2 + .../shell/controlcenter/ControlCenter.qml | 36 +---- desktop/shell/shell/launcher/Launcher.qml | 1 - .../notificationcenter/NotificationCenter.qml | 29 +--- desktop/shell/shell/plugins/agents/Panel.qml | 2 +- .../shell/plugins/background/Background.qml | 2 +- desktop/shell/shell/plugins/bar/Bar.qml | 14 +- .../shell/shell/plugins/bar/widgets/Tray.qml | 13 +- .../shell/plugins/clipboard/Clipboard.qml | 18 ++- desktop/shell/shell/plugins/dock/Dock.qml | 14 +- desktop/shell/shell/plugins/emojis/Emojis.qml | 14 +- desktop/shell/shell/plugins/flash/Flash.qml | 28 ++-- .../plugins/image-picker/ImagePicker.qml | 29 ++-- desktop/shell/shell/plugins/lock/Service.qml | 4 +- desktop/shell/shell/plugins/menu/Menu.qml | 23 ++- .../shell/plugins/notifications/Service.qml | 6 +- desktop/shell/shell/plugins/osd/Osd.qml | 145 +++++++++--------- .../shell/plugins/panels/audio/Panel.qml | 2 +- .../shell/plugins/panels/bluetooth/Panel.qml | 2 +- .../shell/plugins/panels/clock/BarWidget.qml | 5 +- .../shell/plugins/panels/dropbox/Panel.qml | 2 +- .../shell/plugins/panels/elsewhen/Panel.qml | 2 +- .../shell/plugins/panels/monitor/Panel.qml | 2 +- .../shell/plugins/panels/network/Panel.qml | 2 +- .../shell/plugins/panels/power/Panel.qml | 2 +- .../shell/plugins/panels/tailscale/Panel.qml | 2 +- .../shell/plugins/panels/weather/Panel.qml | 2 +- .../shell/plugins/polkit/PolkitAgent.qml | 25 +-- .../shell/plugins/reminders/ReminderFlow.qml | 12 +- .../plugins/services/media/BarWidget.qml | 7 +- .../shell/shell/services/BackgroundIntro.qml | 4 +- desktop/shell/shell/settings/Settings.qml | 2 +- desktop/shell/shell/shell.qml | 87 ++++++++--- 35 files changed, 350 insertions(+), 240 deletions(-) create mode 100644 desktop/shell/shell/Ui/LazyKeyboardPanel.qml create mode 100644 desktop/shell/shell/Ui/OnDemandLoader.qml diff --git a/desktop/shell/shell/Ui/LazyKeyboardPanel.qml b/desktop/shell/shell/Ui/LazyKeyboardPanel.qml new file mode 100644 index 00000000..22b30af9 --- /dev/null +++ b/desktop/shell/shell/Ui/LazyKeyboardPanel.qml @@ -0,0 +1,37 @@ +import QtQuick + +// A bar button and its IPC remain live. A host such as Control Center can +// also use content directly without constructing a separate popup window. +OnDemandLoader { + id: loader + required property Item anchorItem + required property QtObject bar + property var owner: null + property bool open: false + property bool centerOnBar: false + property bool yielding: false + property Item focusTarget: null + property int contentWidth: 0 + property int contentHeight: 0 + property Component content + readonly property Item loadedContent: item ? item.loadedContent : null + readonly property real loadedContentHeight: item ? item.loadedContentHeight : 0 + + function ensureContent() { return load().ensureContent() } + function fittedContentWidth(width, cap) { return item ? item.fittedContentWidth(width, cap) : width } + function fittedContentHeight(height, cap) { return item ? item.fittedContentHeight(height, cap) : height } + + requested: open + sourceComponent: KeyboardPanel { + anchorItem: loader.anchorItem + owner: loader.owner + bar: loader.bar + open: !!loader.item && loader.open + centerOnBar: loader.centerOnBar + yielding: loader.yielding + focusTarget: loader.focusTarget + contentWidth: loader.contentWidth + contentHeight: loader.contentHeight + content: loader.content + } +} diff --git a/desktop/shell/shell/Ui/OnDemandLoader.qml b/desktop/shell/shell/Ui/OnDemandLoader.qml new file mode 100644 index 00000000..2538fd31 --- /dev/null +++ b/desktop/shell/shell/Ui/OnDemandLoader.qml @@ -0,0 +1,13 @@ +import QtQuick + +// Keep the first instance so closing a window preserves its state and animations. +Loader { + active: false + property bool requested: false + onRequestedChanged: if (requested) active = true + + function load() { + active = true + return item + } +} diff --git a/desktop/shell/shell/Ui/qmldir b/desktop/shell/shell/Ui/qmldir index e45214be..18e08334 100644 --- a/desktop/shell/shell/Ui/qmldir +++ b/desktop/shell/shell/Ui/qmldir @@ -15,8 +15,10 @@ Dropdown 1.0 Dropdown.qml FilterInput 1.0 FilterInput.qml IconContentBounds 1.0 IconContentBounds.qml KeyboardPanel 1.0 KeyboardPanel.qml +LazyKeyboardPanel 1.0 LazyKeyboardPanel.qml MultiSelect 1.0 MultiSelect.qml NumberField 1.0 NumberField.qml +OnDemandLoader 1.0 OnDemandLoader.qml OpticalGlyph 1.0 OpticalGlyph.qml OverlayWindow 1.0 OverlayWindow.qml Panel 1.0 Panel.qml diff --git a/desktop/shell/shell/controlcenter/ControlCenter.qml b/desktop/shell/shell/controlcenter/ControlCenter.qml index 7567a33f..d06dceb2 100644 --- a/desktop/shell/shell/controlcenter/ControlCenter.qml +++ b/desktop/shell/shell/controlcenter/ControlCenter.qml @@ -559,41 +559,7 @@ Item { // Moving: the spring, a finger, or a popup's fade. readonly property bool moving: spring.running || root.pulling || popupIn.running || popupOut.running - // While open, a note for the Home button (omarchy-home-button closes it). - readonly property string openNote: (Quickshell.env("XDG_RUNTIME_DIR") || "/tmp") + "/omarchy-control-center-open" - // One writer, run again until the note matches: two detached commands could - // finish out of order and leave the note behind a closed control center, - // and Home would then only ever "close" it. A note left from an earlier - // shell goes at start. - property bool noteWritten: true - function writeOpenNote() { - if (noteWriter.running || root.noteWritten === root.opened) return - noteWriter.writing = root.opened - noteWriter.command = root.opened ? ["touch", root.openNote] : ["rm", "-f", root.openNote] - noteWriter.running = true - } - Process { - id: noteWriter - property bool writing: false - onExited: { - root.noteWritten = writing - root.writeOpenNote() - } - } - Component.onCompleted: writeOpenNote() - onOpenedChanged: { - writeOpenNote() - Qt.callLater(notePopupCard) - } - - ShellIpc { - target: "omarchy.controlcenter" - function toggle(): void { root.toggle() } - function open(): void { if (!root.opened) root.open() } - function close(): void { root.close() } - // Open at a module's page: omarchy.monitor, … - function page(module: string): void { root.openPage(module) } - } + onOpenedChanged: Qt.callLater(notePopupCard) // ------------------------------------------------------------- window diff --git a/desktop/shell/shell/launcher/Launcher.qml b/desktop/shell/shell/launcher/Launcher.qml index 147679a1..636381b7 100644 --- a/desktop/shell/shell/launcher/Launcher.qml +++ b/desktop/shell/shell/launcher/Launcher.qml @@ -574,7 +574,6 @@ Item { } } - Component.onCompleted: { wallpaperProc.running = true; opaqueProc.running = true } // Orchard: on the theme's plain background by default (no blurred copy // is made then); Trigger > Toggle > Frosted Launcher puts it on the frosted diff --git a/desktop/shell/shell/notificationcenter/NotificationCenter.qml b/desktop/shell/shell/notificationcenter/NotificationCenter.qml index 720560ed..75f5ed49 100644 --- a/desktop/shell/shell/notificationcenter/NotificationCenter.qml +++ b/desktop/shell/shell/notificationcenter/NotificationCenter.qml @@ -219,33 +219,8 @@ Item { function togglePopup() { root.toggle() } function animateIn() { root.settle(1, 0) } - // While open, a note for the Home button (omarchy-home-button closes it), - // written by one writer until it matches. - readonly property string openNote: (Quickshell.env("XDG_RUNTIME_DIR") || "/tmp") + "/omarchy-notification-center-open" - property bool noteWritten: true - function writeOpenNote() { - if (noteWriter.running || root.noteWritten === root.opened) return - noteWriter.writing = root.opened - noteWriter.command = root.opened ? ["touch", root.openNote] : ["rm", "-f", root.openNote] - noteWriter.running = true - } - Process { - id: noteWriter - property bool writing: false - onExited: { root.noteWritten = writing; root.writeOpenNote() } - } - Component.onCompleted: { writeOpenNote(); syncGroups() } - onOpenedChanged: { - writeOpenNote() - if (!opened && typing) endReply() - } - - ShellIpc { - target: "omarchy.notificationcenter" - function toggle(): void { root.toggle() } - function open(): void { if (!root.opened) root.open() } - function close(): void { root.close() } - } + Component.onCompleted: syncGroups() + onOpenedChanged: if (!opened && typing) endReply() // ------------------------------------------------------------ the pull diff --git a/desktop/shell/shell/plugins/agents/Panel.qml b/desktop/shell/shell/plugins/agents/Panel.qml index 67b1a842..50ae3044 100644 --- a/desktop/shell/shell/plugins/agents/Panel.qml +++ b/desktop/shell/shell/plugins/agents/Panel.qml @@ -1565,7 +1565,7 @@ Panel { } } - KeyboardPanel { + LazyKeyboardPanel { id: panel anchorItem: button owner: root diff --git a/desktop/shell/shell/plugins/background/Background.qml b/desktop/shell/shell/plugins/background/Background.qml index 19765990..402844cd 100644 --- a/desktop/shell/shell/plugins/background/Background.qml +++ b/desktop/shell/shell/plugins/background/Background.qml @@ -593,7 +593,7 @@ Item { // under it while a video plays. A clear layer above the video and below // every window keeps the desktop's double-clicks working meanwhile. Variants { - model: Quickshell.screens + model: root.suspended ? Quickshell.screens : [] PanelWindow { required property var modelData diff --git a/desktop/shell/shell/plugins/bar/Bar.qml b/desktop/shell/shell/plugins/bar/Bar.qml index 5e2ecfef..de750d56 100644 --- a/desktop/shell/shell/plugins/bar/Bar.qml +++ b/desktop/shell/shell/plugins/bar/Bar.qml @@ -1694,7 +1694,7 @@ Item { } Variants { - model: Quickshell.screens + model: root.barDragSource || root.barPoof ? Quickshell.screens : [] delegate: Component { DragGhostPanel { @@ -1707,7 +1707,7 @@ Item { } Variants { - model: Quickshell.screens + model: root.barMoveActive ? Quickshell.screens : [] delegate: Component { BarMoveGhostPanel { @@ -1901,10 +1901,14 @@ Item { } } - PopupWindow { + OnDemandLoader { + id: tooltipLoader + requested: root.tooltipShown && root.tooltipTarget !== null && root.tooltipText !== "" && root.targetBelongsToWindow(root.tooltipTarget, barWindow) + sourceComponent: barWindow.tooltipComponent + } + property Component tooltipComponent: PopupWindow { id: tooltipWindow - - visible: root.tooltipShown && root.tooltipTarget !== null && root.tooltipText !== "" && root.targetBelongsToWindow(root.tooltipTarget, barWindow) + visible: tooltipLoader.requested color: "transparent" implicitWidth: Math.ceil(tooltipBubble.implicitWidth) implicitHeight: Math.ceil(tooltipBubble.implicitHeight) diff --git a/desktop/shell/shell/plugins/bar/widgets/Tray.qml b/desktop/shell/shell/plugins/bar/widgets/Tray.qml index c7ec6bef..1f49070c 100644 --- a/desktop/shell/shell/plugins/bar/widgets/Tray.qml +++ b/desktop/shell/shell/plugins/bar/widgets/Tray.qml @@ -107,7 +107,7 @@ BarWidget { // Flickable keeps its offset across a model swap whenever the new content // is still tall enough to hold it, so a menu dismissed while scrolled // would otherwise reopen part-way down with its first entries off screen. - trayMenuFlick.contentY = 0 + if (trayMenuPopupLoader.item) trayMenuPopupLoader.item.resetScroll() // Clear the reactive stack before tearing anything down, so no binding can // read a partially-destroyed opener while this runs. Then destroy deepest // first: an inner opener's menu entry is owned by its parent's children @@ -454,12 +454,13 @@ BarWidget { } } - PopupCard { + OnDemandLoader { id: managePopupLoader; requested: root.managePopupOpen; sourceComponent: root.managePopupComponent } + property Component managePopupComponent: PopupCard { id: managePopup anchorItem: root owner: root bar: root.bar - open: root.managePopupOpen + open: !!managePopupLoader.item && root.managePopupOpen contentWidth: managePopup.fittedContentWidth(Style.space(300)) contentHeight: managePopup.fittedContentHeight(manageColumn.implicitHeight) @@ -580,12 +581,14 @@ BarWidget { menu: root.activeTrayItem ? root.activeTrayItem.menu : null } - PopupCard { + OnDemandLoader { id: trayMenuPopupLoader; requested: root.trayMenuOpen; sourceComponent: root.trayMenuPopupComponent } + property Component trayMenuPopupComponent: PopupCard { id: trayMenuPopup + function resetScroll() { trayMenuFlick.contentY = 0 } anchorItem: root.activeTrayAnchor || root owner: root bar: root.bar - open: root.trayMenuOpen + open: !!trayMenuPopupLoader.item && root.trayMenuOpen // The card fades out over 140ms (visible stays true for that whole time -- // see PopupCard's own visible: open || card.opacity > 0), so resetting on // "open" would swap a live submenu for the root menu mid-fade: a visible diff --git a/desktop/shell/shell/plugins/clipboard/Clipboard.qml b/desktop/shell/shell/plugins/clipboard/Clipboard.qml index bb2b4c0f..d8649679 100644 --- a/desktop/shell/shell/plugins/clipboard/Clipboard.qml +++ b/desktop/shell/shell/plugins/clipboard/Clipboard.qml @@ -35,8 +35,8 @@ Item { property int contentMargin: Style.spacing.panelPadding property int headerHeight: Math.max(Style.space(34), Style.font.title + Style.spacing.controlPaddingY * 2) property int contentSpacing: Style.spacing.md - property int cardWidth: Math.min(Style.space(875), panel.width - Style.gapsOut * 2) - property int cardHeight: Math.min(Style.space(600), panel.height - Style.gapsOut * 2) + property int cardWidth: !panel ? 0 : Math.min(Style.space(875), panel.width - Style.gapsOut * 2) + property int cardHeight: !panel ? 0 : Math.min(Style.space(600), panel.height - Style.gapsOut * 2) property int rowHeight: Math.max(Style.space(50), Style.font.body + Style.font.caption + Style.spacing.rowPaddingX * 2) property int historyLimit: 500 @@ -319,9 +319,19 @@ Item { } } - OverlayWindow { + readonly property var panel: windowLoader.item + readonly property var card: panel ? panel.card : null + readonly property var resultList: panel ? panel.resultList : null + readonly property var keyCatcher: panel ? panel.keyCatcher : null + readonly property var clearConfirm: panel ? panel.clearConfirm : null + OnDemandLoader { id: windowLoader; requested: root.opened; sourceComponent: windowComponent } + property Component windowComponent: OverlayWindow { id: panel - shown: root.opened + property alias card: card + property alias resultList: resultList + property alias keyCatcher: keyCatcher + property alias clearConfirm: clearConfirm + shown: !!windowLoader.item && root.opened WlrLayershell.namespace: "omarchy-clipboard" Rectangle { diff --git a/desktop/shell/shell/plugins/dock/Dock.qml b/desktop/shell/shell/plugins/dock/Dock.qml index 4a955814..38a1da7b 100644 --- a/desktop/shell/shell/plugins/dock/Dock.qml +++ b/desktop/shell/shell/plugins/dock/Dock.qml @@ -2,6 +2,7 @@ import QtQuick import Quickshell import Quickshell.Hyprland import Quickshell.Io +import qs.Ui import qs.Commons import "DockModel.js" as DockModel @@ -221,7 +222,7 @@ Item { } function openApps() { - appGrid.open() + appGrid.load().open() } readonly property var pinnedKeys: root.pendingPins || DockModel.pinnedIds(root.dockConfig, root.defaultDockConfig) @@ -360,9 +361,9 @@ Item { // The layout commands call this after changing a workspace's mode. function refresh(): void { root.refresh() } - function apps(): void { appGrid.toggle() } - function closeApps(): void { if (appGrid.opened) appGrid.close() } - function openApps(): void { if (!appGrid.opened) appGrid.open() } + function apps(): void { appGrid.load().toggle() } + function closeApps(): void { if (appGrid.item && appGrid.item.opened) appGrid.item.close() } + function openApps(): void { if (!appGrid.item || !appGrid.item.opened) appGrid.load().open() } } // An app dragged out of the app grid: the grid holds the pointer and @@ -408,9 +409,8 @@ Item { } } - AppGrid { + OnDemandLoader { id: appGrid - appLibrary: root.appLibrary - dock: root + sourceComponent: AppGrid { appLibrary: root.appLibrary; dock: root } } } diff --git a/desktop/shell/shell/plugins/emojis/Emojis.qml b/desktop/shell/shell/plugins/emojis/Emojis.qml index dc8f0ef2..a27e67b8 100644 --- a/desktop/shell/shell/plugins/emojis/Emojis.qml +++ b/desktop/shell/shell/plugins/emojis/Emojis.qml @@ -36,8 +36,8 @@ Item { property int contentMargin: Style.spacing.panelPadding property int headerHeight: Math.max(Style.space(34), Style.font.title + Style.spacing.controlPaddingY * 2) property int contentSpacing: Style.spacing.md - property int cardWidth: Math.min(Style.space(400), panel.width - Style.gapsOut * 2) - property int cardHeight: Math.min(Style.space(500), panel.height - Style.gapsOut * 2) + property int cardWidth: !panel ? 0 : Math.min(Style.space(400), panel.width - Style.gapsOut * 2) + property int cardHeight: !panel ? 0 : Math.min(Style.space(500), panel.height - Style.gapsOut * 2) property int cellWidth: Math.max(Style.space(44), Style.font.display + Style.spacing.md) property int cellHeight: Math.max(Style.space(44), Style.font.display + Style.spacing.md) @@ -158,9 +158,15 @@ Item { path: root.omarchyPath + "/shell/plugins/emojis/emojis.json" onLoaded: root.loadEmojis(text()) } - OverlayWindow { + readonly property var panel: windowLoader.item + readonly property var keyCatcher: panel ? panel.keyCatcher : null + readonly property var resultGrid: panel ? panel.resultGrid : null + OnDemandLoader { id: windowLoader; requested: root.opened; sourceComponent: root.windowComponent } + property Component windowComponent: OverlayWindow { id: panel - shown: root.opened + property alias keyCatcher: keyCatcher + property alias resultGrid: resultGrid + shown: !!windowLoader.item && root.opened WlrLayershell.namespace: "omarchy-emojis" Rectangle { diff --git a/desktop/shell/shell/plugins/flash/Flash.qml b/desktop/shell/shell/plugins/flash/Flash.qml index 4e1610cc..52698952 100644 --- a/desktop/shell/shell/plugins/flash/Flash.qml +++ b/desktop/shell/shell/plugins/flash/Flash.qml @@ -14,10 +14,7 @@ Item { property bool opened: false function flash() { - flashAnimation.stop() - white.opacity = 0 - opened = true - flashAnimation.start() + flashWindow.load().play() } ShellIpc { @@ -26,8 +23,15 @@ Item { function ping(): string { return "ok" } } - OverlayWindow { + OnDemandLoader { id: flashWindow; sourceComponent: windowComponent } + property Component windowComponent: OverlayWindow { id: panel + function play() { + flashAnimation.stop() + white.opacity = 0 + root.opened = true + flashAnimation.start() + } shown: root.opened shownKeyboardFocus: WlrKeyboardFocus.None WlrLayershell.namespace: "omarchy-flash" @@ -40,13 +44,13 @@ Item { color: "white" opacity: 0 } - } - // Full white at once, then a gentle fade. - SequentialAnimation { - id: flashAnimation - PropertyAction { target: white; property: "opacity"; value: 0.95 } - NumberAnimation { target: white; property: "opacity"; to: 0; duration: 500; easing.type: Easing.InOutSine } - onFinished: root.opened = false + // Full white at once, then a gentle fade. + SequentialAnimation { + id: flashAnimation + PropertyAction { target: white; property: "opacity"; value: 0.95 } + NumberAnimation { target: white; property: "opacity"; to: 0; duration: 500; easing.type: Easing.InOutSine } + onFinished: root.opened = false + } } } diff --git a/desktop/shell/shell/plugins/image-picker/ImagePicker.qml b/desktop/shell/shell/plugins/image-picker/ImagePicker.qml index a77ad983..b2512791 100644 --- a/desktop/shell/shell/plugins/image-picker/ImagePicker.qml +++ b/desktop/shell/shell/plugins/image-picker/ImagePicker.qml @@ -61,19 +61,21 @@ Item { // Orchard: on a phone-wide screen the selected card takes what is left // after 16-point margins and a slim slice of each neighbour, so it shows // whole and the carousel still reads as one. - readonly property bool narrow: panel.width > 0 && panel.width < 600 + readonly property int windowWidth: panel ? panel.width : 0 + readonly property int windowHeight: panel ? panel.height : 0 + readonly property bool narrow: windowWidth > 0 && windowWidth < 600 readonly property int narrowMargin: 16 property int expandedWidth: narrow - ? Math.max(160, panel.width - 2 * narrowMargin - 2 * (sliceWidth + sliceSpacing)) - : Math.min(768, Math.max(320, Math.floor((panel.width - 32) * 0.60))) - property int expandedHeight: Math.min(475, Math.round(expandedWidth * 475 / 768), Math.max(200, panel.height - 64 - bottomChromeHeight)) + ? Math.max(160, windowWidth - 2 * narrowMargin - 2 * (sliceWidth + sliceSpacing)) + : Math.min(768, Math.max(320, Math.floor((windowWidth - 32) * 0.60))) + property int expandedHeight: Math.min(475, Math.round(expandedWidth * 475 / 768), Math.max(200, windowHeight - 64 - bottomChromeHeight)) property int sliceWidth: narrow ? 44 : Math.min(108, Math.max(72, Math.round(expandedWidth * 108 / 768))) property int sliceHeight: Math.min(432, Math.round(expandedHeight * 432 / 475)) property int sliceSpacing: -Math.round(sliceWidth * 0.28) property int skewOffset: 28 property int bottomChromeHeight: showLabels ? (filterable ? 104 : 74) : (filterable ? 60 : 30) // Render only what fits on this display, plus one prefetch slice per side. - readonly property int previewRadius: Math.max(1, Math.min(16, Math.ceil((panel.width - expandedWidth) / (2 * (sliceWidth + sliceSpacing))) + 1)) + readonly property int previewRadius: Math.max(1, Math.min(16, Math.ceil((windowWidth - expandedWidth) / (2 * (sliceWidth + sliceSpacing))) + 1)) onPreviewRadiusChanged: updateVisibleItems() onOpenedChanged: if (!opened) { layoutSettled = false; renderedFrames = 0; deleteConfirmOpen = false; pendingDeleteTheme = ""; deleteSelectionPath = ""; awaitingDeleteRefresh = false } @@ -90,7 +92,7 @@ Item { } function focusPicker() { - if (root.opened && root.imagesLoaded && root.layoutSettled) + if (carousel && root.opened && root.imagesLoaded && root.layoutSettled) carousel.forceActiveFocus() } @@ -105,7 +107,7 @@ Item { // complete frame instead of flashing its images in as each asynchronous // decode and layer upload finishes. function allPreviewsSettled() { - if (!opened || !imagesLoaded || layoutSettled || imageArray.length === 0 || imageCards.count === 0) return false + if (!opened || !imagesLoaded || layoutSettled || imageArray.length === 0 || !imageCards || imageCards.count === 0) return false for (var i = 0; i < imageCards.count; i++) { var item = imageCards.itemAt(i) if (!item || !item.previewSettled) return false @@ -367,6 +369,7 @@ Item { } function enableNeighborsWhenReady() { + if (!imageCards) return for (var i = 0; i < imageCards.count; i++) { var item = imageCards.itemAt(i) if (item && item.selected && item.previewReady) neighborImagesEnabled = true @@ -645,9 +648,17 @@ Item { onExited: root.releaseNextDoneFile() } - OverlayWindow { + readonly property var panel: windowLoader.item + readonly property var carousel: panel ? panel.carousel : null + readonly property var imageCards: panel ? panel.imageCards : null + readonly property var deleteConfirm: panel ? panel.deleteConfirm : null + OnDemandLoader { id: windowLoader; requested: root.opened; sourceComponent: root.windowComponent } + property Component windowComponent: OverlayWindow { id: panel - shown: root.opened + property alias carousel: carousel + property alias imageCards: imageCards + property alias deleteConfirm: deleteConfirm + shown: !!windowLoader.item && root.opened shownKeyboardFocus: root.imagesLoaded ? WlrKeyboardFocus.Exclusive : WlrKeyboardFocus.None WlrLayershell.namespace: "omarchy-image-selector" diff --git a/desktop/shell/shell/plugins/lock/Service.qml b/desktop/shell/shell/plugins/lock/Service.qml index 5828d9f9..7b371315 100644 --- a/desktop/shell/shell/plugins/lock/Service.qml +++ b/desktop/shell/shell/plugins/lock/Service.qml @@ -1,4 +1,5 @@ import QtQuick +import qs.Ui import Quickshell import Quickshell.Io import Quickshell.Services.Pam @@ -573,7 +574,8 @@ Item { } } - PanelWindow { + OnDemandLoader { id: windowLoader; requested: root.previewVisible; sourceComponent: windowComponent } + property Component windowComponent: PanelWindow { id: previewWindow // Right-to-left languages read this window mirrored. Binding { target: previewWindow.contentItem; property: "LayoutMirroring.enabled"; value: Commons.I18n.rightToLeft } diff --git a/desktop/shell/shell/plugins/menu/Menu.qml b/desktop/shell/shell/plugins/menu/Menu.qml index 3efa2138..95ca6450 100644 --- a/desktop/shell/shell/plugins/menu/Menu.qml +++ b/desktop/shell/shell/plugins/menu/Menu.qml @@ -90,7 +90,7 @@ Item { property string activeMenu: "root" property string filterText: "" // Resets of filterText reach the search line; its edits come back through setFilter. - onFilterTextChanged: if (filterInput.text !== filterText) filterInput.text = filterText + onFilterTextChanged: if (filterInput && filterInput.text !== filterText) filterInput.text = filterText property int selectedIndex: 0 property bool cursorActive: false // Rows with a `alt:` stand-in show and run it while this holds. @@ -137,9 +137,9 @@ Item { property int dividerHeight: Style.space(17) property bool searchDivider: false property int layoutSerial: 0 - property int cardWidth: Math.min(root.dmenuActive ? Style.space(root.dmenuWidth) : ((root.activeMenu === "trigger.capture.screenrecord" || root.activeMenu === "appearance.font" || root.activeMenu === "update.kernel") ? Style.space(520) : Style.space(300)), panel.width - Style.gapsOut * 2) + property int cardWidth: !panel ? 0 : Math.min(root.dmenuActive ? Style.space(root.dmenuWidth) : ((root.activeMenu === "trigger.capture.screenrecord" || root.activeMenu === "appearance.font" || root.activeMenu === "update.kernel") ? Style.space(520) : Style.space(300)), panel.width - Style.gapsOut * 2) property int visibleRowsHeight: root.dmenuActive ? dmenuRowListHeight(layoutSerial, displayModel.count, filterText) : rowListHeight(layoutSerial, displayModel.count, filterText, searchDivider) - property int cardHeight: root.dmenuActive + property int cardHeight: !panel ? 0 : root.dmenuActive ? Math.min(contentMargin * 2 + headerHeight + (mode === "input" ? 0 : contentSpacing + visibleRowsHeight), panel.usableHeight - Style.gapsOut * 2) : Math.min(contentMargin * 2 + headerHeight + contentSpacing + visibleRowsHeight, panel.usableHeight - Style.gapsOut * 2) @@ -184,6 +184,7 @@ Item { // Uses panel.cardTop rather than effectiveCardTop: the centered top is // derived from the card height, which this value feeds. function availableRowsHeight() { + if (!panel) return 0 var top = panel.cardTop >= 0 ? panel.cardTop : Style.gapsOut var available = panel.usableHeight - top - Style.gapsOut - root.contentMargin * 2 - root.headerHeight - root.contentSpacing // The starting menu sets the ceiling along with the offset: drilling into @@ -791,7 +792,7 @@ Item { // the neighbor entirely and losing the fold affordance. Keep the next // hidden row peeking past the cursor in the direction of travel. function revealCursor() { - if (displayModel.count === 0) return + if (!resultList || displayModel.count === 0) return resultList.positionViewAtIndex(root.selectedIndex, ListView.Contain) var item = resultList.itemAtIndex(root.selectedIndex) @@ -1301,9 +1302,19 @@ Item { if (root.guardsPending) Qt.callLater(function() { root.evaluateGuards() }) } } - OverlayWindow { + readonly property var panel: windowLoader.item + readonly property var filterInput: panel ? panel.filterInput : null + readonly property var resultList: panel ? panel.resultList : null + readonly property var card: panel ? panel.card : null + readonly property var deleteConfirm: panel ? panel.deleteConfirm : null + OnDemandLoader { id: windowLoader; requested: root.opened; sourceComponent: windowComponent } + property Component windowComponent: OverlayWindow { id: panel - shown: root.opened && root.rowsLoaded + property alias filterInput: filterInput + property alias resultList: resultList + property alias card: card + property alias deleteConfirm: deleteConfirm + shown: !!windowLoader.item && root.opened && root.rowsLoaded WlrLayershell.namespace: "omarchy-menu" // The card opens centered exactly as always. The first search keystroke diff --git a/desktop/shell/shell/plugins/notifications/Service.qml b/desktop/shell/shell/plugins/notifications/Service.qml index e26b28a0..35f2ee3b 100644 --- a/desktop/shell/shell/plugins/notifications/Service.qml +++ b/desktop/shell/shell/plugins/notifications/Service.qml @@ -260,10 +260,12 @@ Item { property int refsRevision: 0 property int keySeed: 0 + property bool bannerRequested: false ListModel { id: toasts onCountChanged: { - if (count === 0) service.deckDisplayName = "" + if (count > 0) service.bannerRequested = true + else service.deckDisplayName = "" if (service.keyboardMode) Qt.callLater(function() { service.keepSelection(0) }) } } @@ -1798,7 +1800,7 @@ Item { // layout's viewport), except where it steps aside for a fullscreen window. Variants { id: surfaceVariants - model: Quickshell.screens + model: service.bannerRequested ? Quickshell.screens : [] PanelWindow { id: surface diff --git a/desktop/shell/shell/plugins/osd/Osd.qml b/desktop/shell/shell/plugins/osd/Osd.qml index 68e11f7b..2d05fb15 100644 --- a/desktop/shell/shell/plugins/osd/Osd.qml +++ b/desktop/shell/shell/plugins/osd/Osd.qml @@ -19,38 +19,6 @@ Item { property bool hasProgress: true property int duration: 1200 - readonly property bool mediaOsd: iconKey.indexOf("media") === 0 || iconKey.indexOf("player") === 0 - - // The card is built out of measured columns instead of fixed widths, so it - // keeps exactly `pad` between border and content on every side whatever - // glyph or message it carries. Messages grow with their text up to - // `maxMessageWidth` and elide beyond it. - readonly property int pad: Style.space(16) - readonly property int gap: Style.space(16) - // A glyph next to a message reads airier than it measures: the icon outline - // and the letterforms both fall away from their ink extremes, so the space - // between them opens up well past the nominal gap. Text takes two thirds of - // it; the progress bar's hard edge keeps the full gap. - readonly property int messageGap: Math.round(root.gap * 2 / 3) - readonly property int barWidth: Style.space(142) - readonly property int maxMessageWidth: root.mediaOsd ? Style.space(325) : Style.space(190) - - // Nerd Font glyphs draw well outside their monospace cell, so the icon - // column is measured by ink rather than by advance width. Progress OSDs pin - // it to the widest glyph the model can return, so the bar doesn't shift when - // volume crosses an icon threshold. - readonly property int iconInkWidth: Math.ceil(iconMetrics.tightBoundingRect.width) - readonly property int iconWidth: root.hasProgress - ? Math.max(root.iconInkWidth, Math.ceil(widestIconMetrics.tightBoundingRect.width)) - : root.iconInkWidth - // Same idea for the readout: it is as wide as the longest percentage so the - // digits don't jitter between 9% and 100%. - readonly property int valueWidth: Math.ceil(Math.max(valueMetrics.advanceWidth, messageMetrics.advanceWidth)) - readonly property int messageWidth: Math.min(Math.ceil(messageMetrics.advanceWidth), root.maxMessageWidth) - readonly property int contentWidth: root.hasProgress - ? root.iconWidth + root.gap + root.barWidth + root.gap + root.valueWidth - : (root.message === "" ? root.iconWidth : root.iconWidth + root.messageGap + root.messageWidth) - function iconFor(name, percent) { return OsdModel.iconFor(name, percent) } @@ -86,33 +54,6 @@ Item { onTriggered: root.opened = false } - TextMetrics { - id: messageMetrics - font.family: Style.font.family - font.bold: true - font.pixelSize: Style.font.title - text: root.message - } - - TextMetrics { - id: valueMetrics - font: messageMetrics.font - text: Commons.I18n.formatNumber(100) + "%" - } - - TextMetrics { - id: iconMetrics - font.family: Style.font.family - font.pixelSize: Style.font.displayLarge - text: root.icon - } - - TextMetrics { - id: widestIconMetrics - font: iconMetrics.font - text: OsdModel.widestIcon - } - ShellIpc { target: "osd" function show(payloadJson: string): string { @@ -127,19 +68,79 @@ Item { function ping(): string { return "ok" } } - OverlayWindow { + OnDemandLoader { id: windowLoader; requested: root.opened; sourceComponent: windowComponent } + property Component windowComponent: OverlayWindow { id: panel - shown: root.opened + shown: !!windowLoader.item && root.opened shownKeyboardFocus: WlrKeyboardFocus.None WlrLayershell.namespace: "omarchy-osd" // Visual-only surface: keep the layer-shell input region empty so the OSD // never blocks clicks to the desktop below it. mask: Region {} + readonly property bool mediaOsd: root.iconKey.indexOf("media") === 0 || root.iconKey.indexOf("player") === 0 + + // The card is built out of measured columns instead of fixed widths, so it + // keeps exactly `pad` between border and content on every side whatever + // glyph or message it carries. Messages grow with their text up to + // `maxMessageWidth` and elide beyond it. + readonly property int pad: Style.space(16) + readonly property int gap: Style.space(16) + // A glyph next to a message reads airier than it measures: the icon outline + // and the letterforms both fall away from their ink extremes, so the space + // between them opens up well past the nominal gap. Text takes two thirds of + // it; the progress bar's hard edge keeps the full gap. + readonly property int messageGap: Math.round(panel.gap * 2 / 3) + readonly property int barWidth: Style.space(142) + readonly property int maxMessageWidth: panel.mediaOsd ? Style.space(325) : Style.space(190) + + // Nerd Font glyphs draw well outside their monospace cell, so the icon + // column is measured by ink rather than by advance width. Progress OSDs pin + // it to the widest glyph the model can return, so the bar doesn't shift when + // volume crosses an icon threshold. + readonly property int iconInkWidth: Math.ceil(iconMetrics.tightBoundingRect.width) + readonly property int iconWidth: root.hasProgress + ? Math.max(panel.iconInkWidth, Math.ceil(widestIconMetrics.tightBoundingRect.width)) + : panel.iconInkWidth + // Same idea for the readout: it is as wide as the longest percentage so the + // digits don't jitter between 9% and 100%. + readonly property int valueWidth: Math.ceil(Math.max(valueMetrics.advanceWidth, messageMetrics.advanceWidth)) + readonly property int messageWidth: Math.min(Math.ceil(messageMetrics.advanceWidth), panel.maxMessageWidth) + readonly property int contentWidth: root.hasProgress + ? panel.iconWidth + panel.gap + panel.barWidth + panel.gap + panel.valueWidth + : (root.message === "" ? panel.iconWidth : panel.iconWidth + panel.messageGap + panel.messageWidth) + + TextMetrics { + id: messageMetrics + font.family: Style.font.family + font.bold: true + font.pixelSize: Style.font.title + text: root.message + } + + TextMetrics { + id: valueMetrics + font: messageMetrics.font + text: Commons.I18n.formatNumber(100) + "%" + } + + TextMetrics { + id: iconMetrics + font.family: Style.font.family + font.pixelSize: Style.font.displayLarge + text: root.icon + } + + TextMetrics { + id: widestIconMetrics + font: iconMetrics.font + text: OsdModel.widestIcon + } + BorderSurface { id: card - width: card.borderLeft + root.pad + root.contentWidth + root.pad + card.borderRight - height: card.borderTop + root.pad + Style.font.displayLarge + root.pad + card.borderBottom + width: card.borderLeft + panel.pad + panel.contentWidth + panel.pad + card.borderRight + height: card.borderTop + panel.pad + Style.font.displayLarge + panel.pad + card.borderBottom anchors.horizontalCenter: parent.horizontalCenter anchors.bottom: parent.bottom anchors.bottomMargin: Style.space(67) @@ -150,19 +151,19 @@ Item { Row { anchors.fill: parent - anchors.topMargin: card.borderTop + root.pad - anchors.rightMargin: card.borderRight + root.pad - anchors.bottomMargin: card.borderBottom + root.pad - anchors.leftMargin: card.borderLeft + root.pad - spacing: root.hasProgress ? root.gap : root.messageGap + anchors.topMargin: card.borderTop + panel.pad + anchors.rightMargin: card.borderRight + panel.pad + anchors.bottomMargin: card.borderBottom + panel.pad + anchors.leftMargin: card.borderLeft + panel.pad + spacing: root.hasProgress ? panel.gap : panel.messageGap Item { - width: root.iconWidth + width: panel.iconWidth height: parent.height Text { textFormat: Text.PlainText // Sit the glyph's ink flush in the column, centered when the // column is wider than this particular glyph. - x: Math.round((root.iconWidth - root.iconInkWidth) / 2 - iconMetrics.tightBoundingRect.x) + x: Math.round((panel.iconWidth - panel.iconInkWidth) / 2 - iconMetrics.tightBoundingRect.x) anchors.verticalCenter: parent.verticalCenter text: root.icon font: iconMetrics.font @@ -171,7 +172,7 @@ Item { } Rectangle { visible: root.hasProgress - width: root.barWidth + width: panel.barWidth height: Math.max(Style.space(6), Style.spacing.sm) anchors.verticalCenter: parent.verticalCenter color: Util.alpha(Commons.Color.popups.text, 0.45) @@ -191,7 +192,7 @@ Item { Text { textFormat: Text.PlainText visible: root.message !== "" - width: root.hasProgress ? root.valueWidth : root.messageWidth + width: root.hasProgress ? panel.valueWidth : panel.messageWidth // The readout hugs the card edge so a short percentage doesn't leave // a hole in the padding; the slack lands in the gap after the bar. horizontalAlignment: root.hasProgress ? Text.AlignRight : Text.AlignLeft diff --git a/desktop/shell/shell/plugins/panels/audio/Panel.qml b/desktop/shell/shell/plugins/panels/audio/Panel.qml index 30582cde..0430053a 100644 --- a/desktop/shell/shell/plugins/panels/audio/Panel.qml +++ b/desktop/shell/shell/plugins/panels/audio/Panel.qml @@ -756,7 +756,7 @@ Panel { // The content, for a host that shows it as a page (the control center). readonly property Component pageContent: panel.content - KeyboardPanel { + LazyKeyboardPanel { id: panel anchorItem: button owner: root diff --git a/desktop/shell/shell/plugins/panels/bluetooth/Panel.qml b/desktop/shell/shell/plugins/panels/bluetooth/Panel.qml index 0e5b9c06..48a1fe22 100644 --- a/desktop/shell/shell/plugins/panels/bluetooth/Panel.qml +++ b/desktop/shell/shell/plugins/panels/bluetooth/Panel.qml @@ -705,7 +705,7 @@ Panel { // The content, for a host that shows it as a page (the control center). readonly property Component pageContent: panel.content - KeyboardPanel { + LazyKeyboardPanel { id: panel anchorItem: button owner: root diff --git a/desktop/shell/shell/plugins/panels/clock/BarWidget.qml b/desktop/shell/shell/plugins/panels/clock/BarWidget.qml index c2069650..68941f23 100644 --- a/desktop/shell/shell/plugins/panels/clock/BarWidget.qml +++ b/desktop/shell/shell/plugins/panels/clock/BarWidget.qml @@ -74,6 +74,7 @@ BarWidget { readonly property bool opened: panelLoader.item ? panelLoader.item.opened === true : false function open() { + panelLoader.active = true if (panelLoader.item) panelLoader.item.open() } @@ -82,10 +83,12 @@ BarWidget { } function togglePanel() { + panelLoader.active = true if (panelLoader.item) panelLoader.item.toggle() } function toggleWeekStart() { + panelLoader.active = true if (panelLoader.item) panelLoader.item.toggleWeekStart() } @@ -129,7 +132,7 @@ BarWidget { Loader { id: panelLoader - active: true + active: false source: Qt.resolvedUrl("Panel.qml") visible: false onLoaded: { diff --git a/desktop/shell/shell/plugins/panels/dropbox/Panel.qml b/desktop/shell/shell/plugins/panels/dropbox/Panel.qml index e861c646..e054c839 100644 --- a/desktop/shell/shell/plugins/panels/dropbox/Panel.qml +++ b/desktop/shell/shell/plugins/panels/dropbox/Panel.qml @@ -199,7 +199,7 @@ Panel { } } - KeyboardPanel { + LazyKeyboardPanel { id: panel anchorItem: button owner: root diff --git a/desktop/shell/shell/plugins/panels/elsewhen/Panel.qml b/desktop/shell/shell/plugins/panels/elsewhen/Panel.qml index 44584048..5245f941 100644 --- a/desktop/shell/shell/plugins/panels/elsewhen/Panel.qml +++ b/desktop/shell/shell/plugins/panels/elsewhen/Panel.qml @@ -993,7 +993,7 @@ Panel { } } - KeyboardPanel { + LazyKeyboardPanel { id: panel anchorItem: button owner: root diff --git a/desktop/shell/shell/plugins/panels/monitor/Panel.qml b/desktop/shell/shell/plugins/panels/monitor/Panel.qml index 9922e2b7..3abc3db4 100644 --- a/desktop/shell/shell/plugins/panels/monitor/Panel.qml +++ b/desktop/shell/shell/plugins/panels/monitor/Panel.qml @@ -857,7 +857,7 @@ Panel { // The content, for a host that shows it as a page (the control center). readonly property Component pageContent: panel.content - KeyboardPanel { + LazyKeyboardPanel { id: panel anchorItem: button owner: root diff --git a/desktop/shell/shell/plugins/panels/network/Panel.qml b/desktop/shell/shell/plugins/panels/network/Panel.qml index e043de0a..c5baedd9 100644 --- a/desktop/shell/shell/plugins/panels/network/Panel.qml +++ b/desktop/shell/shell/plugins/panels/network/Panel.qml @@ -1123,7 +1123,7 @@ Panel { // The content, for a host that shows it as a page (the control center). readonly property Component pageContent: panel.content - KeyboardPanel { + LazyKeyboardPanel { id: panel anchorItem: button owner: root diff --git a/desktop/shell/shell/plugins/panels/power/Panel.qml b/desktop/shell/shell/plugins/panels/power/Panel.qml index c41758f0..7a9210e9 100644 --- a/desktop/shell/shell/plugins/panels/power/Panel.qml +++ b/desktop/shell/shell/plugins/panels/power/Panel.qml @@ -312,7 +312,7 @@ Panel { // The content, for a host that shows it as a page (the control center). readonly property Component pageContent: panel.content - KeyboardPanel { + LazyKeyboardPanel { id: panel anchorItem: button owner: root diff --git a/desktop/shell/shell/plugins/panels/tailscale/Panel.qml b/desktop/shell/shell/plugins/panels/tailscale/Panel.qml index 40f46b65..9ba5fb50 100644 --- a/desktop/shell/shell/plugins/panels/tailscale/Panel.qml +++ b/desktop/shell/shell/plugins/panels/tailscale/Panel.qml @@ -554,7 +554,7 @@ Panel { } } - KeyboardPanel { + LazyKeyboardPanel { id: panel anchorItem: button owner: root diff --git a/desktop/shell/shell/plugins/panels/weather/Panel.qml b/desktop/shell/shell/plugins/panels/weather/Panel.qml index f17ce8d9..00505169 100644 --- a/desktop/shell/shell/plugins/panels/weather/Panel.qml +++ b/desktop/shell/shell/plugins/panels/weather/Panel.qml @@ -531,7 +531,7 @@ Panel { function edit(): void { root.openFromHotkey(); root.startEditingLocation() } } - KeyboardPanel { + LazyKeyboardPanel { id: panel anchorItem: root.anchorItem owner: root.barIdentity diff --git a/desktop/shell/shell/plugins/polkit/PolkitAgent.qml b/desktop/shell/shell/plugins/polkit/PolkitAgent.qml index a2d662ba..68fc9f06 100644 --- a/desktop/shell/shell/plugins/polkit/PolkitAgent.qml +++ b/desktop/shell/shell/plugins/polkit/PolkitAgent.qml @@ -46,10 +46,10 @@ Item { // a password — including immediately when the lid is shut and the clamshell // gate skips pam_fprintd — we switch to the password field instead. readonly property bool fingerprintMode: fingerprintConfigured && !laptopClosed && dialogVisible && !responseRequired && !submitted && !errorFlash - readonly property int cardHeight: panel.height > 0 ? Math.min(fieldHeight + contentMargin * 2, panel.height - Style.gapsOut * 2) : fieldHeight + contentMargin * 2 + readonly property int cardHeight: !panel ? 0 : panel.height > 0 ? Math.min(fieldHeight + contentMargin * 2, panel.height - Style.gapsOut * 2) : fieldHeight + contentMargin * 2 // Password mode is a wide field; fingerprint mode collapses to a square that // just frames the centered sensor icon. - readonly property int cardWidth: fingerprintMode ? cardHeight : Math.min(Style.space(312), Math.max(Style.space(260), panel.width - Style.gapsOut * 2)) + readonly property int cardWidth: !panel ? 0 : fingerprintMode ? cardHeight : Math.min(Style.space(312), Math.max(Style.space(260), panel.width - Style.gapsOut * 2)) function authorizationLabel(message) { return message ? PolkitModel.authorizationLabel(message, I18n.t) : I18n.t("polkit.authenticationNeeded") @@ -72,7 +72,7 @@ Item { failed = false errorFlash = false submitted = false - passwordInput.text = "" + if (passwordInput) passwordInput.text = "" } function syncFromFlow() { @@ -90,10 +90,11 @@ Item { } function beginFlow() { + windowLoader.load() closeTimer.stop() closing = false submitted = false - passwordInput.text = "" + if (passwordInput) passwordInput.text = "" refreshLidState() syncFromFlow() Qt.callLater(refocus) @@ -113,13 +114,13 @@ Item { submitted = true errorFlash = false flow.submit(passwordInput.text) - passwordInput.text = "" + if (passwordInput) passwordInput.text = "" keyCatcher.forceActiveFocus() } function cancelRequest() { var flow = polkitAgent.flow - passwordInput.text = "" + if (passwordInput) passwordInput.text = "" submitted = false closing = true closeTimer.restart() @@ -129,7 +130,7 @@ Item { function triggerFailureFeedback() { submitted = false errorFlash = true - passwordInput.text = "" + if (passwordInput) passwordInput.text = "" errorTimer.restart() shakeAnimation.restart() Qt.callLater(refocus) @@ -194,7 +195,7 @@ Item { function onIsResponseRequiredChanged() { root.syncFromFlow() - if (!polkitAgent.flow || !polkitAgent.flow.isResponseRequired) passwordInput.text = "" + if (passwordInput && (!polkitAgent.flow || !polkitAgent.flow.isResponseRequired)) passwordInput.text = "" Qt.callLater(root.refocus) } @@ -219,8 +220,14 @@ Item { } } - PanelWindow { + readonly property var panel: windowLoader.item + readonly property var keyCatcher: panel ? panel.keyCatcher : null + readonly property var passwordInput: panel ? panel.passwordInput : null + OnDemandLoader { id: windowLoader; requested: root.dialogVisible; sourceComponent: windowComponent } + property Component windowComponent: PanelWindow { id: panel + property alias keyCatcher: keyCatcher + property alias passwordInput: passwordInput // Right-to-left languages read this window mirrored. Binding { target: panel.contentItem; property: "LayoutMirroring.enabled"; value: Commons.I18n.rightToLeft } Binding { target: panel.contentItem; property: "LayoutMirroring.childrenInherit"; value: true } diff --git a/desktop/shell/shell/plugins/reminders/ReminderFlow.qml b/desktop/shell/shell/plugins/reminders/ReminderFlow.qml index e99650dc..c5446181 100644 --- a/desktop/shell/shell/plugins/reminders/ReminderFlow.qml +++ b/desktop/shell/shell/plugins/reminders/ReminderFlow.qml @@ -27,8 +27,8 @@ Item { readonly property int cornerRadius: Style.cornerRadius property int contentMargin: Style.spacing.panelPadding property int headerHeight: Math.max(Style.space(34), Style.font.title + Style.spacing.controlPaddingY * 2) - property int cardWidth: Math.min(Style.space(300), panel.width - Style.gapsOut * 2) - property int cardHeight: Math.min(contentMargin * 2 + headerHeight, panel.height - Style.gapsOut * 2) + property int cardWidth: !panel ? 0 : Math.min(Style.space(300), panel.width - Style.gapsOut * 2) + property int cardHeight: !panel ? 0 : Math.min(contentMargin * 2 + headerHeight, panel.height - Style.gapsOut * 2) readonly property string promptText: root.step === "message" ? I18n.t("reminders.messagePrompt") : I18n.t("reminders.minutesPrompt") function open(payloadJson) { @@ -93,9 +93,13 @@ Item { } } - OverlayWindow { + readonly property var panel: windowLoader.item + readonly property var keyCatcher: panel ? panel.keyCatcher : null + OnDemandLoader { id: windowLoader; requested: root.opened; sourceComponent: root.windowComponent } + property Component windowComponent: OverlayWindow { id: panel - shown: root.opened + property alias keyCatcher: keyCatcher + shown: !!windowLoader.item && root.opened WlrLayershell.namespace: "omarchy-reminders" Rectangle { diff --git a/desktop/shell/shell/plugins/services/media/BarWidget.qml b/desktop/shell/shell/plugins/services/media/BarWidget.qml index b4c9a7d3..ea4c8104 100644 --- a/desktop/shell/shell/plugins/services/media/BarWidget.qml +++ b/desktop/shell/shell/plugins/services/media/BarWidget.qml @@ -107,12 +107,13 @@ BarWidget { onExited: if (root.bar) root.bar.hideTooltip(root) } - PopupCard { + OnDemandLoader { id: popupLoader; requested: root.popupOpen; sourceComponent: root.popupComponent } + property Component popupComponent: PopupCard { id: popup anchorItem: root bar: root.bar owner: root - open: root.popupOpen + open: !!popupLoader.item && root.popupOpen contentWidth: popup.fittedContentWidth(Style.space(320)) contentHeight: popup.fittedContentHeight(column.implicitHeight) @@ -133,7 +134,7 @@ BarWidget { borderSpec: Border.controlSpec("normal", root.bar.foreground, Commons.Color.accent) // Decode the art at the size it is drawn, not the size the player - // serves it at. The popup is built on every monitor at startup. + // serves it at. SizedImage { anchors.fill: parent anchors.margins: Style.space(2) diff --git a/desktop/shell/shell/services/BackgroundIntro.qml b/desktop/shell/shell/services/BackgroundIntro.qml index 62f667fb..f7919617 100644 --- a/desktop/shell/shell/services/BackgroundIntro.qml +++ b/desktop/shell/shell/services/BackgroundIntro.qml @@ -294,7 +294,7 @@ Item { // retain the current desktop and never map this startup cover. Variants { id: startupCovers - model: Quickshell.screens + model: root.startupPending ? Quickshell.screens : [] PanelWindow { required property var modelData @@ -327,7 +327,7 @@ Item { Variants { id: covers - model: Quickshell.screens + model: root.cover || root.themeBackground !== "" ? Quickshell.screens : [] PanelWindow { id: panel diff --git a/desktop/shell/shell/settings/Settings.qml b/desktop/shell/shell/settings/Settings.qml index ca9e99bb..94b0e9a5 100644 --- a/desktop/shell/shell/settings/Settings.qml +++ b/desktop/shell/shell/settings/Settings.qml @@ -105,7 +105,7 @@ Item { // shell restarts. property bool bluetoothScan: false property bool owesDiscoveryStop: false - readonly property var adapter: Bluetooth.defaultAdapter + readonly property var adapter: bluetoothScan || owesDiscoveryStop ? Bluetooth.defaultAdapter : null Timer { interval: 1000 repeat: true diff --git a/desktop/shell/shell/shell.qml b/desktop/shell/shell/shell.qml index 4f4de6d7..92b97170 100644 --- a/desktop/shell/shell/shell.qml +++ b/desktop/shell/shell/shell.qml @@ -11,6 +11,7 @@ import Quickshell.Io import qs.Commons import qs.Commons as Commons +import qs.Ui import "plugins/bar" import "launcher" @@ -34,26 +35,74 @@ ShellRoot { // Orchard: the launcher answers the stock Apps menu action // (`omarchy-shell omarchy.dock apps`), so Home, Super, Super+Space and the // bar's logo open it, without mapping Hyprland's dock. - Launcher { id: appGrid; shell: shell; appLibrary: shell.appLibrary } - // Orchard: the control center (`omarchy-shell omarchy.controlcenter toggle`). - ControlCenter { id: controlCenter; shell: shell } - NotificationCenter { id: notificationCenter; shell: shell } - Settings { id: settings; shell: shell } - // The bar pulls it down from the top edge's right third (Bar.qml). - readonly property var controlCenter: controlCenter - readonly property var notificationCenter: notificationCenter - readonly property var settings: settings - readonly property var launcher: appGrid + OnDemandLoader { + id: appGrid + sourceComponent: Launcher { shell: shell; appLibrary: shell.appLibrary } + } + readonly property var launcher: appGrid.item ShellIpc { target: "omarchy.dock" - function apps(): void { appGrid.toggle() } - // For callers that must not toggle: the overview puts the drawer away - // when it opens. - function closeApps(): void { if (appGrid.opened) appGrid.close() } - // The long bottom swipe (labwc's bottomSwipeFarCommand) opens it, and - // never closes it. - function openApps(): void { if (!appGrid.opened) appGrid.open() } + function apps(): void { appGrid.load().toggle() } + function closeApps(): void { if (shell.launcher && shell.launcher.opened) shell.launcher.close() } + function openApps(): void { if (!shell.launcher || !shell.launcher.opened) appGrid.load().open() } + } + + component CenterLoader: OnDemandLoader { + id: center + required property string noteName + readonly property bool opened: !!item && item.opened + readonly property bool mapped: !!item && item.mapped + function open() { if (!opened) load().open() } + function close() { if (item) item.close() } + function toggle() { load().toggle() } + function togglePopup() { load().togglePopup() } + function beginPull() { load().beginPull() } + function pullTo(distance) { if (item) item.pullTo(distance) } + function endPull(velocity) { if (item) item.endPull(velocity) } + + // Clear a stale Home-button marker on shell restart. Serialize writes + // so an open arriving during that initial removal wins. + readonly property string openNote: (Quickshell.env("XDG_RUNTIME_DIR") || "/tmp") + "/" + noteName + property bool noteWritten: true + function writeOpenNote() { + if (noteWriter.running || noteWritten === opened) return + noteWriter.writing = opened + noteWriter.command = opened ? ["touch", openNote] : ["rm", "-f", openNote] + noteWriter.running = true + } + Process { + id: noteWriter + property bool writing: false + onExited: { center.noteWritten = writing; center.writeOpenNote() } + } + Component.onCompleted: writeOpenNote() + onOpenedChanged: writeOpenNote() + } + + readonly property CenterLoader controlCenter: CenterLoader { + noteName: "omarchy-control-center-open" + readonly property bool popupStyle: !!item && item.popupStyle + sourceComponent: ControlCenter { shell: shell } + } + ShellIpc { + target: "omarchy.controlcenter" + function toggle(): void { shell.controlCenter.toggle() } + function open(): void { shell.controlCenter.open() } + function close(): void { shell.controlCenter.close() } + function page(module: string): void { shell.controlCenter.load().openPage(module) } + } + readonly property CenterLoader notificationCenter: CenterLoader { + noteName: "omarchy-notification-center-open" + sourceComponent: NotificationCenter { shell: shell } } + ShellIpc { + target: "omarchy.notificationcenter" + function toggle(): void { shell.notificationCenter.toggle() } + function open(): void { shell.notificationCenter.open() } + function close(): void { shell.notificationCenter.close() } + } + + readonly property Settings settings: Settings { shell: shell } // labwc's long bottom swipe (bottomSwipeFarSocket): lines "p 0.42" while // the finger moves past where the overview turns back, then "end 1" (let @@ -65,8 +114,8 @@ ShellRoot { parser: SplitParser { onRead: function(line) { var parts = String(line).trim().split(" ") - if (parts[0] === "p") appGrid.follow(Number(parts[1]) || 0) - else if (parts[0] === "end") appGrid.followEnd(parts[1] === "1") + if (parts[0] === "p" && (appGrid.item || Number(parts[1]) > 0)) appGrid.load().follow(Number(parts[1]) || 0) + else if (parts[0] === "end" && appGrid.item) appGrid.item.followEnd(parts[1] === "1") } } } From 66645067455f987bd8c761f72f2568ccc86a593e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Berkay=20K=C3=B6sebay?= Date: Tue, 1 Dec 2026 18:02:06 +0100 Subject: [PATCH 03/17] shell: decode wallpapers and previews at display resolution MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Use the same physical size for the synchronous lock image and its cache warmer. Keep the desktop still visible while its rotated size decodes, and decode the launcher backdrop off the UI thread. Assisted-by: LLM Signed-off-by: Berkay Kösebay --- desktop/shell/shell/Ui/BackgroundMedia.qml | 10 ++++++---- desktop/shell/shell/launcher/Launcher.qml | 3 ++- .../shell/notificationcenter/NotificationCenter.qml | 4 ++-- .../shell/shell/plugins/background/Background.qml | 13 ++----------- desktop/shell/shell/plugins/lock/LockView.qml | 3 ++- desktop/shell/shell/plugins/lock/Service.qml | 6 +++--- desktop/shell/shell/settings/BackgroundPage.qml | 4 ++-- desktop/shell/shell/settings/IconsPage.qml | 4 ++-- desktop/shell/shell/settings/ThemePage.qml | 4 ++-- 9 files changed, 23 insertions(+), 28 deletions(-) diff --git a/desktop/shell/shell/Ui/BackgroundMedia.qml b/desktop/shell/shell/Ui/BackgroundMedia.qml index fd818598..9efdea40 100644 --- a/desktop/shell/shell/Ui/BackgroundMedia.qml +++ b/desktop/shell/shell/Ui/BackgroundMedia.qml @@ -10,6 +10,7 @@ Item { property int version: 0 // Unversioned images cache by path. A caller whose version changes with every // new file, as the lock's does, may cache too: the version is in the URL. + property bool asynchronous: true property bool cached: version === 0 // A caller that knows the size its screen needs, in physical pixels, sets // constrainDecode and decodeSize. The image then waits for that size rather @@ -38,12 +39,13 @@ Item { Image { readonly property bool ready: status === Image.Ready readonly property bool failed: status === Image.Error - source: !root.constrainDecode || root.decodeSize.width > 0 ? root.imageUrl : "" + source: sourceSize.width > 0 && sourceSize.height > 0 ? root.imageUrl : "" fillMode: Image.PreserveAspectCrop - asynchronous: true + asynchronous: root.asynchronous + retainWhileLoading: root.asynchronous cache: root.cached - sourceSize.width: root.constrainDecode ? root.decodeSize.width : (root.version > 0 ? width : 0) - sourceSize.height: root.constrainDecode ? root.decodeSize.height : (root.version > 0 ? height : 0) + sourceSize.width: root.constrainDecode ? root.decodeSize.width : Math.ceil(width * Screen.devicePixelRatio) + sourceSize.height: root.constrainDecode ? root.decodeSize.height : Math.ceil(height * Screen.devicePixelRatio) } } } diff --git a/desktop/shell/shell/launcher/Launcher.qml b/desktop/shell/shell/launcher/Launcher.qml index 636381b7..f7323243 100644 --- a/desktop/shell/shell/launcher/Launcher.qml +++ b/desktop/shell/shell/launcher/Launcher.qml @@ -1060,7 +1060,8 @@ LC_ALL=C pacman -Qi omarchy-a 2>/dev/null | awk \'/^Depends On/ { on = 1 } /^Opt height: panel.height visible: root.backdropReady source: root.backdropReady ? Util.fileUrl(root.backdropPath) : "" - asynchronous: false + sourceSize: Qt.size(root.backdropWidth, root.backdropHeight) + asynchronous: true cache: false smooth: false } diff --git a/desktop/shell/shell/notificationcenter/NotificationCenter.qml b/desktop/shell/shell/notificationcenter/NotificationCenter.qml index 75f5ed49..4f0f22db 100644 --- a/desktop/shell/shell/notificationcenter/NotificationCenter.qml +++ b/desktop/shell/shell/notificationcenter/NotificationCenter.qml @@ -1028,8 +1028,8 @@ Item { anchors.fill: parent visible: card.iconUrl !== "" source: card.iconUrl - sourceSize.width: width * 2 - sourceSize.height: height * 2 + sourceSize.width: Math.ceil(width * Screen.devicePixelRatio) + sourceSize.height: Math.ceil(height * Screen.devicePixelRatio) fillMode: Image.PreserveAspectFit asynchronous: true } diff --git a/desktop/shell/shell/plugins/background/Background.qml b/desktop/shell/shell/plugins/background/Background.qml index 402844cd..415b2fff 100644 --- a/desktop/shell/shell/plugins/background/Background.qml +++ b/desktop/shell/shell/plugins/background/Background.qml @@ -450,17 +450,8 @@ Item { // decoded at native size first, and a wallpaper smaller than the screen // is decoded at its own size rather than scaled up to cover the screen. readonly property bool sized: width > 0 && height > 0 - // On a tablet, swapping width/height must not clear and asynchronously - // decode the wallpaper again. Keep one orientation-independent decode. - // A high-water mark also ignores intermediate geometry during rotation. - readonly property bool tabletRotation: Quickshell.env("OMARCHY_TOUCH_MODE") === "1" - readonly property int requestedDecodeEdge: sized ? Math.ceil(Math.max(width, height) * screen.devicePixelRatio) : 0 - property int stableDecodeEdge: 0 - onRequestedDecodeEdgeChanged: { - if (requestedDecodeEdge > stableDecodeEdge) stableDecodeEdge = requestedDecodeEdge - } - readonly property int decodeWidth: sized ? (tabletRotation ? Math.max(stableDecodeEdge, requestedDecodeEdge) : Math.ceil(width * screen.devicePixelRatio)) : 0 - readonly property int decodeHeight: sized ? (tabletRotation ? Math.max(stableDecodeEdge, requestedDecodeEdge) : Math.ceil(height * screen.devicePixelRatio)) : 0 + readonly property int decodeWidth: sized ? Math.ceil(width * screen.devicePixelRatio) : 0 + readonly property int decodeHeight: sized ? Math.ceil(height * screen.devicePixelRatio) : 0 function decodeSize(path) { if (!sized || !path) return Qt.size(0, 0) diff --git a/desktop/shell/shell/plugins/lock/LockView.qml b/desktop/shell/shell/plugins/lock/LockView.qml index 52b8a59d..ae5a302e 100644 --- a/desktop/shell/shell/plugins/lock/LockView.qml +++ b/desktop/shell/shell/plugins/lock/LockView.qml @@ -188,7 +188,8 @@ Item { // lock, so the first frame has the wallpaper. cached: true constrainDecode: true - decodeSize: Qt.size(width, height) + asynchronous: false + decodeSize: Qt.size(Math.ceil(width * Screen.devicePixelRatio), Math.ceil(height * Screen.devicePixelRatio)) } // One even scrim over the whole wallpaper: the theme's lock.scrim (its diff --git a/desktop/shell/shell/plugins/lock/Service.qml b/desktop/shell/shell/plugins/lock/Service.qml index 7b371315..9b5bf274 100644 --- a/desktop/shell/shell/plugins/lock/Service.qml +++ b/desktop/shell/shell/plugins/lock/Service.qml @@ -657,7 +657,7 @@ Item { // suspending right after locking froze that decode partway: waking showed // the password field on a bare background, then the wallpaper popped in. // Keep each screen's lock wallpaper decoded in the image cache ahead of - // time, as the lock view requests it (same URL, the screen's logical size, + // time, as the lock view requests it (same URL, the screen's physical size, // PreserveAspectCrop), so the lock draws it on its first frame. readonly property string lockWallpaperPath: videoBackground ? videoPosterPath : backgroundPath readonly property string lockWallpaperUrl: lockWallpaperPath && !Util.isVideoPath(lockWallpaperPath) @@ -671,8 +671,8 @@ Item { required property var modelData visible: false source: root.lockWallpaperUrl - sourceSize.width: modelData.width - sourceSize.height: modelData.height + sourceSize.width: Math.ceil(modelData.width * modelData.devicePixelRatio) + sourceSize.height: Math.ceil(modelData.height * modelData.devicePixelRatio) fillMode: Image.PreserveAspectCrop asynchronous: true cache: true diff --git a/desktop/shell/shell/settings/BackgroundPage.qml b/desktop/shell/shell/settings/BackgroundPage.qml index 4b6dd218..50605a47 100644 --- a/desktop/shell/shell/settings/BackgroundPage.qml +++ b/desktop/shell/shell/settings/BackgroundPage.qml @@ -91,8 +91,8 @@ Item { anchors.fill: parent anchors.margins: parent.border.width visible: !tile.modelData.video - source: tile.modelData.video ? "" : Util.fileUrl(tile.modelData.path) - sourceSize.width: Math.round(page.cell * 1.5) + source: width <= 0 || height <= 0 || tile.modelData.video ? "" : Util.fileUrl(tile.modelData.path) + sourceSize: Qt.size(Math.ceil(width * Screen.devicePixelRatio), Math.ceil(height * Screen.devicePixelRatio)) fillMode: Image.PreserveAspectCrop asynchronous: true cache: false diff --git a/desktop/shell/shell/settings/IconsPage.qml b/desktop/shell/shell/settings/IconsPage.qml index 4fabc6b8..97e9a1c8 100644 --- a/desktop/shell/shell/settings/IconsPage.qml +++ b/desktop/shell/shell/settings/IconsPage.qml @@ -89,8 +89,8 @@ Item { width: parent.width * 1.15 height: parent.height * 1.15 visible: tile.modelData.preview !== "" - source: tile.modelData.preview ? Util.fileUrl(tile.modelData.preview) : "" - sourceSize.width: Math.round(page.cell * 2) + source: width > 0 && height > 0 && tile.modelData.preview ? Util.fileUrl(tile.modelData.preview) : "" + sourceSize: Qt.size(Math.ceil(width * Screen.devicePixelRatio), Math.ceil(height * Screen.devicePixelRatio)) fillMode: Image.PreserveAspectCrop asynchronous: true cache: false diff --git a/desktop/shell/shell/settings/ThemePage.qml b/desktop/shell/shell/settings/ThemePage.qml index cd410f3c..13761c64 100644 --- a/desktop/shell/shell/settings/ThemePage.qml +++ b/desktop/shell/shell/settings/ThemePage.qml @@ -86,8 +86,8 @@ Item { anchors.fill: parent anchors.margins: parent.border.width visible: status === Image.Ready - source: tile.modelData.wallpaper ? Util.fileUrl(tile.modelData.wallpaper) : "" - sourceSize.width: Math.ceil(width * 2) + source: width > 0 && height > 0 && tile.modelData.wallpaper ? Util.fileUrl(tile.modelData.wallpaper) : "" + sourceSize: Qt.size(Math.ceil(width * Screen.devicePixelRatio), Math.ceil(height * Screen.devicePixelRatio)) fillMode: Image.PreserveAspectCrop asynchronous: true cache: false From 01d664739e96308f777bfb1eb79bb755852def31 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Berkay=20K=C3=B6sebay?= Date: Tue, 1 Dec 2026 18:02:06 +0100 Subject: [PATCH 04/17] shell: schedule background probes after startup MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Give initial painting two seconds before background work. Hold that timer while the startup lock is acquiring or drawing its first secure frames. Keep the first manifest scan, bar state, notification storage (including Focus), idle policy, PIN authentication and lock indicators available. Defer these initial tasks: - AppLibrary desktop-entry subscriptions, desktop-file and icon scans, and icon-revision watch. Opening the launcher requests them early. - Plugin directory setup, orphan watcher cleanup, watch and follow-up scan. - Backlight device discovery, the locked session's desktop wallpaper lookup and decode, and the lock cache warmer until the lock draws. Skip the unused intro readlink when there is no cover. - Load emoji data and list stock, installed and extra themes on first use. - Menu guard shell commands and the notification stacking-mode probe. - Monitor and auto-brightness probes, verbose network details, audio node enumeration and output resolution, and power-profile discovery. - Accelerometer presence (rotation-lock state still reads immediately). - Workspace and dock layout lookup, dock desktop entries, keyboard layout lookup, and the initial indicator refresh including reminders, recording and passwordless sudo. Defer update and custom-command polls. - Weather, Elsewhen time-zone probes, Dropbox and Tailscale status and startup retries, agent usage files, provider updates and sync. - Optional low-battery check and profile read, night light, remote session detection, and MPRIS/PipeWire media enumeration. Media actions request the players early. Queue clipboard capture on the next turn. Change polling: - Battery status: 1 s to 5 s with an immediate read on AC changes. - Open power panel: poll profiles every 5 s instead of every second. The status reader supplies the battery sample independently. - Elsewhen: tick at the next minute boundary instead of every second. - Dock launch feedback: wake for the next launch deadline; window arrivals still settle immediately. Assisted-by: LLM Signed-off-by: Berkay Kösebay --- desktop/shell/shell/Commons/AfterStartup.qml | 7 ++++++ desktop/shell/shell/Commons/Startup.qml | 13 ++++++++++ desktop/shell/shell/Commons/qmldir | 2 ++ desktop/shell/shell/plugins/agents/Main.qml | 25 +++++++++++-------- .../shell/plugins/background/Background.qml | 7 +++++- desktop/shell/shell/plugins/bar/Bar.qml | 2 +- .../bar/indicators/PasswordlessSudo.qml | 4 +-- .../shell/plugins/bar/indicators/Reminder.qml | 3 ++- .../bar/indicators/ScreenRecording.qml | 4 +-- .../shell/plugins/bar/widgets/Indicators.qml | 2 +- .../plugins/bar/widgets/KeyboardLayout.qml | 2 +- .../plugins/bar/widgets/SystemUpdate.qml | 4 +-- .../shell/plugins/bar/widgets/Workspaces.qml | 4 +-- .../shell/plugins/clipboard/Clipboard.qml | 2 +- desktop/shell/shell/plugins/dock/Dock.qml | 15 ++++++++--- desktop/shell/shell/plugins/emojis/Emojis.qml | 3 ++- .../plugins/image-picker/ImagePicker.qml | 11 ++------ desktop/shell/shell/plugins/lock/Service.qml | 8 +++++- desktop/shell/shell/plugins/menu/Menu.qml | 12 +++++++-- .../shell/plugins/notifications/Service.qml | 3 ++- .../shell/plugins/panels/audio/Panel.qml | 13 +++++----- .../shell/plugins/panels/dropbox/Service.qml | 4 +-- .../shell/plugins/panels/elsewhen/Panel.qml | 4 +-- .../shell/plugins/panels/monitor/Panel.qml | 2 +- .../shell/plugins/panels/network/Panel.qml | 4 +-- .../shell/plugins/panels/power/Panel.qml | 11 ++++---- .../shell/plugins/panels/power/Status.qml | 9 +++++-- .../plugins/panels/tailscale/Service.qml | 4 +-- .../shell/plugins/panels/weather/Panel.qml | 10 ++++---- .../plugins/services/battery/Service.qml | 4 +-- .../shell/plugins/services/media/Service.qml | 11 +++++--- .../plugins/services/nightlight/Service.qml | 2 +- .../services/remote-session/Service.qml | 3 ++- .../shell/plugins/status/RotationLock.qml | 3 ++- desktop/shell/shell/services/AppLibrary.qml | 18 +++++++++---- .../shell/shell/services/BackgroundIntro.qml | 2 +- .../shell/shell/services/BrightnessKeys.qml | 2 +- .../shell/shell/services/PluginRegistry.qml | 2 +- desktop/shell/shell/shell.qml | 4 +-- 39 files changed, 155 insertions(+), 90 deletions(-) create mode 100644 desktop/shell/shell/Commons/AfterStartup.qml create mode 100644 desktop/shell/shell/Commons/Startup.qml diff --git a/desktop/shell/shell/Commons/AfterStartup.qml b/desktop/shell/shell/Commons/AfterStartup.qml new file mode 100644 index 00000000..c411ba22 --- /dev/null +++ b/desktop/shell/shell/Commons/AfterStartup.qml @@ -0,0 +1,7 @@ +import QtQuick + +// A one-shot task. Components opened later run it on their next event turn. +Timer { + interval: 0 + running: Startup.ready +} diff --git a/desktop/shell/shell/Commons/Startup.qml b/desktop/shell/shell/Commons/Startup.qml new file mode 100644 index 00000000..27c238f5 --- /dev/null +++ b/desktop/shell/shell/Commons/Startup.qml @@ -0,0 +1,13 @@ +pragma Singleton + +import QtQuick + +// Give the first frame priority. If the startup lock is being drawn, its +// service releases the timer once the compositor can show the PIN screen. +Timer { + property bool ready: false + property bool drawingLock: false + interval: 2000 + running: !drawingLock && !ready + onTriggered: ready = true +} diff --git a/desktop/shell/shell/Commons/qmldir b/desktop/shell/shell/Commons/qmldir index 24f4db12..d16656ae 100644 --- a/desktop/shell/shell/Commons/qmldir +++ b/desktop/shell/shell/Commons/qmldir @@ -6,11 +6,13 @@ singleton I18n 1.0 I18n.qml singleton InputDevices 1.0 InputDevices.qml singleton IpcRegistry 1.0 IpcRegistry.qml singleton InputMethodState 1.0 InputMethodState.qml +singleton Startup 1.0 Startup.qml singleton Style 1.0 Style.qml singleton TimeZone 1.0 TimeZone.qml singleton TimeFormat 1.0 TimeFormat.qml singleton UntypedInput 1.0 UntypedInput.qml singleton Util 1.0 Util.qml +AfterStartup 1.0 AfterStartup.qml ShellIpc 1.0 ShellIpc.qml Translations 1.0 Translations.qml WatchedFile 1.0 WatchedFile.qml diff --git a/desktop/shell/shell/plugins/agents/Main.qml b/desktop/shell/shell/plugins/agents/Main.qml index e9426987..b725667f 100644 --- a/desktop/shell/shell/plugins/agents/Main.qml +++ b/desktop/shell/shell/plugins/agents/Main.qml @@ -22,7 +22,7 @@ Item { FileView { id: localModelFile - path: root.home + "/.local/state/omarchy/agent-local/status.json" + path: Startup.ready ? root.home + "/.local/state/omarchy/agent-local/status.json" : "" watchChanges: true printErrors: false onFileChanged: reload() @@ -40,7 +40,7 @@ Item { FileView { id: localRecipesFile - path: root.home + "/.local/state/omarchy/agent-local/list.json" + path: Startup.ready ? root.home + "/.local/state/omarchy/agent-local/list.json" : "" watchChanges: true printErrors: false onFileChanged: reload() @@ -83,7 +83,7 @@ Item { FileView { id: networkFile - path: root.home + "/.local/state/omarchy/agent-local/network.json" + path: Startup.ready ? root.home + "/.local/state/omarchy/agent-local/network.json" : "" watchChanges: true printErrors: false onFileChanged: reload() @@ -97,7 +97,7 @@ Item { FileView { id: clientsFile - path: root.home + "/.local/state/omarchy/agent-local/clients.json" + path: Startup.ready ? root.home + "/.local/state/omarchy/agent-local/clients.json" : "" watchChanges: true printErrors: false onFileChanged: reload() @@ -452,9 +452,11 @@ Item { else limitsRetry.stop() } - Component.onCompleted: { - rescanAgents() - if (syncConfigured()) scheduleSync() + AfterStartup { + onTriggered: { + root.rescanAgents() + if (root.syncConfigured()) root.scheduleSync() + } } // -------------------------------------------------------------- refresh @@ -484,7 +486,7 @@ Item { Timer { interval: root.nearLimit ? Math.min(180, root.refreshIntervalSec) * 1000 : root.refreshIntervalSec * 1000 - running: true + running: Startup.ready repeat: true triggeredOnStart: true onTriggered: root.runUpdate(root.nearLimit ? "limits" : "normal") @@ -660,7 +662,7 @@ Item { FileView { id: orderFile - path: root.orderPath + path: Startup.ready ? root.orderPath : "" watchChanges: true atomicWrites: true printErrors: false @@ -840,7 +842,7 @@ Item { FileView { id: syncSnapshotFile - path: root.syncSnapshotPath + path: Startup.ready ? root.syncSnapshotPath : "" watchChanges: false atomicWrites: true printErrors: false @@ -848,7 +850,7 @@ Item { FileView { id: hostnameFile - path: "/etc/hostname" + path: Startup.ready ? "/etc/hostname" : "" watchChanges: false printErrors: false onLoaded: root.detectedHostname = String(text() || "").trim() @@ -881,6 +883,7 @@ Item { } function scheduleSync() { + if (!Startup.ready) return if (!syncConfigured()) return syncDebounce.restart() } diff --git a/desktop/shell/shell/plugins/background/Background.qml b/desktop/shell/shell/plugins/background/Background.qml index 415b2fff..27b0f609 100644 --- a/desktop/shell/shell/plugins/background/Background.qml +++ b/desktop/shell/shell/plugins/background/Background.qml @@ -391,7 +391,12 @@ Item { } } - Component.onCompleted: refreshBackground() + Component.onCompleted: { + if (Quickshell.env("OMARCHY_START_LOCKED") !== "1") refreshBackground() + } + AfterStartup { + onTriggered: if (Quickshell.env("OMARCHY_START_LOCKED") === "1" && !root.currentBackground) root.refreshBackground() + } Variants { id: backgrounds diff --git a/desktop/shell/shell/plugins/bar/Bar.qml b/desktop/shell/shell/plugins/bar/Bar.qml index de750d56..f858e56a 100644 --- a/desktop/shell/shell/plugins/bar/Bar.qml +++ b/desktop/shell/shell/plugins/bar/Bar.qml @@ -3292,7 +3292,7 @@ Item { Timer { interval: Math.max(1, Number(customRoot.setting("interval", 5))) * 1000 - running: String(customRoot.setting("exec", "")) !== "" + running: Startup.ready && String(customRoot.setting("exec", "")) !== "" repeat: true triggeredOnStart: true onTriggered: root.runProcess(customProc) diff --git a/desktop/shell/shell/plugins/bar/indicators/PasswordlessSudo.qml b/desktop/shell/shell/plugins/bar/indicators/PasswordlessSudo.qml index 6639aa51..7db0b97f 100644 --- a/desktop/shell/shell/plugins/bar/indicators/PasswordlessSudo.qml +++ b/desktop/shell/shell/plugins/bar/indicators/PasswordlessSudo.qml @@ -28,8 +28,8 @@ BarIndicator { statusProc.running = true } - onBarChanged: refresh() - Component.onCompleted: refresh() + onBarChanged: if (Startup.ready) refresh() + AfterStartup { onTriggered: root.refresh() } // No polling: each probe is a hardened script plus sudo calls that can log. // omarchy-sudo-passwordless refreshes omarchy.indicators on enable, disable diff --git a/desktop/shell/shell/plugins/bar/indicators/Reminder.qml b/desktop/shell/shell/plugins/bar/indicators/Reminder.qml index 3441edbe..df0f1a6d 100644 --- a/desktop/shell/shell/plugins/bar/indicators/Reminder.qml +++ b/desktop/shell/shell/plugins/bar/indicators/Reminder.qml @@ -1,4 +1,5 @@ import QtQuick +import qs.Commons import Quickshell import Quickshell.Io import qs.Ui @@ -29,7 +30,7 @@ BarIndicator { tooltip = String(data.tooltip || "") } - Component.onCompleted: refresh() + AfterStartup { onTriggered: root.refresh() } Connections { target: root.indicatorHost diff --git a/desktop/shell/shell/plugins/bar/indicators/ScreenRecording.qml b/desktop/shell/shell/plugins/bar/indicators/ScreenRecording.qml index 9e93047e..fbd47f1d 100644 --- a/desktop/shell/shell/plugins/bar/indicators/ScreenRecording.qml +++ b/desktop/shell/shell/plugins/bar/indicators/ScreenRecording.qml @@ -74,8 +74,8 @@ BarIndicator { statusProc.running = true } - onBarChanged: refresh() - Component.onCompleted: refresh() + onBarChanged: if (Startup.ready) refresh() + AfterStartup { onTriggered: root.refresh() } Connections { target: root.indicatorHost diff --git a/desktop/shell/shell/plugins/bar/widgets/Indicators.qml b/desktop/shell/shell/plugins/bar/widgets/Indicators.qml index 043bb3b1..4d98ce3e 100644 --- a/desktop/shell/shell/plugins/bar/widgets/Indicators.qml +++ b/desktop/shell/shell/plugins/bar/widgets/Indicators.qml @@ -227,8 +227,8 @@ BarWidget { Component.onCompleted: { syncInactiveIndicatorModel() - root.refreshRequested() } + AfterStartup { onTriggered: root.refreshRequested() } // Instantiating both orientation trees and toggling `visible` doubled every // indicator per bar (and every process an indicator spawns, once per diff --git a/desktop/shell/shell/plugins/bar/widgets/KeyboardLayout.qml b/desktop/shell/shell/plugins/bar/widgets/KeyboardLayout.qml index 48f3c651..a25672e9 100644 --- a/desktop/shell/shell/plugins/bar/widgets/KeyboardLayout.qml +++ b/desktop/shell/shell/plugins/bar/widgets/KeyboardLayout.qml @@ -109,7 +109,7 @@ BarWidget { refreshTimer.restart() } - Component.onCompleted: refresh() + AfterStartup { onTriggered: root.refresh() } Connections { target: Hyprland diff --git a/desktop/shell/shell/plugins/bar/widgets/SystemUpdate.qml b/desktop/shell/shell/plugins/bar/widgets/SystemUpdate.qml index ed88af74..2cffbdc5 100644 --- a/desktop/shell/shell/plugins/bar/widgets/SystemUpdate.qml +++ b/desktop/shell/shell/plugins/bar/widgets/SystemUpdate.qml @@ -56,11 +56,11 @@ BarWidget { // Recheck as soon as NetworkManager reports full internet connectivity, so a // check that ran before Wi-Fi came up doesn't hide the icon for six hours. readonly property bool online: Networking.connectivity === NetworkConnectivity.Full - onOnlineChanged: if (online) root.refresh() + onOnlineChanged: if (online && Startup.ready) root.refresh() Timer { interval: 21600000 - running: true + running: Startup.ready repeat: true triggeredOnStart: true onTriggered: root.refresh() diff --git a/desktop/shell/shell/plugins/bar/widgets/Workspaces.qml b/desktop/shell/shell/plugins/bar/widgets/Workspaces.qml index 0166c429..a883bae8 100644 --- a/desktop/shell/shell/plugins/bar/widgets/Workspaces.qml +++ b/desktop/shell/shell/plugins/bar/widgets/Workspaces.qml @@ -185,8 +185,8 @@ BarWidget { root.bar.run(command) } - Component.onCompleted: refresh() - onMonitorChanged: root.showActiveMode() + AfterStartup { onTriggered: root.refresh() } + onMonitorChanged: if (Startup.ready) root.showActiveMode() Connections { target: root.monitor diff --git a/desktop/shell/shell/plugins/clipboard/Clipboard.qml b/desktop/shell/shell/plugins/clipboard/Clipboard.qml index d8649679..e2166131 100644 --- a/desktop/shell/shell/plugins/clipboard/Clipboard.qml +++ b/desktop/shell/shell/plugins/clipboard/Clipboard.qml @@ -246,7 +246,7 @@ Item { Quickshell.execDetached([root.omarchyPath + "/bin/omarchy-clipboard-open", "--history-index", String(row.historyIndex)]) } - Component.onCompleted: initProc.running = true + Component.onCompleted: Qt.callLater(function() { initProc.running = true }) ListModel { id: displayModel } diff --git a/desktop/shell/shell/plugins/dock/Dock.qml b/desktop/shell/shell/plugins/dock/Dock.qml index 38a1da7b..ee72b9a9 100644 --- a/desktop/shell/shell/plugins/dock/Dock.qml +++ b/desktop/shell/shell/plugins/dock/Dock.qml @@ -35,6 +35,7 @@ Item { // Entries that can claim a terminal app's window: those run in a terminal, // and those that hand the terminal an app id of their own. readonly property var terminalEntries: { + if (!Startup.ready) return [] var values = DesktopEntries.applications.values var out = [] for (var i = 0; i < values.length; i++) { @@ -55,6 +56,7 @@ Item { // A pinned app that is not installed has nothing to launch, so it is left // out until it is. Windows are matched to the desktop entry that claims them. readonly property var items: { + if (!Startup.ready) return [] var appsRevision = DesktopEntries.applications.values.length var pinned = (root.pendingPins || DockModel.pinnedIds(dockConfig, defaultDockConfig)).filter(function(id) { return !!DesktopEntries.byId(id) @@ -135,14 +137,19 @@ Item { var launch = root.launches[key] var item = root.itemsByKey[key] var windows = item ? item.windows.length : 0 - if (windows > launch.windows || now - launch.at > root.launchTimeout) changed = true + if (windows > launch.windows || now - launch.at >= root.launchTimeout) changed = true else next[key] = launch } if (changed) root.launches = next } Timer { - interval: 1000 + interval: { + var deadline = Infinity + for (var key in root.launches) + deadline = Math.min(deadline, root.launches[key].at + root.launchTimeout) + return isFinite(deadline) ? Math.max(1, deadline - Date.now()) : root.launchTimeout + } repeat: true running: Object.keys(root.launches).length > 0 onTriggered: root.settleLaunches() @@ -288,7 +295,7 @@ Item { } function readMode(workspaceId) { - if (!(workspaceId >= 1) || root.readModes[workspaceId]) return + if (!Startup.ready || !(workspaceId >= 1) || root.readModes[workspaceId]) return root.readModes[workspaceId] = true root.pendingModes.push(workspaceId) root.readNextMode() @@ -317,9 +324,9 @@ Item { } Component.onCompleted: { - refresh() syncItemModel() } + AfterStartup { onTriggered: root.refresh() } Process { id: modeProc diff --git a/desktop/shell/shell/plugins/emojis/Emojis.qml b/desktop/shell/shell/plugins/emojis/Emojis.qml index a27e67b8..ace47263 100644 --- a/desktop/shell/shell/plugins/emojis/Emojis.qml +++ b/desktop/shell/shell/plugins/emojis/Emojis.qml @@ -155,7 +155,8 @@ Item { ListModel { id: displayModel } FileView { - path: root.omarchyPath + "/shell/plugins/emojis/emojis.json" + path: windowLoader.active ? root.omarchyPath + "/shell/plugins/emojis/emojis.json" : "" + blockLoading: true onLoaded: root.loadEmojis(text()) } readonly property var panel: windowLoader.item diff --git a/desktop/shell/shell/plugins/image-picker/ImagePicker.qml b/desktop/shell/shell/plugins/image-picker/ImagePicker.qml index b2512791..1178eab9 100644 --- a/desktop/shell/shell/plugins/image-picker/ImagePicker.qml +++ b/desktop/shell/shell/plugins/image-picker/ImagePicker.qml @@ -35,8 +35,7 @@ Item { property string doneFile: "" property string filterText: "" property var doneFilesToRelease: [] - // Themes open from rows the shell already holds, so the picker shows without - // waiting on omarchy-theme-switcher; each open refreshes them behind it. + // Keep the rows after the first theme request. Later opens refresh them behind the picker. property string themeRows: "" property bool themeMode: false property bool themeOpenPending: false @@ -392,7 +391,7 @@ Item { if (themeRows) { openThemeRows() } else { - // First open before the startup refresh has landed. + // A cold picker opens as soon as the theme listing arrives. themeOpenPending = true } refreshThemeRows() @@ -533,12 +532,6 @@ Item { } } - Component.onCompleted: { - refreshThemeRows() - refreshExtraThemes() - refreshStockThemes() - } - function startImageScan(serial, dirs) { if (loadImagesProc.running) { loadImagesProc.queuedSerial = serial diff --git a/desktop/shell/shell/plugins/lock/Service.qml b/desktop/shell/shell/plugins/lock/Service.qml index 9b5bf274..ce0e6f8c 100644 --- a/desktop/shell/shell/plugins/lock/Service.qml +++ b/desktop/shell/shell/plugins/lock/Service.qml @@ -665,7 +665,7 @@ Item { : "" Variants { - model: Quickshell.screens + model: !root.startLocked || root.startupLifted ? Quickshell.screens : [] Image { required property var modelData @@ -949,6 +949,12 @@ Item { // The lock is on screen: lift Labwc's startup cover, and record for the // installer that the PIN screen is on (omarchy-desktop-ready pin-screen). + Binding { + target: Startup + property: "drawingLock" + value: root.startLocked && root.lockRequested && !root.startupLifted + } + function liftStartup() { if (startupLifted) return startupLifted = true diff --git a/desktop/shell/shell/plugins/menu/Menu.qml b/desktop/shell/shell/plugins/menu/Menu.qml index 95ca6450..79fd68da 100644 --- a/desktop/shell/shell/plugins/menu/Menu.qml +++ b/desktop/shell/shell/plugins/menu/Menu.qml @@ -308,7 +308,7 @@ Item { root.items = mergedMenu.items root.itemOrder = mergedMenu.itemOrder root.rowsLoaded = true - if (!skipGuards && root.defaultMenuSettled && root.userMenuSettled) root.evaluateGuards() + if (!skipGuards && root.defaultMenuSettled && root.userMenuSettled) root.scheduleGuards() if (root.opened) { root.rebuildDisplay() if (!root.dmenuActive) { @@ -1185,7 +1185,7 @@ Item { printErrors: false onLoaded: { root.defaultMenuItems = MenuModel.keepMenuRows(root.defaultMenuItems, text(), true); root.defaultMenuSettled = true; root.rebuildItemsFromSources() } // A user file that loaded first held its evaluation for this one. - onLoadFailed: { root.defaultMenuSettled = true; if (root.userMenuSettled) root.evaluateGuards() } + onLoadFailed: { root.defaultMenuSettled = true; if (root.userMenuSettled) root.scheduleGuards() } onFileChanged: reload() } @@ -1233,7 +1233,15 @@ Item { property var disabledResults: ({}) // id → true|false (dim, skip cursor) property bool guardsPending: false + property bool guardsDeferred: false + function scheduleGuards() { + if (Startup.ready || opened) evaluateGuards() + else guardsDeferred = true + } + AfterStartup { onTriggered: if (root.guardsDeferred) root.evaluateGuards() } + function evaluateGuards() { + guardsDeferred = false // Process ignores a command change while it is running, and `collected` // belongs to the run in flight, so a second evaluation cannot overwrite // the first: it would throw away the lines already read and never start. diff --git a/desktop/shell/shell/plugins/notifications/Service.qml b/desktop/shell/shell/plugins/notifications/Service.qml index 35f2ee3b..fb1f18d1 100644 --- a/desktop/shell/shell/plugins/notifications/Service.qml +++ b/desktop/shell/shell/plugins/notifications/Service.qml @@ -1620,7 +1620,8 @@ Item { onExited: function(code) { service.storeReady = code === 0 } } - Component.onCompleted: { storePrepare.running = true; stackModeProc.running = true } + Component.onCompleted: storePrepare.running = true // quiet.json supplies the lock's Focus icon. + AfterStartup { onTriggered: stackModeProc.running = true } // A reload or a clean exit inside the save delay still writes. Component.onDestruction: flushStore() diff --git a/desktop/shell/shell/plugins/panels/audio/Panel.qml b/desktop/shell/shell/plugins/panels/audio/Panel.qml index 0430053a..2f0d4440 100644 --- a/desktop/shell/shell/plugins/panels/audio/Panel.qml +++ b/desktop/shell/shell/plugins/panels/audio/Panel.qml @@ -16,8 +16,8 @@ Panel { readonly property var sink: Pipewire.defaultAudioSink readonly property var source: Pipewire.defaultAudioSource - readonly property var nodes: Pipewire.nodes ? Pipewire.nodes.values : [] - readonly property var mprisPlayers: Mpris.players ? Mpris.players.values : [] + readonly property var nodes: (Startup.ready || opened) && Pipewire.nodes ? Pipewire.nodes.values : [] + readonly property var mprisPlayers: opened && Mpris.players ? Mpris.players.values : [] readonly property var mediaService: bar?.shell?.firstPartyServiceFor("omarchy.media") readonly property var activeMediaPlayer: mediaService ? mediaService.activePlayer : null @@ -157,11 +157,11 @@ Panel { // Re-resolve whenever the selected output changes, and when nodes or links // come and go: a tuning being applied or removed underneath us, or a DSP sink // rerouted to another output, shows up as exactly that. - onSinkChanged: resolveVolumeSink() - onNodesChanged: volumeSinkResolveTimer.restart() + onSinkChanged: if (Startup.ready || opened) resolveVolumeSink() + onNodesChanged: if (Startup.ready || opened) volumeSinkResolveTimer.restart() Connections { - target: Pipewire.linkGroups + target: Startup.ready || root.opened ? Pipewire.linkGroups : null function onValuesChanged() { volumeSinkResolveTimer.restart() } } @@ -369,6 +369,7 @@ Panel { onOpenedChanged: { if (opened) { + resolveVolumeSink() refreshDisplayAudioModels() focusSection = "output" selectedIndex = -1 // first keyboard cursor reveal starts on the output slider @@ -724,7 +725,7 @@ Panel { onTriggered: root.resolveVolumeSink() } - Component.onCompleted: root.resolveVolumeSink() + AfterStartup { onTriggered: root.resolveVolumeSink() } Timer { id: audioModelRefreshTimer diff --git a/desktop/shell/shell/plugins/panels/dropbox/Service.qml b/desktop/shell/shell/plugins/panels/dropbox/Service.qml index 86896ccf..17b7ef28 100644 --- a/desktop/shell/shell/plugins/panels/dropbox/Service.qml +++ b/desktop/shell/shell/plugins/panels/dropbox/Service.qml @@ -185,7 +185,7 @@ Item { id: refreshTimer interval: root.refreshIntervalSec * 1000 repeat: true - running: true + running: Startup.ready triggeredOnStart: true onTriggered: root.refresh() } @@ -199,7 +199,7 @@ Item { property int ticks: 0 interval: 2000 repeat: true - running: true + running: Startup.ready onTriggered: { ticks += 1 if (root.running || ticks >= 15) startupRamp.running = false diff --git a/desktop/shell/shell/plugins/panels/elsewhen/Panel.qml b/desktop/shell/shell/plugins/panels/elsewhen/Panel.qml index 5245f941..e08c2be0 100644 --- a/desktop/shell/shell/plugins/panels/elsewhen/Panel.qml +++ b/desktop/shell/shell/plugins/panels/elsewhen/Panel.qml @@ -724,7 +724,7 @@ Panel { spinPending = false; spinFallback.stop() } } - Component.onCompleted: refresh() + AfterStartup { onTriggered: root.refresh() } Process { id: probeProc @@ -922,7 +922,7 @@ Panel { } Timer { - interval: 1000 + interval: 60000 - (root.nowMs % 60000) running: root.opened repeat: true onTriggered: root.tick() diff --git a/desktop/shell/shell/plugins/panels/monitor/Panel.qml b/desktop/shell/shell/plugins/panels/monitor/Panel.qml index 3abc3db4..1475c115 100644 --- a/desktop/shell/shell/plugins/panels/monitor/Panel.qml +++ b/desktop/shell/shell/plugins/panels/monitor/Panel.qml @@ -674,7 +674,7 @@ Panel { implicitWidth: button.implicitWidth implicitHeight: button.implicitHeight - Component.onCompleted: refresh() + AfterStartup { onTriggered: root.refresh() } // KeyboardPanel primes focus at open-time, so SUPER-bound IPC summons land // with j/k ready to navigate. Keep a default landing point, but don't paint diff --git a/desktop/shell/shell/plugins/panels/network/Panel.qml b/desktop/shell/shell/plugins/panels/network/Panel.qml index c5baedd9..7d4d7d77 100644 --- a/desktop/shell/shell/plugins/panels/network/Panel.qml +++ b/desktop/shell/shell/plugins/panels/network/Panel.qml @@ -943,8 +943,8 @@ Panel { implicitWidth: networkManagerAvailable ? button.implicitWidth : 0 implicitHeight: networkManagerAvailable ? button.implicitHeight : 0 - Component.onCompleted: if (networkManagerAvailable) refresh() - onNetworkManagerAvailableChanged: if (networkManagerAvailable) refresh() + AfterStartup { onTriggered: if (root.networkManagerAvailable) root.refresh() } + onNetworkManagerAvailableChanged: if (networkManagerAvailable && (Startup.ready || opened)) refresh() // Pulls everything we want about the active route's interface in one shot. Process { diff --git a/desktop/shell/shell/plugins/panels/power/Panel.qml b/desktop/shell/shell/plugins/panels/power/Panel.qml index 7a9210e9..4f783ff9 100644 --- a/desktop/shell/shell/plugins/panels/power/Panel.qml +++ b/desktop/shell/shell/plugins/panels/power/Panel.qml @@ -220,10 +220,10 @@ Panel { onBatteryPresentChanged: { if (!batteryPresent && !hosted) close() - else Qt.callLater(root.refresh) + else if (Startup.ready || opened) Qt.callLater(root.refresh) } - Component.onCompleted: refresh() + AfterStartup { onTriggered: root.refresh() } visible: batteryPresent implicitWidth: batteryPresent ? button.implicitWidth : 0 @@ -241,12 +241,11 @@ Panel { } Timer { - interval: 1000 - // The battery reading is Status.qml's own; open, the profiles too. + interval: 5000 + // Status polls the battery independently. running: root.opened repeat: true - triggeredOnStart: true - onTriggered: root.refresh() + onTriggered: if (!profilesProc.running) profilesProc.running = true } // Rotate the status phrase while the panel is open and we're in a diff --git a/desktop/shell/shell/plugins/panels/power/Status.qml b/desktop/shell/shell/plugins/panels/power/Status.qml index d668d8d8..83fa4792 100644 --- a/desktop/shell/shell/plugins/panels/power/Status.qml +++ b/desktop/shell/shell/plugins/panels/power/Status.qml @@ -12,7 +12,7 @@ Item { visible: false // The battery script's readings (omarchy-battery-status --shell), read - // every second: discovery must not depend on a charger event or on UPower. + // periodically: discovery must not depend on a charger event or on UPower. property var batteryInfo: ({}) readonly property bool externalPower: batteryInfo.external_power === "connected" readonly property var batteryDevice: { @@ -57,8 +57,13 @@ Item { stdout: StdioCollector { waitForEnd: true; onStreamFinished: root.updateKeyValue(text) } } + Connections { + target: UPower + function onOnBatteryChanged() { root.refresh() } + } + Timer { - interval: 1000 + interval: 5000 running: true repeat: true triggeredOnStart: true diff --git a/desktop/shell/shell/plugins/panels/tailscale/Service.qml b/desktop/shell/shell/plugins/panels/tailscale/Service.qml index 2d3c6a21..f4d091ac 100644 --- a/desktop/shell/shell/plugins/panels/tailscale/Service.qml +++ b/desktop/shell/shell/plugins/panels/tailscale/Service.qml @@ -489,7 +489,7 @@ Item { id: refreshTimer interval: root.refreshIntervalSec * 1000 repeat: true - running: true + running: Startup.ready triggeredOnStart: true onTriggered: root.refresh() } @@ -502,7 +502,7 @@ Item { property int ticks: 0 interval: 2000 repeat: true - running: true + running: Startup.ready onTriggered: { ticks += 1 if (root.running || ticks >= 15) startupRamp.running = false diff --git a/desktop/shell/shell/plugins/panels/weather/Panel.qml b/desktop/shell/shell/plugins/panels/weather/Panel.qml index 00505169..bdf8ac50 100644 --- a/desktop/shell/shell/plugins/panels/weather/Panel.qml +++ b/desktop/shell/shell/plugins/panels/weather/Panel.qml @@ -73,7 +73,7 @@ Panel { property var detectedLocationState: ({ name: "", latitude: null, longitude: null }) property bool detectingLocation: false readonly property bool autoLocation: Model.isAutoLocation(configuredLocationState) - onAutoLocationChanged: if (autoLocation) detectLocation() + onAutoLocationChanged: if (autoLocation && (Startup.ready || opened)) detectLocation() // The query is the wttr.in path segment (coordinates when known, else the // encoded name); empty means wttr.in's own IP auto-detect, used only when @@ -90,7 +90,7 @@ Panel { dailyForecastRetries = 0 forecastProc.running = false dailyForecastProc.running = false - Qt.callLater(refresh) + if (Startup.ready || opened) Qt.callLater(refresh) } property FileView locationFile: FileView { @@ -108,7 +108,7 @@ Panel { // state doesn't change locationQuery and so triggers no refetch. Timer { interval: 1500 - running: true + running: Startup.ready onTriggered: locationFile.reload() } @@ -506,12 +506,12 @@ Panel { // scheduled refresh. Restarting the timer fetches at once (triggeredOnStart) // and counts the next scheduled refresh from there. readonly property bool online: Networking.connectivity === NetworkConnectivity.Full - onOnlineChanged: if (online) refreshTimer.restart() + onOnlineChanged: if (online && Startup.ready) refreshTimer.restart() Timer { id: refreshTimer interval: root.refreshMinutes * 60 * 1000 - running: true + running: Startup.ready repeat: true triggeredOnStart: true onTriggered: { diff --git a/desktop/shell/shell/plugins/services/battery/Service.qml b/desktop/shell/shell/plugins/services/battery/Service.qml index ce4a4089..d741c6ab 100644 --- a/desktop/shell/shell/plugins/services/battery/Service.qml +++ b/desktop/shell/shell/plugins/services/battery/Service.qml @@ -126,7 +126,7 @@ Item { Timer { interval: 30000 - running: true + running: Startup.ready repeat: true triggeredOnStart: true onTriggered: root.checkBattery() @@ -141,5 +141,5 @@ Item { } } - Component.onCompleted: root.refreshPowerProfile() + AfterStartup { onTriggered: root.refreshPowerProfile() } } diff --git a/desktop/shell/shell/plugins/services/media/Service.qml b/desktop/shell/shell/plugins/services/media/Service.qml index 86c5cca3..e45c5d7f 100644 --- a/desktop/shell/shell/plugins/services/media/Service.qml +++ b/desktop/shell/shell/plugins/services/media/Service.qml @@ -15,8 +15,10 @@ Item { property var pendingTrackOsd: null property int playSerial: 0 - readonly property var players: Mpris.players ? Mpris.players.values : [] - readonly property var nodes: Pipewire.nodes ? Pipewire.nodes.values : [] + property bool mediaRequested: false + readonly property bool watchMedia: Startup.ready || mediaRequested + readonly property var players: watchMedia && Mpris.players ? Mpris.players.values : [] + readonly property var nodes: watchMedia && Pipewire.nodes ? Pipewire.nodes.values : [] readonly property var playbackStreams: { var list = [] for (var i = 0; i < nodes.length; i++) { @@ -257,6 +259,7 @@ Item { } function selectPlayer(key) { + mediaRequested = true var player = playerForKey(key) if (!player || !hasMetadata(player)) return false preferredPlayerKey = playerKey(player) @@ -286,6 +289,7 @@ Item { } function switchSource(delta, transferPlayback, showFeedback) { + mediaRequested = true var list = sourceCyclePlayers if (!list || list.length === 0) return false @@ -340,6 +344,7 @@ Item { } function runAction(action, showFeedback, targetKey) { + mediaRequested = true var player = playerForAction(action, targetKey) var key = playerKey(player) var actionLabel = I18n.t("media.playPause") @@ -406,7 +411,6 @@ Item { // syncPlayingOrder only depends on the set of players and each player's // isPlaying state: onPlayersChanged covers players appearing/disappearing, // and the Instantiator wires isPlayingChanged for each live player. - Component.onCompleted: root.syncPlayingOrder() onPlayersChanged: root.syncPlayingOrder() Instantiator { @@ -477,6 +481,7 @@ Item { PwObjectTracker { objects: root.defaultSink ? [root.defaultSink] : [] } function statusJson() { + mediaRequested = true var p = activePlayer return JSON.stringify({ hasPlayer: p !== null, diff --git a/desktop/shell/shell/plugins/services/nightlight/Service.qml b/desktop/shell/shell/plugins/services/nightlight/Service.qml index 90bce7f9..b6028613 100644 --- a/desktop/shell/shell/plugins/services/nightlight/Service.qml +++ b/desktop/shell/shell/plugins/services/nightlight/Service.qml @@ -86,7 +86,7 @@ Item { } } - Component.onCompleted: refresh() + AfterStartup { onTriggered: root.refresh() } ShellIpc { target: "nightlight" diff --git a/desktop/shell/shell/plugins/services/remote-session/Service.qml b/desktop/shell/shell/plugins/services/remote-session/Service.qml index fd94248a..c76e0eaa 100644 --- a/desktop/shell/shell/plugins/services/remote-session/Service.qml +++ b/desktop/shell/shell/plugins/services/remote-session/Service.qml @@ -1,4 +1,5 @@ import QtQuick +import qs.Commons import Quickshell import Quickshell.Hyprland import Quickshell.Io @@ -53,7 +54,7 @@ Item { root.stateLoaded = true } - Component.onCompleted: refresh() + AfterStartup { onTriggered: root.refresh() } Component.onDestruction: root.setCaptureOverride(false, true) // gliff-server captures the screen through ext-image-copy-capture, so a diff --git a/desktop/shell/shell/plugins/status/RotationLock.qml b/desktop/shell/shell/plugins/status/RotationLock.qml index 776eaf75..7b031c23 100644 --- a/desktop/shell/shell/plugins/status/RotationLock.qml +++ b/desktop/shell/shell/plugins/status/RotationLock.qml @@ -1,4 +1,5 @@ import QtQuick +import qs.Commons import Quickshell import Quickshell.Io @@ -22,7 +23,7 @@ Item { root.sensor = exitCode === 0 && probeOut.text.trim() === "b true" } } - Component.onCompleted: probe.running = true + AfterStartup { onTriggered: probe.running = true } // The proxy may still be starting when the shell does: ask once more. Timer { interval: 10000 diff --git a/desktop/shell/shell/services/AppLibrary.qml b/desktop/shell/shell/services/AppLibrary.qml index e68dec16..1ea2df42 100644 --- a/desktop/shell/shell/services/AppLibrary.qml +++ b/desktop/shell/shell/services/AppLibrary.qml @@ -13,6 +13,8 @@ Item { property string omarchyPath: Quickshell.env("OMARCHY_PATH") + property bool indexRequested: false + readonly property bool indexActive: Startup.ready || indexRequested property var configuredHiddenEntryIds: ({}) property var desktopHiddenEntryIds: ({}) // Desktop id -> X-Omarchy-Dock-Click, which Quickshell doesn't parse. @@ -72,6 +74,7 @@ Item { } function sortedEntries(query) { + indexRequested = true var values = DesktopEntries.applications.values || [] return AppSearch.sortedEntries(values, query, function(entry) { return root.isHiddenEntry(entry) }) } @@ -96,6 +99,7 @@ Item { // A request during a scan queues one more, since the running scan may have // listed icons before they changed. function refreshIcons() { + if (!indexActive) { indexRequested = true; return } if (iconIndexScan.running) root.iconRescanQueued = true else iconIndexScan.running = true } @@ -341,7 +345,7 @@ Item { } FileView { - path: root.home + "/.local/state/omarchy/current/icons.revision" + path: root.indexActive ? root.home + "/.local/state/omarchy/current/icons.revision" : "" watchChanges: true printErrors: false onFileChanged: { @@ -386,7 +390,7 @@ Item { } Connections { - target: DesktopEntries.applications + target: root.indexActive ? DesktopEntries.applications : null function onValuesChanged() { desktopEntryScan.running = true iconIndexDebounce.restart() @@ -394,8 +398,12 @@ Item { } } - Component.onCompleted: { - desktopEntryScan.running = true - iconIndexScan.running = true + Timer { + interval: 0 + running: root.indexActive + onTriggered: { + desktopEntryScan.running = true + iconIndexScan.running = true + } } } diff --git a/desktop/shell/shell/services/BackgroundIntro.qml b/desktop/shell/shell/services/BackgroundIntro.qml index f7919617..bc54a39c 100644 --- a/desktop/shell/shell/services/BackgroundIntro.qml +++ b/desktop/shell/shell/services/BackgroundIntro.qml @@ -276,7 +276,7 @@ Item { Component.onCompleted: { checked = true - if (!startupBackgroundPath && !startupPending) startupBackground.running = true + if (cover && !startupBackgroundPath && !startupPending) startupBackground.running = true // Orchard: without the cover there is no intro to play or wait for. if (cover) introProc.running = true } diff --git a/desktop/shell/shell/services/BrightnessKeys.qml b/desktop/shell/shell/services/BrightnessKeys.qml index 0f9818f5..f6c22f91 100644 --- a/desktop/shell/shell/services/BrightnessKeys.qml +++ b/desktop/shell/shell/services/BrightnessKeys.qml @@ -92,7 +92,7 @@ Item { Process { id: deviceProc command: ["omarchy-hw-display"] - running: true + running: Startup.ready stdout: StdioCollector { waitForEnd: true onStreamFinished: root.device = String(text || "").trim() diff --git a/desktop/shell/shell/services/PluginRegistry.qml b/desktop/shell/shell/services/PluginRegistry.qml index 8ee43474..3e2216b6 100644 --- a/desktop/shell/shell/services/PluginRegistry.qml +++ b/desktop/shell/shell/services/PluginRegistry.qml @@ -804,5 +804,5 @@ QtObject { return slash === -1 ? relative : relative.slice(0, slash) } - Component.onCompleted: ensureUserDir() + property AfterStartup watcherSetup: AfterStartup { onTriggered: registry.ensureUserDir() } } diff --git a/desktop/shell/shell/shell.qml b/desktop/shell/shell/shell.qml index 92b97170..5355d471 100644 --- a/desktop/shell/shell/shell.qml +++ b/desktop/shell/shell/shell.qml @@ -293,9 +293,7 @@ ShellRoot { pluginRegistry.firstPartyDir = shell.firstPartyPluginsDir pluginRegistry.shellConfigProvider = function() { return shell.shellConfig } pluginRegistry.shellConfigMutator = function(mutate) { shell.mutateShellConfig(mutate) } - // PluginRegistry.ensureUserDir() runs in its own Component.onCompleted and - // chains rescan() once the directory exists. We also kick a scan here in - // case the user dir already existed at startup. + // Discover the lock, bar and IPC immediately. The user plugin watcher starts later. pluginRegistry.rescan() shell._syncServices() } From 6df3b5288712d7de995124f139c800f220eb5cf8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Berkay=20K=C3=B6sebay?= Date: Tue, 1 Dec 2026 18:02:06 +0100 Subject: [PATCH 05/17] shell: hand the lazy panels the root through their loaders MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Inside sourceComponent: Launcher { shell: shell }, `shell` names the panel's own shell property (null), not the root object, so the lazily loaded launcher got no app library and showed no apps (TypeError: Cannot read property 'appLibrary' of null), and the control and notification centres got no shell. Each loader now carries the root as rootShell and the panels read it from there. Assisted-by: LLM Signed-off-by: Berkay Kösebay --- desktop/shell/shell/shell.qml | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/desktop/shell/shell/shell.qml b/desktop/shell/shell/shell.qml index 5355d471..165221df 100644 --- a/desktop/shell/shell/shell.qml +++ b/desktop/shell/shell/shell.qml @@ -35,9 +35,12 @@ ShellRoot { // Orchard: the launcher answers the stock Apps menu action // (`omarchy-shell omarchy.dock apps`), so Home, Super, Super+Space and the // bar's logo open it, without mapping Hyprland's dock. + // Lazy panels get the root through their loader: inside the component, `shell` + // names the panel's own (still null) shell property, not this object. OnDemandLoader { id: appGrid - sourceComponent: Launcher { shell: shell; appLibrary: shell.appLibrary } + readonly property var rootShell: shell + sourceComponent: Launcher { shell: appGrid.rootShell; appLibrary: appGrid.rootShell.appLibrary } } readonly property var launcher: appGrid.item ShellIpc { @@ -80,9 +83,11 @@ ShellRoot { } readonly property CenterLoader controlCenter: CenterLoader { + id: controlCenterLoader noteName: "omarchy-control-center-open" + readonly property var rootShell: shell readonly property bool popupStyle: !!item && item.popupStyle - sourceComponent: ControlCenter { shell: shell } + sourceComponent: ControlCenter { shell: controlCenterLoader.rootShell } } ShellIpc { target: "omarchy.controlcenter" @@ -92,8 +97,10 @@ ShellRoot { function page(module: string): void { shell.controlCenter.load().openPage(module) } } readonly property CenterLoader notificationCenter: CenterLoader { + id: notificationCenterLoader noteName: "omarchy-notification-center-open" - sourceComponent: NotificationCenter { shell: shell } + readonly property var rootShell: shell + sourceComponent: NotificationCenter { shell: notificationCenterLoader.rootShell } } ShellIpc { target: "omarchy.notificationcenter" From 81a0bfba05ba3a3dcd441b5ba435bd98f7b3e281 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Berkay=20K=C3=B6sebay?= Date: Tue, 1 Dec 2026 18:02:08 +0100 Subject: [PATCH 06/17] shell: add a lite rendering profile for GLES2 hardware MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Assisted-by: LLM Signed-off-by: Berkay Kösebay --- desktop/shell/shell/Commons/Lite.qml | 12 +++++++++++ desktop/shell/shell/Commons/Style.qml | 4 +++- desktop/shell/shell/Commons/qmldir | 1 + desktop/shell/shell/Ui/Button.qml | 2 +- desktop/shell/shell/Ui/MultiSelect.qml | 2 +- desktop/shell/shell/launcher/Launcher.qml | 2 +- .../shell/plugins/background/Background.qml | 4 ++-- desktop/shell/shell/plugins/bar/Bar.qml | 8 ++++---- .../shell/shell/plugins/bar/widgets/Tray.qml | 6 +++--- .../shell/shell/plugins/dock/DockWindow.qml | 2 +- desktop/shell/shell/plugins/flash/Flash.qml | 2 +- .../plugins/image-picker/ImagePicker.qml | 7 ++++--- desktop/shell/shell/plugins/lock/LockView.qml | 10 +++++----- .../shell/plugins/notifications/Toast.qml | 7 ++++--- .../plugins/panels/dropbox/DropboxIcon.qml | 2 +- .../shell/plugins/panels/elsewhen/Avatar.qml | 20 +++++++++++-------- .../plugins/panels/elsewhen/DaylightStrip.qml | 3 ++- .../shell/plugins/panels/power/Panel.qml | 2 +- .../shell/plugins/panels/tailscale/Panel.qml | 4 ++-- .../shell/plugins/panels/weather/Panel.qml | 2 +- .../plugins/services/media/BarWidget.qml | 2 +- .../shell/shell/services/BackgroundIntro.qml | 2 +- .../shell/shell/settings/SettingsWindow.qml | 2 +- 23 files changed, 65 insertions(+), 43 deletions(-) create mode 100644 desktop/shell/shell/Commons/Lite.qml diff --git a/desktop/shell/shell/Commons/Lite.qml b/desktop/shell/shell/Commons/Lite.qml new file mode 100644 index 00000000..b342f6e9 --- /dev/null +++ b/desktop/shell/shell/Commons/Lite.qml @@ -0,0 +1,12 @@ +pragma Singleton + +import QtQuick +import Quickshell + +QtObject { + readonly property bool enabled: Quickshell.env("OMARCHY_SHELL_LITE") === "1" + + function duration(ms) { + return enabled ? Math.min(ms, 80) : ms + } +} diff --git a/desktop/shell/shell/Commons/Style.qml b/desktop/shell/shell/Commons/Style.qml index 6016cce4..68f2f375 100644 --- a/desktop/shell/shell/Commons/Style.qml +++ b/desktop/shell/shell/Commons/Style.qml @@ -361,9 +361,11 @@ QtObject { // them off for machines that render on the CPU. Every shell animation runs // for Style.duration(ms), which is then 0, so nothing is drawn in between. property bool reduceMotion: false + // Looping pulses and marquees should stay still at lite transition speeds. + readonly property bool animateLoops: !reduceMotion && !Commons.Lite.enabled function duration(ms) { - return reduceMotion ? 0 : ms + return reduceMotion ? 0 : Commons.Lite.duration(ms) } // A strong ease-out, for anything appearing or moving in answer to the diff --git a/desktop/shell/shell/Commons/qmldir b/desktop/shell/shell/Commons/qmldir index d16656ae..e47a9482 100644 --- a/desktop/shell/shell/Commons/qmldir +++ b/desktop/shell/shell/Commons/qmldir @@ -6,6 +6,7 @@ singleton I18n 1.0 I18n.qml singleton InputDevices 1.0 InputDevices.qml singleton IpcRegistry 1.0 IpcRegistry.qml singleton InputMethodState 1.0 InputMethodState.qml +singleton Lite 1.0 Lite.qml singleton Startup 1.0 Startup.qml singleton Style 1.0 Style.qml singleton TimeZone 1.0 TimeZone.qml diff --git a/desktop/shell/shell/Ui/Button.qml b/desktop/shell/shell/Ui/Button.qml index 5d34baa1..27cf8a9c 100644 --- a/desktop/shell/shell/Ui/Button.qml +++ b/desktop/shell/shell/Ui/Button.qml @@ -196,7 +196,7 @@ BorderSurface { to: 360 duration: Style.duration(900) loops: Animation.Infinite - running: root.iconSpinning && !Style.reduceMotion + running: root.iconSpinning && Style.animateLoops } } diff --git a/desktop/shell/shell/Ui/MultiSelect.qml b/desktop/shell/shell/Ui/MultiSelect.qml index 4e3a8d71..81d0feb8 100644 --- a/desktop/shell/shell/Ui/MultiSelect.qml +++ b/desktop/shell/shell/Ui/MultiSelect.qml @@ -472,7 +472,7 @@ Item { font.pixelSize: Style.font.body RotationAnimator on rotation { - running: root.loadingOptions && !Style.reduceMotion + running: root.loadingOptions && Style.animateLoops from: 0; to: 360 duration: Style.duration(800) loops: Animation.Infinite diff --git a/desktop/shell/shell/launcher/Launcher.qml b/desktop/shell/shell/launcher/Launcher.qml index f7323243..939dd7b2 100644 --- a/desktop/shell/shell/launcher/Launcher.qml +++ b/desktop/shell/shell/launcher/Launcher.qml @@ -693,7 +693,7 @@ Item { if (root.menu) root.menu.evaluateGuards() // A wallpaper changed since: the next open shows it. wallpaperProc.running = true - opaqueProc.running = true + if (!Lite.enabled) opaqueProc.running = true root.endSearch() root.pageIndex = 0 root.zone = "" diff --git a/desktop/shell/shell/plugins/background/Background.qml b/desktop/shell/shell/plugins/background/Background.qml index 27b0f609..fcc7d2e3 100644 --- a/desktop/shell/shell/plugins/background/Background.qml +++ b/desktop/shell/shell/plugins/background/Background.qml @@ -131,7 +131,7 @@ Item { // Video frames are not fed through the image-only reveal stack. Switching // instantly also avoids decoding two full videos during a transition. - if (instant || Quickshell.env("QT_QUICK_BACKEND") === "software" || !displayedBackground || isVideo(path) || isVideo(displayedBackground)) { + if (instant || Lite.enabled || Quickshell.env("QT_QUICK_BACKEND") === "software" || !displayedBackground || isVideo(path) || isVideo(displayedBackground)) { oldBackground = "" incomingBackground = "" preparedBackground = "" @@ -549,7 +549,7 @@ Item { id: revealMask anchors.fill: parent visible: false - layer.enabled: true + layer.enabled: !Lite.enabled readonly property real slant: -0.18 readonly property real centerTop: width / 2 - slant * height / 2 diff --git a/desktop/shell/shell/plugins/bar/Bar.qml b/desktop/shell/shell/plugins/bar/Bar.qml index f858e56a..d9a5409d 100644 --- a/desktop/shell/shell/plugins/bar/Bar.qml +++ b/desktop/shell/shell/plugins/bar/Bar.qml @@ -812,8 +812,8 @@ Item { // A bar going clear waits for its text color before dropping its // background, so a glassy one stays glassy until then rather than // flashing opaque. Once clear, transparent wins over a stale glassy. - if (look !== "none") glassy = look === "glassy" - if (look !== glassSyncedLook) { + if (look !== "none") glassy = !Lite.enabled && look === "glassy" + if (!Lite.enabled && look !== glassSyncedLook) { glassSyncedLook = look Util.execDetached("omarchy-bar sync-glass") } @@ -1214,7 +1214,7 @@ Item { // whole room in 120ms. // Armed for removal, there is no target: every place gives its room up. function fadeDragRoom(seconds) { - var duration = Style.duration(120) + var duration = Style.reduceMotion ? 0 : 120 var step = duration > 0 ? seconds * 1000 / duration : 1 var target = barDragRemoveArmed ? "" : dragShareKey(barDragRoom) barDragShares = BarModel.fadeShares(barDragShares, target, step) @@ -2211,7 +2211,7 @@ Item { // Built with the ghost's surface rather than at the release, which // would cost the poof its first frames while the effect sets up. // Until the poof plays the cloud holds nothing to draw. - layer.enabled: ghostWindow.visible + layer.enabled: !Lite.enabled && ghostWindow.visible layer.effect: MultiEffect { blurEnabled: true blur: 0.6 diff --git a/desktop/shell/shell/plugins/bar/widgets/Tray.qml b/desktop/shell/shell/plugins/bar/widgets/Tray.qml index 1f49070c..7eb1b97d 100644 --- a/desktop/shell/shell/plugins/bar/widgets/Tray.qml +++ b/desktop/shell/shell/plugins/bar/widgets/Tray.qml @@ -329,7 +329,7 @@ BarWidget { x: root.fixedAtStart ? root.sectionExtent : 0 anchors.verticalCenter: parent.verticalCenter spacing: root.trayItemGap - layer.enabled: true + layer.enabled: !Lite.enabled Repeater { model: root.drawerItems @@ -420,7 +420,7 @@ BarWidget { y: root.fixedAtStart ? root.sectionExtent : 0 anchors.horizontalCenter: parent.horizontalCenter spacing: root.trayItemGap - layer.enabled: true + layer.enabled: !Lite.enabled Repeater { model: root.drawerItems @@ -838,7 +838,7 @@ BarWidget { component TrayIcon: Item { id: trayIconRoot required property var icon - readonly property bool symbolic: root.iconIsSymbolic(icon) + readonly property bool symbolic: !Lite.enabled && root.iconIsSymbolic(icon) Image { id: trayIconImage diff --git a/desktop/shell/shell/plugins/dock/DockWindow.qml b/desktop/shell/shell/plugins/dock/DockWindow.qml index 66ad8cc3..9617e9a4 100644 --- a/desktop/shell/shell/plugins/dock/DockWindow.qml +++ b/desktop/shell/shell/plugins/dock/DockWindow.qml @@ -511,7 +511,7 @@ PanelWindow { // With animations off it holds still rather than spinning through // zero-length steps. SequentialAnimation { - running: appSlot.launching && !Style.reduceMotion + running: appSlot.launching && Style.animateLoops loops: Animation.Infinite onRunningChanged: if (!running) appSlot.pulse = 1 diff --git a/desktop/shell/shell/plugins/flash/Flash.qml b/desktop/shell/shell/plugins/flash/Flash.qml index 52698952..5da39a95 100644 --- a/desktop/shell/shell/plugins/flash/Flash.qml +++ b/desktop/shell/shell/plugins/flash/Flash.qml @@ -49,7 +49,7 @@ Item { SequentialAnimation { id: flashAnimation PropertyAction { target: white; property: "opacity"; value: 0.95 } - NumberAnimation { target: white; property: "opacity"; to: 0; duration: 500; easing.type: Easing.InOutSine } + NumberAnimation { target: white; property: "opacity"; to: 0; duration: Lite.duration(500); easing.type: Easing.InOutSine } onFinished: root.opened = false } } diff --git a/desktop/shell/shell/plugins/image-picker/ImagePicker.qml b/desktop/shell/shell/plugins/image-picker/ImagePicker.qml index 1178eab9..ff4b3869 100644 --- a/desktop/shell/shell/plugins/image-picker/ImagePicker.qml +++ b/desktop/shell/shell/plugins/image-picker/ImagePicker.qml @@ -779,7 +779,7 @@ Item { y: selected ? 0 : (root.expandedHeight - root.sliceHeight) / 2 z: selected ? 100 : 50 - Math.min(Math.abs(relativeIndex), 40) - readonly property real skAbs: Math.abs(root.skewOffset) + readonly property real skAbs: Lite.enabled ? 0 : Math.abs(root.skewOffset) readonly property real topLeft: root.skewOffset >= 0 ? skAbs : 0 readonly property real topRight: root.skewOffset >= 0 ? width : width - skAbs readonly property real bottomRight: root.skewOffset >= 0 ? width - skAbs : width @@ -789,7 +789,7 @@ Item { id: maskShape anchors.fill: parent visible: false - layer.enabled: true + layer.enabled: !Lite.enabled Shape { anchors.fill: parent @@ -809,7 +809,8 @@ Item { Item { anchors.fill: parent - layer.enabled: true + layer.enabled: !Lite.enabled + clip: Lite.enabled layer.smooth: true layer.effect: MultiEffect { maskEnabled: true diff --git a/desktop/shell/shell/plugins/lock/LockView.qml b/desktop/shell/shell/plugins/lock/LockView.qml index ae5a302e..1bb58fa4 100644 --- a/desktop/shell/shell/plugins/lock/LockView.qml +++ b/desktop/shell/shell/plugins/lock/LockView.qml @@ -72,7 +72,7 @@ Item { // A soft shadow in the theme's background under the clock, the slots and // the failure: readable on any wallpaper without darkening all of it. The // GPU draws it; software rendering goes without. - readonly property bool gpu: Quickshell.env("QT_QUICK_BACKEND") !== "software" + readonly property bool drawShadows: !Lite.enabled && Quickshell.env("QT_QUICK_BACKEND") !== "software" // A soft dark shadow (the theme background at 80 %, about 8 px of blur, // 1 px down): text stays readable over busy parts of the wallpaper. component Shade: MultiEffect { @@ -249,7 +249,7 @@ Item { // ------------------------------------------------------ clock Column { id: clockBlock - layer.enabled: root.gpu + layer.enabled: root.drawShadows layer.effect: Shade {} spacing: Style.space(6) // x, not an anchor: an anchor let go on rotation keeps its place. @@ -415,7 +415,7 @@ Item { Grid { id: keypad visible: root.touchPin - layer.enabled: root.gpu + layer.enabled: root.drawShadows layer.effect: Shade {} columns: 3 rowSpacing: root.pt("keyGap") @@ -477,7 +477,7 @@ Item { visible: root.touchPin width: parent.width height: root.pt("slotRow") - layer.enabled: root.gpu + layer.enabled: root.drawShadows layer.effect: Shade {} Row { anchors.horizontalCenter: parent.horizontalCenter @@ -507,7 +507,7 @@ Item { Text { id: failureLine objectName: "lockFailure" - layer.enabled: root.gpu && text.length > 0 + layer.enabled: root.drawShadows && text.length > 0 layer.effect: Shade {} width: parent.width // Above the keys, the line is the gap to them: as wide as the one diff --git a/desktop/shell/shell/plugins/notifications/Toast.qml b/desktop/shell/shell/plugins/notifications/Toast.qml index e31ca7f0..db49e513 100644 --- a/desktop/shell/shell/plugins/notifications/Toast.qml +++ b/desktop/shell/shell/plugins/notifications/Toast.qml @@ -421,7 +421,7 @@ Item { Rectangle { id: bannerShadow - visible: card.banner && card.gpu + visible: !Lite.enabled && card.banner && card.gpu anchors.fill: bannerBox color: "black" layer.enabled: visible @@ -811,7 +811,8 @@ Item { // rounded like the card, only when the theme rounds at all. readonly property bool rounded: thumb.photo && Style.cornerRadius > 0 opacity: thumb.mono ? 0.85 : 1 - layer.enabled: visible && (thumb.mono || rounded) + clip: Lite.enabled && thumb.photo + layer.enabled: !Lite.enabled && visible && (thumb.mono || rounded) layer.effect: MultiEffect { maskEnabled: picture.rounded maskSource: mask @@ -825,7 +826,7 @@ Item { id: mask anchors.fill: parent visible: false - layer.enabled: true + layer.enabled: !Lite.enabled radius: Style.cornerRadius color: "black" } diff --git a/desktop/shell/shell/plugins/panels/dropbox/DropboxIcon.qml b/desktop/shell/shell/plugins/panels/dropbox/DropboxIcon.qml index 5f0d411d..bf64bbb0 100644 --- a/desktop/shell/shell/plugins/panels/dropbox/DropboxIcon.qml +++ b/desktop/shell/shell/plugins/panels/dropbox/DropboxIcon.qml @@ -19,7 +19,7 @@ Item { Shape { anchors.fill: parent antialiasing: true - layer.enabled: true + layer.enabled: !Lite.enabled layer.samples: 4 scale: root.artworkScale diff --git a/desktop/shell/shell/plugins/panels/elsewhen/Avatar.qml b/desktop/shell/shell/plugins/panels/elsewhen/Avatar.qml index b3acd3f5..13fd5f16 100644 --- a/desktop/shell/shell/plugins/panels/elsewhen/Avatar.qml +++ b/desktop/shell/shell/plugins/panels/elsewhen/Avatar.qml @@ -53,7 +53,8 @@ Item { Image { id: picture anchors.fill: parent - visible: false + visible: Lite.enabled && avatar.pictured + clip: Lite.enabled source: avatar.source === "" ? "" : "file://" + avatar.source + "?v=" + avatar.stamp sourceSize.width: Math.ceil(avatar.size * Screen.devicePixelRatio) sourceSize.height: Math.ceil(avatar.size * Screen.devicePixelRatio) @@ -67,7 +68,7 @@ Item { id: disc anchors.fill: parent visible: false - layer.enabled: true + layer.enabled: !Lite.enabled Rectangle { anchors.fill: parent @@ -76,13 +77,16 @@ Item { } } - MultiEffect { + Loader { anchors.fill: parent + active: !Lite.enabled visible: avatar.pictured - source: picture - maskEnabled: true - maskSource: disc - maskThresholdMin: 0.5 - maskSpreadAtMin: 1.0 + sourceComponent: MultiEffect { + source: picture + maskEnabled: true + maskSource: disc + maskThresholdMin: 0.5 + maskSpreadAtMin: 1.0 + } } } diff --git a/desktop/shell/shell/plugins/panels/elsewhen/DaylightStrip.qml b/desktop/shell/shell/plugins/panels/elsewhen/DaylightStrip.qml index 205ad9d2..cd64bbea 100644 --- a/desktop/shell/shell/plugins/panels/elsewhen/DaylightStrip.qml +++ b/desktop/shell/shell/plugins/panels/elsewhen/DaylightStrip.qml @@ -123,13 +123,14 @@ Item { color: strip.foreground } - Behavior on x { NumberAnimation { duration: Style.duration(400); easing.type: Easing.OutCubic } } + Behavior on x { NumberAnimation { duration: scrubArea.pressed && !Style.reduceMotion ? 400 : Style.duration(400); easing.type: Easing.OutCubic } } } } // Scrub, or Shift-click the moon to run its phase show. The arrows below are // later siblings, so their taps never reach this. MouseArea { + id: scrubArea anchors.fill: parent cursorShape: Qt.SizeHorCursor preventStealing: true diff --git a/desktop/shell/shell/plugins/panels/power/Panel.qml b/desktop/shell/shell/plugins/panels/power/Panel.qml index 4f783ff9..5976ac69 100644 --- a/desktop/shell/shell/plugins/panels/power/Panel.qml +++ b/desktop/shell/shell/plugins/panels/power/Panel.qml @@ -457,7 +457,7 @@ Panel { // Subtle pulse while charging — visible signal that energy is flowing in. SequentialAnimation on opacity { - running: root.charging && !root.fullyCharged && root.opened && !Style.reduceMotion + running: root.charging && !root.fullyCharged && root.opened && Style.animateLoops loops: Animation.Infinite alwaysRunToEnd: true NumberAnimation { from: 1.0; to: 0.55; duration: Style.duration(950); easing.type: Easing.InOutSine } diff --git a/desktop/shell/shell/plugins/panels/tailscale/Panel.qml b/desktop/shell/shell/plugins/panels/tailscale/Panel.qml index 9ba5fb50..961cb9ee 100644 --- a/desktop/shell/shell/plugins/panels/tailscale/Panel.qml +++ b/desktop/shell/shell/plugins/panels/tailscale/Panel.qml @@ -1211,7 +1211,7 @@ Panel { opacity: accountRow.switchingAccount || accountRow.renameInFlight ? 0.45 : 1.0 SequentialAnimation on opacity { - running: (accountRow.switchingAccount || accountRow.renameInFlight) && !Style.reduceMotion + running: (accountRow.switchingAccount || accountRow.renameInFlight) && Style.animateLoops NumberAnimation { to: 1.0; duration: Style.duration(420); easing.type: Easing.InOutQuad } NumberAnimation { to: 0.45; duration: Style.duration(420); easing.type: Easing.InOutQuad } loops: Animation.Infinite @@ -1455,7 +1455,7 @@ Panel { anchors.verticalCenter: parent.verticalCenter NumberAnimation on rotation { - running: exitNodeRow.settingExitNode && !Style.reduceMotion + running: exitNodeRow.settingExitNode && Style.animateLoops from: 0 to: 360 duration: Style.duration(900) diff --git a/desktop/shell/shell/plugins/panels/weather/Panel.qml b/desktop/shell/shell/plugins/panels/weather/Panel.qml index bdf8ac50..48613a56 100644 --- a/desktop/shell/shell/plugins/panels/weather/Panel.qml +++ b/desktop/shell/shell/plugins/panels/weather/Panel.qml @@ -709,7 +709,7 @@ Panel { font.pixelSize: Style.font.bodySmall RotationAnimator on rotation { - running: root.savingLocation && !Style.reduceMotion + running: root.savingLocation && Style.animateLoops from: 0; to: 360 duration: Style.duration(800) loops: Animation.Infinite diff --git a/desktop/shell/shell/plugins/services/media/BarWidget.qml b/desktop/shell/shell/plugins/services/media/BarWidget.qml index ea4c8104..4be1e7b6 100644 --- a/desktop/shell/shell/plugins/services/media/BarWidget.qml +++ b/desktop/shell/shell/plugins/services/media/BarWidget.qml @@ -69,7 +69,7 @@ BarWidget { // track is playing and the bar is on screen to show it. NumberAnimation on x { id: scrollAnim - running: labelText.needsScroll && root.isPlaying && root.visible && !root.bar.barHidden && !root.popupOpen && !root.bar.vertical && !Style.reduceMotion + running: labelText.needsScroll && root.isPlaying && root.visible && !root.bar.barHidden && !root.popupOpen && !root.bar.vertical && Style.animateLoops // Stopped, the title reads from its start again. onRunningChanged: if (!running) labelText.x = 0 loops: Animation.Infinite diff --git a/desktop/shell/shell/services/BackgroundIntro.qml b/desktop/shell/shell/services/BackgroundIntro.qml index bc54a39c..7d5721f4 100644 --- a/desktop/shell/shell/services/BackgroundIntro.qml +++ b/desktop/shell/shell/services/BackgroundIntro.qml @@ -126,7 +126,7 @@ Item { // short, and the new still may still be decoding then. function finishTheme(token, cut) { if (token !== themeToken) return - themeCut = !!cut + themeCut = !Lite.enabled && !!cut if (backgroundReady || !backgroundService) revealTheme() else themeFinishing = true } diff --git a/desktop/shell/shell/settings/SettingsWindow.qml b/desktop/shell/shell/settings/SettingsWindow.qml index 4f024151..5cb7cfe9 100644 --- a/desktop/shell/shell/settings/SettingsWindow.qml +++ b/desktop/shell/shell/settings/SettingsWindow.qml @@ -102,7 +102,7 @@ FloatingWindow { property bool navPhone: false property var navPicture: null function navigate(direction, change) { - if (!win.gpu || direction === 0 || content.width <= 0 || navAnim.running || navWait.running || win.navHeld) { + if (Lite.enabled || !win.gpu || direction === 0 || content.width <= 0 || navAnim.running || navWait.running || win.navHeld) { if (navAnim.running) navAnim.complete() change() return From b14328cee08eb9f9c177258608425c13a83a3f22 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Berkay=20K=C3=B6sebay?= Date: Tue, 1 Dec 2026 18:02:08 +0100 Subject: [PATCH 07/17] session: select the lite shell after a successful apple-sgx probe MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Assisted-by: LLM Signed-off-by: Berkay Kösebay --- desktop/configuration/login-session | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/desktop/configuration/login-session b/desktop/configuration/login-session index 7dab28db..749f143e 100644 --- a/desktop/configuration/login-session +++ b/desktop/configuration/login-session @@ -39,7 +39,8 @@ export LIBGL_ALWAYS_SOFTWARE=1 LIBSEAT_BACKEND=seatd MOZ_ENABLE_WAYLAND=1 # draws OpenGL ES 2 on it: there Labwc draws on wlroots' GLES2 renderer on that # card and applications get the GPU's OpenGL ES, once gpu-probe has drawn a frame # that way in this boot. The shell keeps Qt's software renderer: the SGX has -# OpenGL ES 2 only, and Qt Quick on it is untested. +# OpenGL ES 2 only, and Qt Quick on it is untested. The lite shell avoids +# offscreen passes for masks and shadows on this tile-based GPU. gpu= gpu_driver= for node in /sys/class/drm/renderD*; do driver=$(basename "$(readlink -f "$node/device/driver")") @@ -105,7 +106,7 @@ if [[ -n $gpu ]]; then export "${gpu_desktop[@]}" MESA_DISK_CACHE_SINGLE_FILE=1 unset LIBGL_ALWAYS_SOFTWARE QT_QUICK_BACKEND export QSG_NO_DEPTH_BUFFER=1 QSG_NO_STENCIL_BUFFER=1 - if [[ $gpu_driver == apple-sgx ]]; then export QT_QUICK_BACKEND=software; fi + if [[ $gpu_driver == apple-sgx ]]; then export QT_QUICK_BACKEND=software OMARCHY_SHELL_LITE=1; fi else # The probe runs with the environment the desktop would get. The login # waits for it 10 s at most and does not depend on it ending: a probe @@ -129,7 +130,7 @@ if [[ -n $gpu ]]; then # keeps a full-size depth/stencil buffer in memory that the UI never # reads (on the iPod touch 6 that is about 50 MB in the shell alone). export QSG_NO_DEPTH_BUFFER=1 QSG_NO_STENCIL_BUFFER=1 - if [[ $gpu_driver == apple-sgx ]]; then export QT_QUICK_BACKEND=software; fi + if [[ $gpu_driver == apple-sgx ]]; then export QT_QUICK_BACKEND=software OMARCHY_SHELL_LITE=1; fi if [[ -n $gpu_cache ]]; then mkdir -p "$(dirname "$gpu_cache")" 2>/dev/null || true printf '%s\n%s\n' "$gpu_key" "$gpu_detail" >"$gpu_cache.tmp" 2>/dev/null && From 95f0f625fa4a327252313f71f33855f3be33dc6c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Berkay=20K=C3=B6sebay?= Date: Tue, 1 Dec 2026 18:02:09 +0100 Subject: [PATCH 08/17] shell: close covered centers without starting processes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Assisted-by: LLM Signed-off-by: Berkay Kösebay --- desktop/shell/bin/omarchy-bottom-swipe | 4 ++-- desktop/shell/bin/omarchy-home-button | 4 ++-- desktop/shell/bin/omarchy-keyboard | 8 +++++++ desktop/shell/shell/Ui/KeyboardSession.qml | 15 ++++++++++++ desktop/shell/shell/Ui/qmldir | 1 + .../shell/controlcenter/ControlCenter.qml | 2 +- .../notificationcenter/NotificationCenter.qml | 11 +++------ desktop/shell/shell/shell.qml | 23 ++++++++----------- 8 files changed, 42 insertions(+), 26 deletions(-) create mode 100644 desktop/shell/shell/Ui/KeyboardSession.qml diff --git a/desktop/shell/bin/omarchy-bottom-swipe b/desktop/shell/bin/omarchy-bottom-swipe index 3d4cbb06..7e2d143b 100755 --- a/desktop/shell/bin/omarchy-bottom-swipe +++ b/desktop/shell/bin/omarchy-bottom-swipe @@ -9,10 +9,10 @@ # still come here over one (an older labwc), it puts that one away. Over an # app it brings the keyboard up. runtime="${XDG_RUNTIME_DIR:-/run/user/$UID}" -if [[ -e $runtime/omarchy-notification-center-open ]]; then +if [[ -s $runtime/omarchy-notification-center-open ]]; then exec omarchy-shell omarchy.notificationcenter close fi -if [[ -e $runtime/omarchy-control-center-open ]]; then +if [[ -s $runtime/omarchy-control-center-open ]]; then exec omarchy-shell omarchy.controlcenter close fi exec omarchy-keyboard show diff --git a/desktop/shell/bin/omarchy-home-button b/desktop/shell/bin/omarchy-home-button index 311037e3..fd7236c8 100755 --- a/desktop/shell/bin/omarchy-home-button +++ b/desktop/shell/bin/omarchy-home-button @@ -18,12 +18,12 @@ now=$(( ${EPOCHREALTIME/[.,]/} / 1000 )) # The control center goes away at once. A single press then opens nothing # else; a second one still opens the overview. control_center= -if [[ -e $runtime/omarchy-control-center-open ]]; then +if [[ -s $runtime/omarchy-control-center-open ]]; then control_center=1 omarchy-shell omarchy.controlcenter close >/dev/null 2>&1 & fi # The notification center likewise. -if [[ -e $runtime/omarchy-notification-center-open ]]; then +if [[ -s $runtime/omarchy-notification-center-open ]]; then control_center=1 omarchy-shell omarchy.notificationcenter close >/dev/null 2>&1 & fi diff --git a/desktop/shell/bin/omarchy-keyboard b/desktop/shell/bin/omarchy-keyboard index 67ea0b1c..9c586068 100644 --- a/desktop/shell/bin/omarchy-keyboard +++ b/desktop/shell/bin/omarchy-keyboard @@ -308,6 +308,14 @@ def run(): def main(mode): + if mode in ("hold-while-open", "show-while-open"): + opening, closing = ("hold", "release") if mode.startswith("hold") else ("show", "hide") + main(opening) + try: + sys.stdin.buffer.read(1) + finally: + main(closing) + return if mode == "toggle": mode = "hide" if visible() else "show" if mode == "show": diff --git a/desktop/shell/shell/Ui/KeyboardSession.qml b/desktop/shell/shell/Ui/KeyboardSession.qml new file mode 100644 index 00000000..b6f66689 --- /dev/null +++ b/desktop/shell/shell/Ui/KeyboardSession.qml @@ -0,0 +1,15 @@ +import Quickshell +import Quickshell.Io + +// Closing the input pipe releases the keyboard even when a different surface +// (such as the launcher) takes over before the opening command has run. +Process { + id: session + required property string action + required property bool active + command: [(Quickshell.env("OMARCHY_PATH") || "/usr/share/omarchy") + "/bin/omarchy-keyboard", action + "-while-open"] + stdinEnabled: active + function startIfActive() { if (active && !running) running = true } + onActiveChanged: if (active) Qt.callLater(startIfActive) + onExited: function(code) { if (!code && active) Qt.callLater(startIfActive) } +} diff --git a/desktop/shell/shell/Ui/qmldir b/desktop/shell/shell/Ui/qmldir index 18e08334..a2a5cdae 100644 --- a/desktop/shell/shell/Ui/qmldir +++ b/desktop/shell/shell/Ui/qmldir @@ -15,6 +15,7 @@ Dropdown 1.0 Dropdown.qml FilterInput 1.0 FilterInput.qml IconContentBounds 1.0 IconContentBounds.qml KeyboardPanel 1.0 KeyboardPanel.qml +KeyboardSession 1.0 KeyboardSession.qml LazyKeyboardPanel 1.0 LazyKeyboardPanel.qml MultiSelect 1.0 MultiSelect.qml NumberField 1.0 NumberField.qml diff --git a/desktop/shell/shell/controlcenter/ControlCenter.qml b/desktop/shell/shell/controlcenter/ControlCenter.qml index d06dceb2..e63b56f0 100644 --- a/desktop/shell/shell/controlcenter/ControlCenter.qml +++ b/desktop/shell/shell/controlcenter/ControlCenter.qml @@ -31,7 +31,7 @@ Item { // Over an app it takes the keyboard: the app's text field going off must // not put the on-screen keyboard away, which stays, under the control // center (omarchy-keyboard hold … release). - onMappedChanged: run([omarchy("omarchy-keyboard"), mapped ? "hold" : "release"]) + KeyboardSession { action: "hold"; active: root.mapped } property real reveal: 0 readonly property bool gpu: Quickshell.env("QT_QUICK_BACKEND") !== "software" diff --git a/desktop/shell/shell/notificationcenter/NotificationCenter.qml b/desktop/shell/shell/notificationcenter/NotificationCenter.qml index 4f0f22db..e5a909a2 100644 --- a/desktop/shell/shell/notificationcenter/NotificationCenter.qml +++ b/desktop/shell/shell/notificationcenter/NotificationCenter.qml @@ -414,19 +414,14 @@ Item { // finger) lies over the center then, and goes with the reply. property bool typing: false property bool replyKeyboard: false + KeyboardSession { action: "show"; active: root.replyKeyboard } function beginReply(byTouch) { root.typing = true - if (byTouch && !root.replyKeyboard) { - root.replyKeyboard = true - Quickshell.execDetached([(Quickshell.env("OMARCHY_PATH") || "/usr/share/omarchy") + "/bin/omarchy-keyboard", "show"]) - } + if (byTouch) root.replyKeyboard = true } function endReply() { root.typing = false - if (root.replyKeyboard) { - root.replyKeyboard = false - Quickshell.execDetached([(Quickshell.env("OMARCHY_PATH") || "/usr/share/omarchy") + "/bin/omarchy-keyboard", "hide"]) - } + root.replyKeyboard = false keyCatcher.forceActiveFocus() } diff --git a/desktop/shell/shell/shell.qml b/desktop/shell/shell/shell.qml index 165221df..d348615f 100644 --- a/desktop/shell/shell/shell.qml +++ b/desktop/shell/shell/shell.qml @@ -63,20 +63,17 @@ ShellRoot { function pullTo(distance) { if (item) item.pullTo(distance) } function endPull(velocity) { if (item) item.endPull(velocity) } - // Clear a stale Home-button marker on shell restart. Serialize writes - // so an open arriving during that initial removal wins. - readonly property string openNote: (Quickshell.env("XDG_RUNTIME_DIR") || "/tmp") + "/" + noteName - property bool noteWritten: true + // Home and the bottom swipe read a nonempty marker while this center is open. + FileView { + id: note + path: (Quickshell.env("XDG_RUNTIME_DIR") || "/tmp") + "/" + center.noteName + blockAllReads: true + blockWrites: true + printErrors: false + } function writeOpenNote() { - if (noteWriter.running || noteWritten === opened) return - noteWriter.writing = opened - noteWriter.command = opened ? ["touch", openNote] : ["rm", "-f", openNote] - noteWriter.running = true - } - Process { - id: noteWriter - property bool writing: false - onExited: { center.noteWritten = writing; center.writeOpenNote() } + var value = opened ? "1" : "" + if (note.text() !== value) note.setText(value) } Component.onCompleted: writeOpenNote() onOpenedChanged: writeOpenNote() From 5f4d756c8c1afc2dc3884d4b8ad674403bd39be3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Berkay=20K=C3=B6sebay?= Date: Tue, 1 Dec 2026 18:02:09 +0100 Subject: [PATCH 09/17] launcher: refresh applications, menu guards and backdrops on change MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Assisted-by: LLM Signed-off-by: Berkay Kösebay --- .../shell/bin/omarchy-toggle-launcher-frosted | 2 +- desktop/shell/shell/launcher/Launcher.qml | 145 +++--------------- desktop/shell/shell/launcher/LauncherModel.js | 10 ++ desktop/shell/shell/launcher/RecentApps.qml | 1 - desktop/shell/shell/plugins/bar/Bar.qml | 1 + .../bar/indicators/ScreenRecording.qml | 1 + desktop/shell/shell/plugins/dock/AppGrid.qml | 55 ++----- desktop/shell/shell/plugins/menu/Menu.qml | 32 ++++ desktop/shell/shell/services/AppLibrary.qml | 53 +++++-- .../shell/shell/services/LauncherBackdrop.qml | 129 ++++++++++++++++ desktop/shell/shell/shell.qml | 2 +- 11 files changed, 247 insertions(+), 184 deletions(-) create mode 100644 desktop/shell/shell/services/LauncherBackdrop.qml diff --git a/desktop/shell/bin/omarchy-toggle-launcher-frosted b/desktop/shell/bin/omarchy-toggle-launcher-frosted index 1bf41ee8..3279be93 100755 --- a/desktop/shell/bin/omarchy-toggle-launcher-frosted +++ b/desktop/shell/bin/omarchy-toggle-launcher-frosted @@ -2,7 +2,7 @@ # omarchy:summary=Show the launcher on the frosted wallpaper, or on the theme's plain background # Opaque by default. Turned on, the launcher-frosted flag says so; the -# launcher reads it each time it opens. +# shell watches it for changes. set -euo pipefail [[ $# == 0 ]] || { echo 'Usage: omarchy-toggle-launcher-frosted' >&2; exit 2; } toggles=$HOME/.local/state/omarchy/toggles diff --git a/desktop/shell/shell/launcher/Launcher.qml b/desktop/shell/shell/launcher/Launcher.qml index 939dd7b2..3679b665 100644 --- a/desktop/shell/shell/launcher/Launcher.qml +++ b/desktop/shell/shell/launcher/Launcher.qml @@ -39,8 +39,7 @@ Item { property int cursor: 0 property bool cursorShown: false - property var apps: [] - property bool appsStale: true + readonly property var apps: appLibrary ? appLibrary.entries : [] property var recentFiles: [] property double now: Date.now() @@ -54,15 +53,17 @@ Item { // ------------------------------------------------------------- geometry - readonly property real screenWidth: panel.width - readonly property real screenHeight: panel.height + // The layer surface is recreated on show. Its transient geometry must not + // repaginate the phone grid and discard every icon between opens. + readonly property var layoutScreen: panel.targetScreen || panel.focusedScreen() + readonly property real screenWidth: layoutScreen ? layoutScreen.width : 0 + readonly property real screenHeight: layoutScreen ? layoutScreen.height : 0 readonly property bool phone: Model.isPhone(screenWidth, screenHeight) - readonly property bool landscape: screenWidth > screenHeight readonly property int columns: Model.columnsFor(screenWidth, screenHeight, phone) - readonly property int sideMargin: phone ? Style.space(16) : (landscape ? Style.space(56) : Style.space(32)) + readonly property int sideMargin: Model.sideMargin(screenWidth, screenHeight, Style) readonly property int contentWidth: Math.max(0, screenWidth - sideMargin * 2) readonly property real cellWidth: contentWidth / Math.max(1, columns) - readonly property int iconSize: Math.round(Math.min(Style.space(56), cellWidth * 0.6)) + readonly property int iconSize: Model.iconSize(screenWidth, screenHeight, Style) readonly property int labelLines: 2 readonly property int cellHeight: Style.space(10) + iconSize + Style.spacing.md + Math.ceil(labelMetrics.height) * labelLines + Style.space(10) readonly property int barInset: Style.bar.sizeHorizontal @@ -560,105 +561,9 @@ Item { enabled: root.gpu && root.opened NumberAnimation { duration: Style.duration(180); easing.type: Easing.OutCubic } } - // The wallpaper the desktop shows (a video one leaves the plain colour). - property string wallpaper: "" - - Process { - id: wallpaperProc - command: ["readlink", "-f", (Quickshell.env("HOME") || "") + "/.local/state/omarchy/current/background"] - stdout: StdioCollector { - onStreamFinished: { - var path = text.trim() - root.wallpaper = path && !Util.isVideoPath(path) ? path : "" - } - } - } - - - // Orchard: on the theme's plain background by default (no blurred copy - // is made then); Trigger > Toggle > Frosted Launcher puts it on the frosted - // wallpaper. Read as it opens. - property bool opaque: true - Process { - id: opaqueProc - command: ["omarchy-toggle-enabled", "launcher-frosted"] - onExited: function(code) { root.opaque = code !== 0 } - } - - // The background plugin names the new wallpaper the moment a theme or - // background switch sets it, before its own fade: the blurred copy is made - // then, not when the launcher next opens. - readonly property var backgroundService: root.shell && root.shell.bootIntro ? root.shell.bootIntro.backgroundService : null - readonly property string shownWallpaper: backgroundService ? String(backgroundService.currentBackground || "") : "" - onShownWallpaperChanged: if (shownWallpaper) root.wallpaper = Util.isVideoPath(shownWallpaper) ? "" : shownWallpaper - - // The frosted background: one file per wallpaper, theme colour and - // orientation, in the runtime directory. Both orientations are made - // together, so turning the iPad only switches between two ready images. - readonly property var backdropScreen: panel.screen || (Quickshell.screens.length > 0 ? Quickshell.screens[0] : null) - readonly property real backdropScale: backdropScreen ? backdropScreen.devicePixelRatio : 1 - readonly property int backdropWidth: backdropScreen ? Math.round(backdropScreen.width * backdropScale) : 0 - readonly property int backdropHeight: backdropScreen ? Math.round(backdropScreen.height * backdropScale) : 0 - // How much of the theme's menu background lies over the blurred wallpaper. - readonly property real backdropTint: 0.8 - readonly property color backdropColor: Commons.Color.menu.background - // Everything but the size: what makes a background outdated. - readonly property string backdropLook: wallpaper && !opaque - ? ["frosted4", wallpaper, Math.round(backdropColor.r * 255), Math.round(backdropColor.g * 255), Math.round(backdropColor.b * 255), backdropTint].join("|") : "" - readonly property string backdropKey: backdropKeyFor(backdropWidth, backdropHeight) - readonly property string backdropPath: backdropPathFor(backdropKey) - // key -> path of the backgrounds made so far - property var backdropSaved: ({}) - property var backdropQueue: [] - readonly property bool backdropReady: backdropKey !== "" && !!backdropSaved[backdropKey] - - function backdropKeyFor(width, height) { - return root.backdropLook && width > 0 && height > 0 ? root.backdropLook + "|" + width + "x" + height : "" - } - - function backdropPathFor(key) { - return (Quickshell.env("XDG_RUNTIME_DIR") || "/tmp") + "/omarchy-launcher-backdrop-" + Qt.md5(key) + ".png" - } - - // The orientation on screen first, then the other one. - onBackdropKeyChanged: { - if (!root.backdropKey) return - var wanted = [root.backdropKey, root.backdropKeyFor(root.backdropHeight, root.backdropWidth)] - root.backdropQueue = wanted.filter(function(key) { return key && !root.backdropSaved[key] }) - if (!backdropProc.running) root.makeNextBackdrop() - } - - function makeNextBackdrop() { - if (root.backdropQueue.length === 0) return - var key = root.backdropQueue[0] - root.backdropQueue = root.backdropQueue.slice(1) - var size = key.substring(key.lastIndexOf("|") + 1).split("x") - var look = key.split("|") - backdropProc.key = key - backdropProc.command = [Quickshell.env("OMARCHY_PATH") + "/bin/omarchy-launcher-backdrop", root.wallpaper, - root.backdropPathFor(key), size[0], size[1], look[2], look[3], look[4], look[5]] - backdropProc.running = true - } - - Process { - id: backdropProc - property string key: "" - onExited: function(exitCode) { - if (exitCode === 0) { - var saved = ({}) - for (var k in root.backdropSaved) { - // A background of an earlier wallpaper or theme colour is not - // needed again; both orientations of the current one are. - if (k.indexOf(root.backdropLook + "|") === 0) saved[k] = root.backdropSaved[k] - else Quickshell.execDetached(["rm", "-f", root.backdropSaved[k]]) - } - if (key.indexOf(root.backdropLook + "|") === 0) saved[key] = root.backdropPathFor(key) - else Quickshell.execDetached(["rm", "-f", root.backdropPathFor(key)]) - root.backdropSaved = saved - } - Qt.callLater(root.makeNextBackdrop) - } - } + readonly property int backdropWidth: layoutScreen ? Math.round(screenWidth * layoutScreen.devicePixelRatio) : 0 + readonly property int backdropHeight: layoutScreen ? Math.round(screenHeight * layoutScreen.devicePixelRatio) : 0 + readonly property string backdropPath: appLibrary ? appLibrary.backdrop.cachedPath(backdropWidth, backdropHeight) : "" property bool mapped: false NumberAnimation { @@ -687,13 +592,6 @@ Item { if (bar && bar.activePopout && typeof bar.activePopout.close === "function") bar.activePopout.close() if (root.shell && root.shell.controlCenter && root.shell.controlCenter.opened) root.shell.controlCenter.close() if (root.shell && root.shell.notificationCenter && root.shell.notificationCenter.opened) root.shell.notificationCenter.close() - if (root.appLibrary) root.appLibrary.refreshIcons() - if (root.appsStale || root.apps.length === 0) root.rebuild() - // Stop Screenrecording and the session list follow what is true now. - if (root.menu) root.menu.evaluateGuards() - // A wallpaper changed since: the next open shows it. - wallpaperProc.running = true - if (!Lite.enabled) opaqueProc.running = true root.endSearch() root.pageIndex = 0 root.zone = "" @@ -755,12 +653,6 @@ Item { } } - function rebuild() { - root.appsStale = false - var rows = root.appLibrary ? root.appLibrary.sortedEntries("") : [] - root.apps = rows.map(function(row) { return row.entry }) - } - function showTab(name) { root.pageIndex = root.firstPage(name) } @@ -851,7 +743,10 @@ Item { return } root.close() - if (root.menu) root.menu.runAction(e.action) + if (root.menu) { + root.menu.runAction(e.action) + guardRefresh.restart() + } } function runRow(row) { @@ -1010,10 +905,6 @@ LC_ALL=C pacman -Qi omarchy-a 2>/dev/null | awk \'/^Depends On/ { on = 1 } /^Opt Connections { target: root.appLibrary - function onAppsChanged() { - if (root.opened) root.rebuild() - else root.appsStale = true - } function onRemovalNeedsTerminal() { if (root.opened) root.close() } @@ -1058,8 +949,8 @@ LC_ALL=C pacman -Qi omarchy-a 2>/dev/null | awk \'/^Depends On/ { on = 1 } /^Opt y: -root.barInset width: panel.width height: panel.height - visible: root.backdropReady - source: root.backdropReady ? Util.fileUrl(root.backdropPath) : "" + visible: !!root.backdropPath + source: root.backdropPath ? Util.fileUrl(root.backdropPath) : "" sourceSize: Qt.size(root.backdropWidth, root.backdropHeight) asynchronous: true cache: false @@ -1176,7 +1067,7 @@ LC_ALL=C pacman -Qi omarchy-a 2>/dev/null | awk \'/^Depends On/ { on = 1 } /^Opt x: root.sideMargin y: root.barInset + (root.compact ? Style.space(8) : Style.space(root.phone ? 12 : 24)) width: root.contentWidth - height: parent.height - y - (root.compact ? Style.space(4) : Style.space(root.phone ? 16 : 24)) + height: root.screenHeight - y - (root.compact ? Style.space(4) : Style.space(root.phone ? 16 : 24)) opacity: root.reveal transform: [ Scale { diff --git a/desktop/shell/shell/launcher/LauncherModel.js b/desktop/shell/shell/launcher/LauncherModel.js index 56d5bb47..4cfcddb0 100644 --- a/desktop/shell/shell/launcher/LauncherModel.js +++ b/desktop/shell/shell/launcher/LauncherModel.js @@ -17,6 +17,16 @@ function isPhone(width, height) { return Math.min(width, height) < PHONE_WIDTH } +function sideMargin(width, height, style) { + return style.space(isPhone(width, height) ? 16 : width > height ? 56 : 32) +} + +function iconSize(width, height, style) { + var columns = columnsFor(width, height, isPhone(width, height)) + var cellWidth = Math.max(0, width - 2 * sideMargin(width, height, style)) / columns + return Math.round(Math.min(style.space(56), cellWidth * 0.6)) +} + // The menu's System list as the session actions: its children in menu order, // without About (it belongs to Settings) and without Alt stand-ins. function sessionIds(itemOrder, items, altIds) { diff --git a/desktop/shell/shell/launcher/RecentApps.qml b/desktop/shell/shell/launcher/RecentApps.qml index c6eee60e..43cfe542 100644 --- a/desktop/shell/shell/launcher/RecentApps.qml +++ b/desktop/shell/shell/launcher/RecentApps.qml @@ -135,7 +135,6 @@ Item { } Component.onCompleted: { - Quickshell.execDetached(["mkdir", "-p", root.statePath.substring(0, root.statePath.lastIndexOf("/"))]) syncWindows() readState() } diff --git a/desktop/shell/shell/plugins/bar/Bar.qml b/desktop/shell/shell/plugins/bar/Bar.qml index d9a5409d..e178b48d 100644 --- a/desktop/shell/shell/plugins/bar/Bar.qml +++ b/desktop/shell/shell/plugins/bar/Bar.qml @@ -116,6 +116,7 @@ Item { property string pendingTooltipText: "" property bool tooltipShown: false property int tooltipRequest: 0 + property bool screenRecording: false property var activePopout: null // Where the open panel's card stands, and in which section of the bar, so // a panel taking over in the same section can start its card from there. diff --git a/desktop/shell/shell/plugins/bar/indicators/ScreenRecording.qml b/desktop/shell/shell/plugins/bar/indicators/ScreenRecording.qml index fbd47f1d..6ec8135e 100644 --- a/desktop/shell/shell/plugins/bar/indicators/ScreenRecording.qml +++ b/desktop/shell/shell/plugins/bar/indicators/ScreenRecording.qml @@ -87,6 +87,7 @@ BarIndicator { id: statusProc onExited: function(exitCode) { root.recording = exitCode === 0 + if (root.bar && "screenRecording" in root.bar) root.bar.screenRecording = root.recording } } diff --git a/desktop/shell/shell/plugins/dock/AppGrid.qml b/desktop/shell/shell/plugins/dock/AppGrid.qml index 6df1c278..4cf74d7b 100644 --- a/desktop/shell/shell/plugins/dock/AppGrid.qml +++ b/desktop/shell/shell/plugins/dock/AppGrid.qml @@ -27,12 +27,13 @@ Item { property point menuPoint property string filterText: "" property int selectedIndex: 0 - property var apps: [] + readonly property var apps: !appLibrary ? [] : !filterText ? appLibrary.entries + : appLibrary.sortedEntries(filterText).map(function(row) { return row.entry }) + readonly property var layoutScreen: panel.targetScreen || panel.focusedScreen() readonly property int iconSize: Math.round(56 * Style.fontScale) readonly property int labelHeight: Math.ceil(labelMetrics.height) * 2 - // Orchard: no version under the selected app (upstream shows the package's). - readonly property bool showVersions: false + readonly property bool showVersions: !!appLibrary && appLibrary.showVersions readonly property int versionHeight: showVersions ? Style.spacing.xs + Math.ceil(versionMetrics.height) : 0 readonly property int cellGutter: Style.spacing.sm readonly property int cellPadding: Style.spacing.lg @@ -49,25 +50,15 @@ Item { // The card fits whole columns, and the grid sits centered in it so any // leftover width splits evenly on both sides. - readonly property int cardWidth: Math.min(panel.width - screenMargin * 2, maxColumns * cellWidth + inset * 2) + readonly property int cardWidth: Math.min((layoutScreen ? layoutScreen.width : 0) - screenMargin * 2, maxColumns * cellWidth + inset * 2) readonly property int columns: Math.max(1, Math.floor((cardWidth - inset * 2) / cellWidth)) readonly property int gridWidth: columns * cellWidth - readonly property int cardHeight: Math.min(panel.height - screenMargin * 2, inset * 2 + headerHeight + headerSpacing + visibleRows * cellHeight) + readonly property int cardHeight: Math.min((layoutScreen ? layoutScreen.height : 0) - screenMargin * 2, inset * 2 + headerHeight + headerSpacing + visibleRows * cellHeight) function open() { root.selectedIndex = 0 - if (root.appLibrary) { - root.appLibrary.refreshIcons() - if (root.showVersions) root.appLibrary.refreshVersions() - } - // The cells from last time are reused when nothing changed, so the grid - // opens with its icons already drawn. - if (root.appsStale || root.filterText !== "" || root.apps.length === 0) { - root.filterText = "" - root.rebuild() - } else { - grid.positionViewAtBeginning() - } + root.filterText = "" + grid.positionViewAtBeginning() root.opened = true Qt.callLater(function() { searchField.forceActiveFocus() }) } @@ -128,27 +119,13 @@ Item { else root.open() } - function rebuild() { - root.appsStale = false - var rows = root.appLibrary ? root.appLibrary.sortedEntries(root.filterText) : [] - root.apps = rows.map(function(row) { return row.entry }) - root.selectedIndex = Math.max(0, Math.min(root.selectedIndex, root.apps.length - 1)) - grid.positionViewAtBeginning() - } - onFilterTextChanged: if (searchField.text !== filterText) searchField.text = filterText - // Apps came or went while the grid is open: keep the user where they were. - function refresh() { - var position = grid.contentY - root.rebuild() - grid.forceLayout() - grid.contentY = Math.max(0, Math.min(position, grid.contentHeight - grid.height)) - } + onAppsChanged: selectedIndex = Math.max(0, Math.min(selectedIndex, apps.length - 1)) function setFilter(text) { root.filterText = text root.selectedIndex = 0 - root.rebuild() + grid.positionViewAtBeginning() } function select(delta) { @@ -177,16 +154,8 @@ Item { font.pixelSize: Style.font.caption } - // Apps installed or removed while the grid is closed are picked up when it - // next opens. - property bool appsStale: false - Connections { target: root.appLibrary - function onAppsChanged() { - if (root.opened) root.refresh() - else root.appsStale = true - } function onRemovalNeedsTerminal() { if (root.opened) root.close() } @@ -341,7 +310,7 @@ Item { GridView { id: grid anchors.fill: parent - model: root.apps + model: root.apps.length clip: true cellWidth: root.cellWidth cellHeight: root.cellHeight @@ -351,7 +320,7 @@ Item { id: cell required property int index - required property var modelData + readonly property var modelData: root.apps[index] || null readonly property bool selected: index === root.selectedIndex property point pressPoint // A press that wanders is a drag in the making, not a click. diff --git a/desktop/shell/shell/plugins/menu/Menu.qml b/desktop/shell/shell/plugins/menu/Menu.qml index 79fd68da..6b1f21bf 100644 --- a/desktop/shell/shell/plugins/menu/Menu.qml +++ b/desktop/shell/shell/plugins/menu/Menu.qml @@ -2,6 +2,7 @@ import Quickshell import Quickshell.Io import Quickshell.Wayland import QtQuick +import Qt.labs.folderlistmodel import qs.Commons import qs.Commons as Commons import qs.Ui @@ -1167,6 +1168,7 @@ Item { Connections { target: root.appLibrary + function onPackagesChanged() { guardInputsChanged.restart() } function onAppsChanged() { if (root.providersLoaded["apps"]) root.mergeAppRows() } @@ -1233,6 +1235,36 @@ Item { property var disabledResults: ({}) // id → true|false (dim, skip cursor) property bool guardsPending: false + // The launcher shares these answers. Refresh when their inputs change, + // including changes made outside Settings, without tying work to a window. + Timer { + id: guardInputsChanged + interval: 600 + onTriggered: if (root.defaultMenuSettled && root.userMenuSettled) root.scheduleGuards() + } + FolderListModel { + id: toggles + folder: Util.fileUrl(Quickshell.env("HOME") + "/.local/state/omarchy/toggles") + showDirs: false + } + Connections { + target: toggles + function onDataChanged() { guardInputsChanged.restart() } + function onRowCountChanged() { guardInputsChanged.restart() } + } + Connections { + target: root.shell ? root.shell.bar : null + ignoreUnknownSignals: true + function onBarConfigChanged() { guardInputsChanged.restart() } + function onScreenRecordingChanged() { guardInputsChanged.restart() } + } + FileView { + path: (Quickshell.env("XDG_CONFIG_HOME") || Quickshell.env("HOME") + "/.config") + "/mimeapps.list" + preload: false + watchChanges: true + onFileChanged: guardInputsChanged.restart() + } + property bool guardsDeferred: false function scheduleGuards() { if (Startup.ready || opened) evaluateGuards() diff --git a/desktop/shell/shell/services/AppLibrary.qml b/desktop/shell/shell/services/AppLibrary.qml index 1ea2df42..6bf10746 100644 --- a/desktop/shell/shell/services/AppLibrary.qml +++ b/desktop/shell/shell/services/AppLibrary.qml @@ -11,10 +11,10 @@ import "AppSearch.js" as AppSearch Item { id: root + readonly property LauncherBackdrop backdrop: LauncherBackdrop {} property string omarchyPath: Quickshell.env("OMARCHY_PATH") - property bool indexRequested: false - readonly property bool indexActive: Startup.ready || indexRequested + readonly property bool indexActive: Startup.ready property var configuredHiddenEntryIds: ({}) property var desktopHiddenEntryIds: ({}) // Desktop id -> X-Omarchy-Dock-Click, which Quickshell doesn't parse. @@ -37,10 +37,12 @@ Item { readonly property string userIconsPath: (Quickshell.env("XDG_DATA_HOME") || home + "/.local/share") + "/icons/" property int themeRevision: 0 - // Maps a desktop id to the version of the package that owns it. Rescanned - // each time the app grid opens, since upgrades leave desktop entries alone. + // The Orchard grid currently hides package versions. If enabled, populate + // them after startup and on package transactions, even with the grid closed. + readonly property bool showVersions: false property var versions: ({}) property var pendingVersions: ({}) + property bool versionRescanQueued: false property int launchSerial: 0 property int launchToplevelCount: 0 @@ -54,6 +56,7 @@ Item { // Emitted whenever the visible application set may have changed: desktop // entries appeared or vanished, or the hidden-entry filters reloaded. signal appsChanged() + signal packagesChanged() // Emitted when removing an entry has to open a terminal (a package // uninstall asking for a password), so an open launcher can step aside. @@ -73,8 +76,14 @@ Item { return root.configuredHiddenEntryIds[id] === true || root.desktopHiddenEntryIds[id] === true } + readonly property var allRows: indexActive ? searchEntries("") : [] + readonly property var entries: allRows.map(function(row) { return row.entry }) + function sortedEntries(query) { - indexRequested = true + return query ? searchEntries(query) : allRows + } + + function searchEntries(query) { var values = DesktopEntries.applications.values || [] return AppSearch.sortedEntries(values, query, function(entry) { return root.isHiddenEntry(entry) }) } @@ -94,18 +103,18 @@ Item { return Quickshell.iconPath("application-x-executable", true) } - // The shell may start before first-install packages have finished placing - // their icons; consumers call this when they open so icons appear live. // A request during a scan queues one more, since the running scan may have // listed icons before they changed. function refreshIcons() { - if (!indexActive) { indexRequested = true; return } + if (!indexActive) return if (iconIndexScan.running) root.iconRescanQueued = true else iconIndexScan.running = true } function refreshVersions() { - if (!versionScan.running) versionScan.running = true + if (!showVersions || !indexActive) return + if (versionScan.running) versionRescanQueued = true + else versionScan.running = true } function version(entry) { @@ -333,7 +342,13 @@ Item { } } onStarted: root.pendingVersions = ({}) - onExited: root.versions = root.pendingVersions + onExited: { + root.versions = root.pendingVersions + if (root.versionRescanQueued) { + root.versionRescanQueued = false + Qt.callLater(root.refreshVersions) + } + } } // Coalesces bursts of app-list changes (a package install touches many @@ -341,7 +356,22 @@ Item { Timer { id: iconIndexDebounce interval: 750 - onTriggered: if (!iconIndexScan.running) iconIndexScan.running = true + onTriggered: root.refreshIcons() + } + + FileView { + property bool transactionChanged: false + path: root.indexActive ? (Quickshell.env("OMARCHY_PACMAN_DB_PATH") || "/var/lib/pacman") + "/db.lck" : "" + watchChanges: true + printErrors: false + onFileChanged: { transactionChanged = true; reload() } + onLoadFailed: { + if (!transactionChanged) return + transactionChanged = false + root.packagesChanged() + iconIndexDebounce.restart() + root.refreshVersions() + } } FileView { @@ -404,6 +434,7 @@ Item { onTriggered: { desktopEntryScan.running = true iconIndexScan.running = true + root.refreshVersions() } } } diff --git a/desktop/shell/shell/services/LauncherBackdrop.qml b/desktop/shell/shell/services/LauncherBackdrop.qml new file mode 100644 index 00000000..a75946b1 --- /dev/null +++ b/desktop/shell/shell/services/LauncherBackdrop.qml @@ -0,0 +1,129 @@ +import QtQuick +import Quickshell +import Quickshell.Io +import qs.Commons +import qs.Commons as Commons + +Item { + id: root + property var backgroundService + readonly property string stateDir: Quickshell.env("HOME") + "/.local/state/omarchy" + readonly property bool opaque: Lite.enabled || !frosted.present + readonly property string currentBackground: backgroundService ? backgroundService.currentBackground : "" + readonly property string wallpaper: { + var path = currentBackground || linkTarget + return Util.isVideoPath(path) ? "" : path + } + property string linkTarget: "" + + FileView { + id: frosted + property bool present: false + path: Startup.ready && !Lite.enabled ? root.stateDir + "/toggles/launcher-frosted" : "" + watchChanges: true + printErrors: false + onLoaded: present = true + onLoadFailed: present = false + onFileChanged: reload() + } + + // With the background plugin disabled (e.g. swaybg), follow the same link. + FileView { + id: backgroundLink + path: !root.opaque && !root.currentBackground ? root.stateDir + "/current/background" : "" + preload: false + watchChanges: true + onPathChanged: if (path) Qt.callLater(resolveLink) + onFileChanged: resolveLink() + property bool pending: false + function resolveLink() { + if (readLink.running) pending = true + else if (path) readLink.running = true + } + } + Process { + id: readLink + command: ["readlink", "-f", backgroundLink.path] + stdout: StdioCollector { id: linkOutput } + onExited: { + root.linkTarget = linkOutput.text.trim() + if (backgroundLink.pending) { + backgroundLink.pending = false + Qt.callLater(backgroundLink.resolveLink) + } + } + } + + // The frosted background: one file per wallpaper, theme colour and + // orientation, in the runtime directory. Both orientations are made + // together, so turning the iPad only switches between two ready images. + // How much of the theme's menu background lies over the blurred wallpaper. + readonly property real backdropTint: 0.8 + readonly property color backdropColor: Commons.Color.menu.background + // Everything but the size: what makes a background outdated. + readonly property string backdropLook: wallpaper && !opaque + ? ["frosted4", wallpaper, Math.round(backdropColor.r * 255), Math.round(backdropColor.g * 255), Math.round(backdropColor.b * 255), backdropTint].join("|") : "" + // key -> path of the backgrounds made so far + property var backdropSaved: ({}) + property var backdropQueue: [] + function cachedPath(width, height) { + return backdropSaved[backdropKeyFor(width, height)] || "" + } + + function backdropKeyFor(width, height) { + return root.backdropLook && width > 0 && height > 0 ? root.backdropLook + "|" + width + "x" + height : "" + } + + function backdropPathFor(key) { + return (Quickshell.env("XDG_RUNTIME_DIR") || "/tmp") + "/omarchy-launcher-backdrop-" + Qt.md5(key) + ".png" + } + + // Prepare both orientations for every output independently of launcher visibility. + readonly property var wantedKeys: { + var keys = [] + for (var screen of Quickshell.screens) { + var w = Math.round(screen.width * screen.devicePixelRatio) + var h = Math.round(screen.height * screen.devicePixelRatio) + for (var key of [backdropKeyFor(w, h), backdropKeyFor(h, w)]) + if (key && keys.indexOf(key) < 0) keys.push(key) + } + return keys + } + onWantedKeysChanged: Qt.callLater(updateQueue) + function updateQueue() { + backdropQueue = wantedKeys.filter(key => !backdropSaved[key] && !(backdropProc.running && backdropProc.key === key)) + if (!backdropProc.running) makeNextBackdrop() + } + + function makeNextBackdrop() { + if (root.backdropQueue.length === 0) return + var key = root.backdropQueue[0] + root.backdropQueue = root.backdropQueue.slice(1) + var size = key.substring(key.lastIndexOf("|") + 1).split("x") + var look = key.split("|") + backdropProc.key = key + backdropProc.command = [Quickshell.env("OMARCHY_PATH") + "/bin/omarchy-launcher-backdrop", root.wallpaper, + root.backdropPathFor(key), size[0], size[1], look[2], look[3], look[4], look[5]] + backdropProc.running = true + } + + Process { + id: backdropProc + property string key: "" + onExited: function(exitCode) { + if (exitCode === 0) { + var saved = ({}) + for (var k in root.backdropSaved) { + // A background of an earlier wallpaper or theme colour is not + // needed again; both orientations of the current one are. + if (k.indexOf(root.backdropLook + "|") === 0) saved[k] = root.backdropSaved[k] + else Quickshell.execDetached(["rm", "-f", root.backdropSaved[k]]) + } + if (key.indexOf(root.backdropLook + "|") === 0) saved[key] = root.backdropPathFor(key) + else Quickshell.execDetached(["rm", "-f", root.backdropPathFor(key)]) + root.backdropSaved = saved + } + Qt.callLater(root.makeNextBackdrop) + } + } +} diff --git a/desktop/shell/shell/shell.qml b/desktop/shell/shell/shell.qml index d348615f..cdb93fbb 100644 --- a/desktop/shell/shell/shell.qml +++ b/desktop/shell/shell/shell.qml @@ -30,7 +30,7 @@ ShellRoot { // own empty copies. property PluginRegistry pluginRegistry: PluginRegistry { } property BarWidgetRegistry barWidgetRegistry: BarWidgetRegistry { } - property AppLibrary appLibrary: AppLibrary { } + property AppLibrary appLibrary: AppLibrary { backdrop.backgroundService: shell.bootIntro ? shell.bootIntro.backgroundService : null } // Orchard: the launcher answers the stock Apps menu action // (`omarchy-shell omarchy.dock apps`), so Home, Super, Super+Space and the From f14834a89768d4fa1c67c1a8c687b81da70a33c8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Berkay=20K=C3=B6sebay?= Date: Tue, 1 Dec 2026 18:02:10 +0100 Subject: [PATCH 10/17] launcher: retain display-sized icons and warm the SVG raster cache MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Assisted-by: LLM Signed-off-by: Berkay Kösebay --- desktop/shell/shell/Ui/AppIconImage.qml | 15 +++++ desktop/shell/shell/Ui/qmldir | 1 + desktop/shell/shell/launcher/Launcher.qml | 21 +++---- desktop/shell/shell/plugins/dock/AppGrid.qml | 18 ++---- desktop/shell/shell/plugins/dock/Dock.qml | 19 ++++++- .../shell/shell/plugins/dock/DockWindow.qml | 14 +---- desktop/shell/shell/services/AppLibrary.qml | 57 +++++++++++++++++++ desktop/shell/shell/services/raster-icons.py | 55 ++++++++++++++++++ 8 files changed, 161 insertions(+), 39 deletions(-) create mode 100644 desktop/shell/shell/Ui/AppIconImage.qml create mode 100644 desktop/shell/shell/services/raster-icons.py diff --git a/desktop/shell/shell/Ui/AppIconImage.qml b/desktop/shell/shell/Ui/AppIconImage.qml new file mode 100644 index 00000000..687597e8 --- /dev/null +++ b/desktop/shell/shell/Ui/AppIconImage.qml @@ -0,0 +1,15 @@ +import QtQuick +import qs.Commons + +Image { + property real outputScale: Screen.devicePixelRatio + readonly property int pixelSize: Math.round(width * outputScale) + // Qt applies DPR itself to SVGs and image providers. Ordinary PNGs + // (including the raster cache) take a sourceSize in physical pixels. + readonly property bool scalable: /^image:|\.(svgz?|pdf)([?#]|$)/i.test(String(source)) + sourceSize: Qt.size(scalable ? width : pixelSize, scalable ? height : Math.round(height * outputScale)) + cache: true + fillMode: Image.PreserveAspectFit + smooth: true + mipmap: !Lite.enabled +} diff --git a/desktop/shell/shell/Ui/qmldir b/desktop/shell/shell/Ui/qmldir index a2a5cdae..c09c8131 100644 --- a/desktop/shell/shell/Ui/qmldir +++ b/desktop/shell/shell/Ui/qmldir @@ -1,5 +1,6 @@ module qs.Ui +AppIconImage 1.0 AppIconImage.qml BarIndicator 1.0 BarIndicator.qml BarIconButton 1.0 BarIconButton.qml BarIconContent 1.0 BarIconContent.qml diff --git a/desktop/shell/shell/launcher/Launcher.qml b/desktop/shell/shell/launcher/Launcher.qml index 3679b665..100b9211 100644 --- a/desktop/shell/shell/launcher/Launcher.qml +++ b/desktop/shell/shell/launcher/Launcher.qml @@ -1907,19 +1907,16 @@ LC_ALL=C pacman -Qi omarchy-a 2>/dev/null | awk \'/^Depends On/ { on = 1 } /^Opt holds: true } - Image { + AppIconImage { id: appIcon scale: cellSqueeze.value anchors.horizontalCenter: parent.horizontalCenter y: Style.space(10) width: root.iconSize height: root.iconSize - sourceSize: Qt.size(root.iconSize * 2, root.iconSize * 2) - source: cell.app && root.appLibrary ? root.appLibrary.iconSource(cell.app.icon) : "" - fillMode: Image.PreserveAspectFit + outputScale: root.layoutScreen ? root.layoutScreen.devicePixelRatio : 1 + source: cell.app && root.appLibrary ? root.appLibrary.rasterSource(cell.app.icon, pixelSize) : "" asynchronous: false - smooth: true - mipmap: true } Text { @@ -2084,11 +2081,12 @@ LC_ALL=C pacman -Qi omarchy-a 2>/dev/null | awk \'/^Depends On/ { on = 1 } /^Opt visible: false onPressedChanged: { - if (!root.gpu) return + if (Lite.enabled || !root.gpu) return if (pressed) { out.stop(); press.restart() } else release() } function release() { + if (Lite.enabled || !root.gpu) return press.stop() out.restart() } @@ -2238,15 +2236,12 @@ LC_ALL=C pacman -Qi omarchy-a 2>/dev/null | awk \'/^Depends On/ { on = 1 } /^Opt font.family: root.glyphFont(resultRow.menuEntry) font.pixelSize: Style.font.heading } - Image { + AppIconImage { visible: !resultRow.menuEntry anchors.fill: parent - sourceSize: Qt.size(width * 2, height * 2) + outputScale: root.layoutScreen ? root.layoutScreen.devicePixelRatio : 1 source: resultRow.menuEntry || !root.appLibrary ? "" - : (resultRow.app ? root.appLibrary.iconSource(resultRow.app.icon) : Quickshell.iconPath("text-x-generic", true)) - fillMode: Image.PreserveAspectFit - smooth: true - mipmap: true + : (resultRow.app ? root.appLibrary.rasterSource(resultRow.app.icon, pixelSize) : Quickshell.iconPath("text-x-generic", true)) } } diff --git a/desktop/shell/shell/plugins/dock/AppGrid.qml b/desktop/shell/shell/plugins/dock/AppGrid.qml index 4cf74d7b..489378a0 100644 --- a/desktop/shell/shell/plugins/dock/AppGrid.qml +++ b/desktop/shell/shell/plugins/dock/AppGrid.qml @@ -329,20 +329,17 @@ Item { width: root.cellWidth height: root.cellHeight - Image { + AppIconImage { id: icon anchors.horizontalCenter: parent.horizontalCenter y: root.cellPadding width: root.iconSize height: root.iconSize - sourceSize: Qt.size(root.iconSize * 2, root.iconSize * 2) - source: root.appLibrary ? root.appLibrary.iconSource(cell.modelData.icon) : "" - fillMode: Image.PreserveAspectFit + outputScale: root.layoutScreen ? root.layoutScreen.devicePixelRatio : 1 + source: cell.modelData && root.appLibrary ? root.appLibrary.rasterSource(cell.modelData.icon, pixelSize) : "" // Loaded with the cell, from Qt's image cache after the first // open, so icons do not pop in after the grid has appeared. asynchronous: false - smooth: true - mipmap: true } // The selection marks the app's name, not the whole cell. @@ -439,17 +436,14 @@ Item { } } // The dragged app's icon, under the pointer. - Image { + AppIconImage { visible: root.dragging && !!root.dragEntry x: root.dragPoint.x - width / 2 y: root.dragPoint.y - height / 2 width: root.iconSize height: root.iconSize - sourceSize: Qt.size(root.iconSize * 2, root.iconSize * 2) - source: root.dragEntry && root.appLibrary ? root.appLibrary.iconSource(root.dragEntry.icon) : "" - fillMode: Image.PreserveAspectFit - smooth: true - mipmap: true + outputScale: root.layoutScreen ? root.layoutScreen.devicePixelRatio : 1 + source: root.dragEntry && root.appLibrary ? root.appLibrary.rasterSource(root.dragEntry.icon, pixelSize) : "" } // Right-click on an app: open it, or keep it in the dock or take it out. diff --git a/desktop/shell/shell/plugins/dock/Dock.qml b/desktop/shell/shell/plugins/dock/Dock.qml index ee72b9a9..76f0fc97 100644 --- a/desktop/shell/shell/plugins/dock/Dock.qml +++ b/desktop/shell/shell/plugins/dock/Dock.qml @@ -159,10 +159,23 @@ Item { return item ? DesktopEntries.byId(item.key) : null } - function iconFor(item) { + function iconName(item) { var entry = entryFor(item) - var icon = entry && entry.icon ? entry.icon : (item ? item.key : "") - return root.appLibrary ? root.appLibrary.iconSource(icon) : Quickshell.iconPath(icon, true) + return entry && entry.icon ? entry.icon : (item ? item.key : "") + } + + // Include pinned and running apps without a matching desktop entry in the + // background raster pass. A window count change keeps the same name list. + Binding { + target: root.appLibrary + when: !!root.appLibrary + property: "dockIconNames" + value: JSON.stringify(root.items.map(root.iconName).sort()) + } + + function iconFor(item, pixels) { + var icon = iconName(item) + return root.appLibrary ? root.appLibrary.rasterSource(icon, pixels) : Quickshell.iconPath(icon, true) } function launch(item) { diff --git a/desktop/shell/shell/plugins/dock/DockWindow.qml b/desktop/shell/shell/plugins/dock/DockWindow.qml index 9617e9a4..005c60a8 100644 --- a/desktop/shell/shell/plugins/dock/DockWindow.qml +++ b/desktop/shell/shell/plugins/dock/DockWindow.qml @@ -496,7 +496,7 @@ PanelWindow { y: window.iconInset width: window.iconSize height: window.iconSize - source: window.dock && appSlot.modelData ? window.dock.iconFor(appSlot.modelData) : "" + source: window.dock && appSlot.modelData ? window.dock.iconFor(appSlot.modelData, Math.round(width * window.devicePixelRatio)) : "" opacity: appSlot.launching ? appSlot.pulse : 1 transform: Translate { x: window.vertical ? 0 : appSlot.displayedShift @@ -543,24 +543,16 @@ PanelWindow { } Component.onCompleted: current.source = appIcon.source - Image { + AppIconImage { id: previous anchors.fill: parent - sourceSize: current.sourceSize - fillMode: Image.PreserveAspectFit asynchronous: true - smooth: true - mipmap: true } - Image { + AppIconImage { id: current anchors.fill: parent - sourceSize: Qt.size(window.iconSize * 2, window.iconSize * 2) - fillMode: Image.PreserveAspectFit asynchronous: true - smooth: true - mipmap: true onStatusChanged: appIcon.reveal() } diff --git a/desktop/shell/shell/services/AppLibrary.qml b/desktop/shell/shell/services/AppLibrary.qml index 6bf10746..500f2209 100644 --- a/desktop/shell/shell/services/AppLibrary.qml +++ b/desktop/shell/shell/services/AppLibrary.qml @@ -3,6 +3,7 @@ import Quickshell import Quickshell.Io import Quickshell.Wayland import qs.Commons +import "../launcher/LauncherModel.js" as LauncherModel import "AppSearch.js" as AppSearch // Shared desktop-application library: the sorted entry list with hidden-entry @@ -103,6 +104,60 @@ Item { return Quickshell.iconPath("application-x-executable", true) } + // Prepare only sizes actually used on the attached screens. The launcher + // and dock may be unmapped here, so there is no Qt Quick item to grab. + readonly property var rasterSizes: { + var sizes = new Set() + for (var screen of Quickshell.screens) { + var launcherSize = LauncherModel.iconSize(screen.width, screen.height, Style) + for (var size of [launcherSize, Style.space(36), Math.round(36 * Style.fontScale), Math.round(56 * Style.fontScale)]) { + var pixels = Math.round(size * screen.devicePixelRatio) + if (pixels > 0) sizes.add(pixels) + } + } + return Array.from(sizes) + } + property string dockIconNames: "[]" + property var rasterIndex: ({}) + property bool rasterPending: false + property bool iconsScanned: false + + function rasterSource(icon, pixels) { + var source = iconSource(icon) + var sizes = rasterIndex[source] + return (sizes && sizes[pixels]) || source + } + + function prepareRasters() { + if (!iconsScanned) return + if (rasterScan.running) { rasterPending = true; return } + rasterPending = false + var sources = new Set() + var names = JSON.parse(dockIconNames).concat(entries.map(entry => entry.icon)) + for (var name of names) { + var source = iconSource(name) + if (/^file:.*\.svg(?:\?|$)/i.test(source)) sources.add(source) + } + rasterScan.request = JSON.stringify({ sources: Array.from(sources), sizes: rasterSizes }) + rasterScan.running = true + } + onRasterSizesChanged: Qt.callLater(prepareRasters) + onDockIconNamesChanged: Qt.callLater(prepareRasters) + onEntriesChanged: if (iconsScanned) Qt.callLater(prepareRasters) + + Process { + id: rasterScan + property string request + command: ["python3", root.omarchyPath + "/shell/services/raster-icons.py"] + stdinEnabled: true + onStarted: write(request + "\n") + stdout: StdioCollector { id: rasterResult } + onExited: function(code, status) { + if (!code && !status && rasterResult.text) root.rasterIndex = JSON.parse(rasterResult.text) + if (root.rasterPending) Qt.callLater(root.prepareRasters) + } + } + // A request during a scan queues one more, since the running scan may have // listed icons before they changed. function refreshIcons() { @@ -325,6 +380,8 @@ Item { // newly found icons appear without rebuilding the list. onExited: { root.iconIndex = root.pendingIconIndex + root.iconsScanned = true + Qt.callLater(root.prepareRasters) if (root.iconRescanQueued) { root.iconRescanQueued = false running = true diff --git a/desktop/shell/shell/services/raster-icons.py b/desktop/shell/shell/services/raster-icons.py new file mode 100644 index 00000000..c4a87c1f --- /dev/null +++ b/desktop/shell/shell/services/raster-icons.py @@ -0,0 +1,55 @@ +"""Warm the launcher's on-disk icon cache without mapping a Qt Quick window.""" +import hashlib +import json +import os +from pathlib import Path +import shutil +import subprocess +import sys +import tempfile +from urllib.parse import unquote, urlsplit + + +def prepare(request): + converter = shutil.which("rsvg-convert") + if not converter or not request["sources"]: + return {} + cache = Path(os.environ.get("XDG_CACHE_HOME") or Path.home() / ".cache") / "omarchy/icon-raster" + cache.mkdir(parents=True, exist_ok=True) + index = {} + for source in request["sources"]: + path = Path(unquote(urlsplit(source).path)) + try: + path = path.resolve(strict=True) + stamp = path.stat().st_mtime_ns + except (OSError, RuntimeError): + continue + key = hashlib.sha256(os.fsencode(path)).hexdigest() + sizes = {} + for pixels in request["sizes"]: + target = cache / f"{key}-{stamp}-{pixels}.png" + try: + if not target.is_file(): + with tempfile.NamedTemporaryFile(dir=cache) as tmp: + result = subprocess.run([converter, "--keep-aspect-ratio", "-w", str(pixels), + "-h", str(pixels), str(path)], stdout=tmp) + if result.returncode or not tmp.tell(): + continue + # Publish a complete PNG even if the shell restarts mid-render. + try: + os.link(tmp.name, target) + except FileExistsError: + pass + sizes[pixels] = target.as_uri() + except OSError: + continue + index[source] = sizes + return index + + +if __name__ == "__main__": + try: + index = prepare(json.loads(sys.stdin.readline())) + except OSError: + index = {} + print(json.dumps(index)) From f22771fe4169540f745580f4cea8461fa8cd6409 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Berkay=20K=C3=B6sebay?= Date: Tue, 1 Dec 2026 18:02:11 +0100 Subject: [PATCH 11/17] battery: share event-driven sysfs readings across the shell MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Assisted-by: LLM Signed-off-by: Berkay Kösebay --- desktop/shell/bin/omarchy-battery-status | 36 +++++++++---------- .../Status.qml => Commons/BatteryStatus.qml} | 29 +++++++++++---- desktop/shell/shell/Commons/qmldir | 1 + .../shell/controlcenter/ControlCenter.qml | 2 +- .../shell/plugins/panels/power/Panel.qml | 16 ++++----- .../shell/plugins/status/StatusCluster.qml | 3 +- 6 files changed, 50 insertions(+), 37 deletions(-) rename desktop/shell/shell/{plugins/panels/power/Status.qml => Commons/BatteryStatus.qml} (78%) diff --git a/desktop/shell/bin/omarchy-battery-status b/desktop/shell/bin/omarchy-battery-status index f94bcd77..2040dd98 100644 --- a/desktop/shell/bin/omarchy-battery-status +++ b/desktop/shell/bin/omarchy-battery-status @@ -7,43 +7,43 @@ set -euo pipefail [[ $# == 1 && $1 == --shell ]] || { echo 'Usage: omarchy-battery-status --shell' >&2; exit 2; } base=${OMARCHY_POWER_SUPPLY_PATH:-/sys/class/power_supply} battery='' -for candidate in "$base"/*; do - [[ -r $candidate/type && $(<"$candidate/type") == Battery ]] || continue - [[ ! -r $candidate/present || $(<"$candidate/present") == 1 ]] || continue - [[ -z $battery ]] || exit 0 # Ambiguous: show UPower alone. - battery=$candidate -done -[[ -n $battery && -r $battery/capacity ]] || exit 0 -read -r percentage < "$battery/capacity" -[[ $percentage =~ ^[0-9]+$ && $percentage -le 100 ]] || exit 0 -printf 'percentage\t%s%%\n' "$percentage" - external=unknown for candidate in "$base"/*; do - [[ -r $candidate/type && $(<"$candidate/type") != Battery && -r $candidate/online ]] || continue - if read -r online < "$candidate/online"; then + [[ -r $candidate/type ]] && read -r type < "$candidate/type" || continue + if [[ $type == Battery ]]; then + if [[ -r $candidate/present ]]; then + read -r present < "$candidate/present" && [[ $present == 1 ]] || continue + fi + [[ -z $battery ]] || exit 0 # Ambiguous: show UPower alone. + battery=$candidate + elif [[ $external != connected && -r $candidate/online ]] && read -r online < "$candidate/online"; then case "$online" in - 1) external=connected; break ;; + 1) external=connected ;; 0) external=disconnected ;; esac fi done +[[ -n $battery && -r $battery/capacity ]] || exit 0 +read -r percentage < "$battery/capacity" +[[ $percentage =~ ^[0-9]+$ && 10#$percentage -le 100 ]] || exit 0 +printf 'percentage\t%s%%\n' "$percentage" printf 'external_power\t%s\n' "$external" if [[ -r $battery/energy_full ]] && read -r full < "$battery/energy_full" && - [[ $full =~ ^[0-9]+$ && $full -gt 0 ]]; then - awk -v uwh="$full" 'BEGIN { printf "size\t%.1fWh\n", uwh / 1000000 }' + [[ $full =~ ^[0-9]+$ && 10#$full -gt 0 ]]; then + LC_NUMERIC=C printf 'size\t%.1fWh\n' "${full}e-6" fi if [[ -r $battery/cycle_count ]] && read -r cycles < "$battery/cycle_count"; then [[ ! $cycles =~ ^[0-9]+$ ]] || printf 'cycles\t%s\n' "$cycles" fi if [[ -r $battery/power_now ]]; then read -r microwatts < "$battery/power_now" - [[ ! $microwatts =~ ^-?[0-9]+$ ]] || awk -v u="$microwatts" 'BEGIN { if (u < 0) u = -u; printf "rate\t%.1fW\n", u / 1000000 }' + [[ ! $microwatts =~ ^-?[0-9]+$ ]] || LC_NUMERIC=C printf 'rate\t%.1fW\n' "${microwatts#-}e-6" elif [[ -r $battery/current_now && -r $battery/voltage_now ]]; then read -r microamps < "$battery/current_now" read -r microvolts < "$battery/voltage_now" if [[ $microamps =~ ^-?[0-9]+$ && $microvolts =~ ^[0-9]+$ ]]; then - awk -v i="$microamps" -v v="$microvolts" 'BEGIN { if (i < 0) i = -i; printf "rate\t%.1fW\n", i * v / 1000000000000 }' + picowatts=$((10#${microamps#-} * 10#$microvolts)) + LC_NUMERIC=C printf 'rate\t%.1fW\n' "${picowatts}e-12" fi fi diff --git a/desktop/shell/shell/plugins/panels/power/Status.qml b/desktop/shell/shell/Commons/BatteryStatus.qml similarity index 78% rename from desktop/shell/shell/plugins/panels/power/Status.qml rename to desktop/shell/shell/Commons/BatteryStatus.qml index 83fa4792..a571cd83 100644 --- a/desktop/shell/shell/plugins/panels/power/Status.qml +++ b/desktop/shell/shell/Commons/BatteryStatus.qml @@ -1,18 +1,18 @@ +pragma Singleton import QtQuick import Quickshell import Quickshell.Io import Quickshell.Services.UPower -import "Model.js" as Model +import "../plugins/panels/power/Model.js" as Model // Orchard: the battery state the bar's icon shows, apart from the panel, so // the status cluster, the lock and the control center show the same thing. // The panel binds its own properties of these names to it. -Item { +Singleton { id: root - visible: false // The battery script's readings (omarchy-battery-status --shell), read - // periodically: discovery must not depend on a charger event or on UPower. + // on power events and once a minute for drivers that miss notifications. property var batteryInfo: ({}) readonly property bool externalPower: batteryInfo.external_power === "connected" readonly property var batteryDevice: { @@ -40,7 +40,7 @@ Item { } function refresh() { - if (!batteryProc.running) batteryProc.running = true + scheduleRead.restart() } function updateKeyValue(raw) { @@ -51,6 +51,16 @@ Item { else batteryInfo = Object.assign({}, batteryInfo, { external_power: "unknown" }) } + // Charger and pack properties often change together. Coalesce the burst. + Timer { + id: scheduleRead + interval: 100 + onTriggered: { + if (batteryProc.running) restart() + else batteryProc.running = true + } + } + Process { id: batteryProc command: ["omarchy-battery-status", "--shell"] @@ -62,8 +72,15 @@ Item { function onOnBatteryChanged() { root.refresh() } } + Connections { + target: UPower.displayDevice + function onIsPresentChanged() { root.refresh() } + function onPercentageChanged() { root.refresh() } + function onStateChanged() { root.refresh() } + } + Timer { - interval: 5000 + interval: 60000 running: true repeat: true triggeredOnStart: true diff --git a/desktop/shell/shell/Commons/qmldir b/desktop/shell/shell/Commons/qmldir index e47a9482..f079d0cf 100644 --- a/desktop/shell/shell/Commons/qmldir +++ b/desktop/shell/shell/Commons/qmldir @@ -1,5 +1,6 @@ module qs.Commons singleton AudioNodes 1.0 AudioNodes.qml +singleton BatteryStatus 1.0 BatteryStatus.qml singleton Border 1.0 Border.qml singleton Color 1.0 Color.qml singleton I18n 1.0 I18n.qml diff --git a/desktop/shell/shell/controlcenter/ControlCenter.qml b/desktop/shell/shell/controlcenter/ControlCenter.qml index e63b56f0..f90d07ba 100644 --- a/desktop/shell/shell/controlcenter/ControlCenter.qml +++ b/desktop/shell/shell/controlcenter/ControlCenter.qml @@ -175,7 +175,7 @@ Item { // The battery: how full, whether it charges, and at how many watts. Its // page (the battery panel) has the rest; with no battery found the row // is dimmed and the page says so. - PowerPanel.Status { id: battery } + readonly property var battery: Commons.BatteryStatus readonly property string batteryNote: { if (!battery.batteryPresent) return Commons.I18n.t("controlCenter.noBattery", "No battery") var parts = [] diff --git a/desktop/shell/shell/plugins/panels/power/Panel.qml b/desktop/shell/shell/plugins/panels/power/Panel.qml index 5976ac69..293338ae 100644 --- a/desktop/shell/shell/plugins/panels/power/Panel.qml +++ b/desktop/shell/shell/plugins/panels/power/Panel.qml @@ -14,11 +14,8 @@ Panel { // manageIpc: false so this panel can own the single IpcHandler the target // permits — needed for the togglePercentage method below. manageIpc: false - // Orchard: the battery state lives in Status.qml, which the status cluster - // and the lock share; these names stay the panel's. - Status { id: status } - readonly property var batteryInfo: status.batteryInfo - readonly property bool externalPower: status.externalPower + readonly property var batteryInfo: Commons.BatteryStatus.batteryInfo + readonly property bool externalPower: Commons.BatteryStatus.externalPower property var profiles: [] property string activeProfile: "" property int profileIndex: 0 @@ -28,9 +25,9 @@ Panel { // icon, so the open-panel mark takes the painted width instead of the // icon-sized fraction of the slot the fallback assumes. readonly property real openPanelIndicatorWidth: showPercentage && !button.vertical ? button.glyphPaintedWidth : 0 - readonly property var batteryDevice: status.batteryDevice - readonly property bool batteryPresent: status.batteryPresent - readonly property var displayedPercentage: status.displayedPercentage + readonly property var batteryDevice: Commons.BatteryStatus.batteryDevice + readonly property bool batteryPresent: Commons.BatteryStatus.batteryPresent + readonly property var displayedPercentage: Commons.BatteryStatus.displayedPercentage function upowerStates() { return { @@ -157,7 +154,7 @@ Panel { : Commons.I18n.t("power.noBattery", "No battery found") function refresh() { - status.refresh() + Commons.BatteryStatus.refresh() if (!profilesProc.running) profilesProc.running = true } @@ -242,7 +239,6 @@ Panel { Timer { interval: 5000 - // Status polls the battery independently. running: root.opened repeat: true onTriggered: if (!profilesProc.running) profilesProc.running = true diff --git a/desktop/shell/shell/plugins/status/StatusCluster.qml b/desktop/shell/shell/plugins/status/StatusCluster.qml index 64bb50ee..57ce170c 100644 --- a/desktop/shell/shell/plugins/status/StatusCluster.qml +++ b/desktop/shell/shell/plugins/status/StatusCluster.qml @@ -5,7 +5,6 @@ import qs.Commons import qs.Commons as Commons import "../panels/network" as Network import "../panels/bluetooth" as BluetoothStatus -import "../panels/power" as Power // The status cluster (SHELL-SPEC, step 2): mic muted, rotation lock, Focus // and Stay Awake while on, Bluetooth while on, Wi-Fi, battery percentage and @@ -28,7 +27,7 @@ Row { Network.Status { id: network } BluetoothStatus.Status { id: bluetooth } - Power.Status { id: battery } + readonly property var battery: Commons.BatteryStatus RotationLock { id: rotation } readonly property var source: Pipewire.defaultAudioSource From 1303f13b81133699249a013cfdde1adebe3a9f73 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Berkay=20K=C3=B6sebay?= Date: Tue, 1 Dec 2026 18:02:11 +0100 Subject: [PATCH 12/17] brightness: release the light sensor while the panel sleeps MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Assisted-by: LLM Signed-off-by: Berkay Kösebay --- desktop/configuration/auto-brightness | 74 ++++++++++++++++++--------- 1 file changed, 50 insertions(+), 24 deletions(-) diff --git a/desktop/configuration/auto-brightness b/desktop/configuration/auto-brightness index 6571893c..484c6516 100755 --- a/desktop/configuration/auto-brightness +++ b/desktop/configuration/auto-brightness @@ -29,7 +29,7 @@ import time IIO_ROOT = "/sys/bus/iio/devices" BACKLIGHT_ROOT = "/sys/class/backlight" -TICK = 0.1 +STATE_INTERVAL = 2.0 # powerd's als-state is request/reply, without change notifications RAMP_TICK = 1.0 / 30 # loop period while a ramp runs: small, frequent steps look like a fade RAMP_GAMMA = 2.2 # ramp in perceived brightness (raw ~ perceived ** gamma), not raw PWM RAMP_MIN_SECS, RAMP_MAX_SECS = 0.3, 3.0 @@ -326,15 +326,15 @@ class IioSource: def __init__(self, root, hz): self.root = root - self.interval = 1.0 / max(hz, 0.5) + self.interval = max(STATE_INTERVAL, 1.0 / hz) if hz > 0 else STATE_INTERVAL self.due = 0.0 self.warned = False def poll(self, timeout): - wait = max(0.0, min(timeout, self.due - time.monotonic())) - time.sleep(wait) - if time.monotonic() < self.due: - return [] + remaining = self.due - time.monotonic() + if remaining > 0: + time.sleep(min(timeout, remaining)) + return [] # recheck the panel before touching the sensor self.due = time.monotonic() + self.interval dev = find_iio_light(self.root) lux = read_iio_lux(dev) if dev else None @@ -423,6 +423,7 @@ class ProxySource: self.master = None self.buf = b"" self.retry_at = 0.0 + self.cmd = None @staticmethod def command(): @@ -439,13 +440,19 @@ class ProxySource: return cmd def start(self): - cmd = self.command() + if self.cmd is None: + self.cmd = self.command() master, slave = pty.openpty() - self.proc = subprocess.Popen(cmd, stdin=subprocess.DEVNULL, stdout=slave, stderr=slave, close_fds=True) - os.close(slave) + try: + self.proc = subprocess.Popen(self.cmd, stdin=subprocess.DEVNULL, stdout=slave, stderr=slave, close_fds=True) + except OSError: + os.close(master) + raise + finally: + os.close(slave) self.master = master self.buf = b"" - log("started", " ".join(cmd)) + log("started", " ".join(self.cmd)) def stop(self): if self.proc: @@ -454,6 +461,7 @@ class ProxySource: self.proc.wait(timeout=3) except subprocess.TimeoutExpired: self.proc.kill() + self.proc.wait() if self.master is not None: os.close(self.master) self.proc = self.master = None @@ -603,6 +611,7 @@ class Daemon: self.moves = 0 self.stop = False self.shown = None + self.last_status = None # -- helpers def tolerance(self): @@ -623,8 +632,11 @@ class Daemon: if not is_enabled(conf): self.pause("off") self.write_status(now, enabled=False) - return + return False + raw = self.backlight.read() hold = [] if self.dry else holds() + if raw is None or raw <= 0: + hold = hold or ["backlight"] if hold != self.hold: if hold: log("holding for", ", ".join(hold)) @@ -634,10 +646,7 @@ class Daemon: if hold or now < self.settle_until: self.pause("hold") self.write_status(now, enabled=True) - return - raw = self.backlight.read() - if raw is None: - return + return False # A change we didn't make: a brightness key, the menu. if self.last_written is not None and abs(raw - self.last_written) > self.tolerance(): self.override_until = now + conf["override_secs"] @@ -646,7 +655,7 @@ class Daemon: self.pause("manual change") if now < self.override_until: self.write_status(now, enabled=True, override=self.override_until - now) - return + return True if not self.active: self.active = True log("auto-brightness on") @@ -668,6 +677,7 @@ class Daemon: if self.goal_raw is not None: self.step(raw, now) self.write_status(now, enabled=True) + return True # Perceived brightness in [0, 1]: equal steps here look equal on the panel. def perceived(self, raw): @@ -728,13 +738,15 @@ class Daemon: "hold": self.hold, "override_secs_left": round(override, 1), "moves": self.moves, - "time": time.time(), } + if data == self.last_status: + return tmp = status_path() + ".tmp" try: with open(tmp, "w") as f: - json.dump(data, f) + json.dump(dict(data, time=time.time()), f) os.replace(tmp, status_path()) + self.last_status = data except OSError: pass @@ -749,13 +761,27 @@ class Daemon: os.kill(int(compositor), 0) except (OSError, ValueError): break - if not is_enabled(self.conf): - self.tick(time.monotonic()) - time.sleep(1) # off means no 10Hz backlight/status work + now = time.monotonic() + wait = STATE_INTERVAL if end is None else min(STATE_INTERVAL, max(0, end - now)) + if not self.tick(now): + if isinstance(self.source, ProxySource): + self.source.stop() # dropping monitor-sensor releases its ClaimLight + self.latest = None + if now < self.settle_until: + wait = min(wait, self.settle_until - now) + time.sleep(wait) continue - for lux in self.source.poll(RAMP_TICK if self.ramping() else TICK): + # Reuse the last signalled lux while the median and low-pass filter + # settle. Stable light needs no intermediate policy ticks. + if self.latest is not None and now >= self.override_until: + target = max(0.0, self.latest * self.conf["lux_scale"]) + if (self.smoother.level is None or self.smoother.readings != [target] * self.smoother.window + or abs(math.log1p(target) - self.smoother.level) > 0.001): + wait = min(wait, max(0.0, self.next_sample - now)) + if self.ramping(): + wait = min(wait, RAMP_TICK) + for lux in self.source.poll(wait): self.latest = lux - self.tick(time.monotonic()) self.source.close() try: os.unlink(status_path()) @@ -843,7 +869,7 @@ def main(): os.kill(int(compositor), 0) except (OSError, ValueError): return 0 - time.sleep(1) + time.sleep(STATE_INTERVAL) name = find_backlight(conf["backlight"]) source = make_source(args, conf) daemon = Daemon(conf, source, Backlight(name), args.dry_run, args.debug) From a6aa1b2e4697a92b8eebd3cce90a5dfe66fb8b68 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Berkay=20K=C3=B6sebay?= Date: Tue, 1 Dec 2026 18:02:11 +0100 Subject: [PATCH 13/17] rotation: block on sensor, unlock and compositor events MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Assisted-by: LLM Signed-off-by: Berkay Kösebay --- desktop/configuration/rotate-output | 91 ++++++++++++++++++++++++----- 1 file changed, 76 insertions(+), 15 deletions(-) diff --git a/desktop/configuration/rotate-output b/desktop/configuration/rotate-output index 284ca368..747bf370 100644 --- a/desktop/configuration/rotate-output +++ b/desktop/configuration/rotate-output @@ -206,6 +206,22 @@ def apply(value, speaker_transform=None): return True +def watch_unlock(lock): + # Watch the existing inode, so removing the lock wakes a settled pose + # even when monitor-sensor has nothing more to say. + import ctypes + libc = ctypes.CDLL(None) + if not hasattr(libc, 'inotify_init1'): + return None + fd = libc.inotify_init1(os.O_CLOEXEC | os.O_NONBLOCK) + if fd < 0: + return None + if libc.inotify_add_watch(fd, os.fsencode(lock), 0x400 | 0x800) < 0: # DELETE_SELF | MOVE_SELF + os.close(fd) + return None + return fd + + def main(): lock = Path(os.environ.get('XDG_CONFIG_HOME', str(Path.home() / '.config'))) / 'omarchy/rotation-lock' state = Orientation(float(os.environ.get('ROTATE_SETTLE', '.4')), @@ -237,23 +253,63 @@ def main(): process.stdout.close() monitor = start_monitor() restart_at = None + retry_apply_at = 0.0 + lock_fd = parent_fd = None running = True def stop(*_): - nonlocal running - running = False + raise SystemExit(0) # interrupt even an indefinite selector wait signal.signal(signal.SIGTERM, stop) signal.signal(signal.SIGINT, stop) buffered = b'' eof = False try: + if parent and hasattr(os, 'pidfd_open'): + try: + parent_fd = os.pidfd_open(parent) + except ProcessLookupError: + return + except OSError: + pass # older kernels: fall back to the liveness check + else: + selector.register(parent_fd, selectors.EVENT_READ, 'parent') while running: - if parent: + now = time.monotonic() + deadlines = [] + if parent and parent_fd is None: try: os.kill(parent, 0) except ProcessLookupError: break - wait_s = 0.1 if (state.waiting() or eof) else 1.0 - for key, _ in selector.select(wait_s): + deadlines.append(now + 2) + if not sensors and not saw_proxy and discovery_timeout > 0: + deadlines.append(started + discovery_timeout) + if restart_at is not None: + deadlines.append(restart_at) + if eof and not parent: + deadlines.append(state.since + state.settle + state.cooldown + 5) + if state.waiting(): + if lock.exists(): + if lock_fd is None: + lock_fd = watch_unlock(lock) + if lock_fd is not None: + selector.register(lock_fd, selectors.EVENT_READ, 'unlock') + if lock_fd is None: + deadlines.append(now + 2 if lock.exists() else now) + elif now < retry_apply_at: + deadlines.append(retry_apply_at) + elif motion: + deadlines.append(now + 0.1) # gravity only while a turn is settling + else: + deadlines.append(max(state.since + state.settle, state.last_apply + state.cooldown)) + wait = max(0.0, min(deadlines) - now) if deadlines else None + for key, _ in selector.select(wait): + if key.data == 'parent': + return + if key.data == 'unlock': + selector.unregister(lock_fd) + os.close(lock_fd) + lock_fd = None + continue data = os.read(key.fd, 8192) if not data: eof = True @@ -273,6 +329,8 @@ def main(): if value is not None: saw_proxy = True trace(f'sensor orientation={value}') + if value != state.pending: + retry_apply_at = 0.0 state.observe(value, time.monotonic()) now = time.monotonic() if not running: @@ -280,30 +338,32 @@ def main(): if not sensors and not saw_proxy and discovery_timeout > 0 and now - started >= discovery_timeout: print('rotation: no accelerometer or iio-sensor-proxy after discovery window; exiting', flush=True) break + locked = lock.exists() if motion: - if state.waiting(): + if state.waiting() and not locked and now >= retry_apply_at: motion.sample(now) else: motion.forget() - value = state.ready(now, lock.exists(), bool(motion and motion.turning()), + value = state.ready(now, locked, bool(motion and motion.turning()), motion.trusted_facing() if motion else None) - if value is not None: + if value is not None and now >= retry_apply_at: trace(f'stable orientation={value} waited_ms={(now - state.since) * 1000:.0f}') try: if apply(value, speaker_transform): state.committed(value, now) if motion: motion.judged(value) + else: + retry_apply_at = now + 60 # no eligible output except (OSError, subprocess.SubprocessError) as error: print(f'rotation failed: {error}', flush=True) - state.last_apply = now # bounded retry; never mark failure applied + retry_apply_at = now + 2 if eof: # No accelerated apply on EOF: wait out any pending stability window. - if not (lock.exists() or state.pending is None or state.pending == state.applied - or now - state.since > state.settle + state.cooldown + 5): - continue if not parent: - break + if locked or not state.waiting() or now >= state.since + state.settle + state.cooldown + 5: + break + continue # Inside a session the sensor reader may end (iio-sensor-proxy # not up yet at login, or restarted). Rotation must not stay # dead until the next login: start it again, at most every 2 s. @@ -314,10 +374,11 @@ def main(): stop_monitor(monitor) monitor = start_monitor() buffered, eof, restart_at = b'', False, None - else: - time.sleep(.1) finally: selector.close() + for fd in (lock_fd, parent_fd): + if fd is not None: + os.close(fd) stop_monitor(monitor) From ad15ca0a24c34f3a03c8e10d1b5a7d095cc1a41f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Berkay=20K=C3=B6sebay?= Date: Tue, 1 Dec 2026 18:02:12 +0100 Subject: [PATCH 14/17] docs: record helper costs and the idle measurement procedure MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Assisted-by: LLM Signed-off-by: Berkay Kösebay --- docs/tablet-sensors.md | 25 +++++++++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) diff --git a/docs/tablet-sensors.md b/docs/tablet-sensors.md index fc017b0d..52d6d8f7 100644 --- a/docs/tablet-sensors.md +++ b/docs/tablet-sensors.md @@ -2,7 +2,7 @@ Orientation already comes from iio-sensor-proxy and the kernel's accelerometer mount matrix. Labwc maps touch to the panel, so display and touch rotate together. This remains the native orientation path; no extra board matrix or second sensor reader is installed. -The Display panel's Rotation Lock and `omarchy-rotation-lock on|off|toggle|status` use the same lock as the orientation helper. While locked the helper keeps watching; after unlock it applies the last settled pose even without a new sensor event. Undefined/flat poses stay ignored and the existing half-second settling remains. The helper exits with labwc. +The Display panel's Rotation Lock and `omarchy-rotation-lock on|off|status` use the same lock as the orientation helper. While locked the helper keeps watching; after unlock it applies the last settled pose even without a new sensor event. Undefined/flat poses stay ignored and the default settling time is 0.4 s. The helper exits with labwc. Auto Brightness uses the existing tablet ALS curve, smoothing, hysteresis, ramp and manual-change pause policy. It is **off by default** because panel/light calibration still needs device validation. Enable it with the Auto Brightness switch in the Display panel, or: @@ -14,7 +14,7 @@ omarchy-auto-brightness off It reads generic IIO lux or iio-sensor-proxy. Missing sensors are harmless; the switch appears when an IIO light sensor and panel exist. Its process follows the compositor lifetime. Logs are in `$XDG_RUNTIME_DIR/arch-ipad-auto-brightness.log`; `--list` shows discovery and `--probe 20` computes a dry run without backlight writes. -User preferences live in `~/.config/omarchy/als-brightness.conf` and the switch is saved in `~/.local/state/omarchy/display`. Optional configuration keys are `enabled`, `backlight`, `curve`, `min_pct`, `max_pct`, `lux_scale`, `smooth_secs`, `hysteresis`, `min_pct_step`, `min_interval`, `ramp_pct_per_s`, `override_secs`, and `poll_hz`. The default curve is `0:10, 5:18, 20:30, 80:50, 250:70, 700:90, 1500:100` (lux:percent). Readings pass through a five-sample median and log-lux smoothing. Manual changes pause automatic adjustment for 30 seconds. +User preferences live in `~/.config/omarchy/als-brightness.conf` and the switch is saved in `~/.local/state/omarchy/display`. Optional configuration keys are `enabled`, `backlight`, `curve`, `min_pct`, `max_pct`, `lux_scale`, `smooth_secs`, `hysteresis`, `min_pct_step`, `min_interval`, `ramp_pct_per_s`, `override_secs`, and `poll_hz`. The default curve is `0:15, 5:25, 20:38, 80:58, 250:78, 700:94, 1500:100` (lux:percent). Readings pass through a three-sample median and log-lux smoothing. Manual changes pause automatic adjustment for 30 seconds. Automatic writes use omarchy-powerd's control socket, serialized with its existing screen/sleep/wake state machine. The request names the panel and supplies the expected old raw value. Powerd accepts only positive, in-range levels for that panel while lit and rejects stale values. A dark panel, unavailable power daemon or manual edit therefore stops a ramp. Wake still restores the level through powerd before automatic adjustment resumes. No brightnessctl helper, root user daemon or passwordless brightness sudo rule is added. @@ -23,6 +23,27 @@ Both fresh desktop staging and the public-root builder include the helper and it Host checks cover the retained light policy, switch state, missing power daemon, stale-value/dark-panel refusal, manual pause, actual socket writes, rotation debounce/lock/unlock and compositor exit, plus staging and public-root inclusion. Physical lux response, all four orientation directions, touch mapping and power-button/idle/sleep coexistence still need a device run. +## Background helper cost + +On 2026-12-01, a 60-second shell profile on the iPhone 5 attributed 4.2% of samples to the battery helper and 3.4% to `awk`. At idle, auto-brightness used about 2% CPU and iio-sensor-proxy 1.4%. Process RSS was 15 MB for auto-brightness, 12 MB each for rotation and the keyboard listener, and 21 MB for the separate power daemon. + +- Battery views now share one sysfs snapshot per shell process. UPower source, presence, percentage and state changes refresh it, as does opening the power panel. The fallback runs every 60 s. Previously each view launched a reader every 5 s. The reader formats the same tab-separated fields with Bash builtins. +- Auto-brightness follows light changes through `monitor-sensor`. Direct IIO reads are at least 2 s apart. Powerd exposes its light state by request, so the helper checks it at most 2 s apart while idle. Off, a dark or unreadable backlight, or a powerd hold releases the light claim and stops IIO reads. After a hold, wake gets its existing 1 s to settle. Filtering a light change and animating a fade still use shorter timers. +- Rotation blocks on the accelerometer monitor, compositor exit and removal of a pending rotation lock on Linux. It samples raw acceleration every 100 ms only while judging a turn. The keyboard listener already sleeps on labwc stdin and its control socket, with a 250 ms deadline for a pending hide. + +For an on-device comparison, use the same shell layout, charge state and ambient light on both revisions. Collect an idle minute with the panel lit. Repeat with the screen dark, then check charger, orientation and keyboard transitions separately. + +```sh +ps -eo pid,ppid,rss,pcpu,args | grep -E '[a]uto-brightness|[r]otate-output|[o]marchy-keyboard listen|[i]io-sensor-proxy|[o]marchy-powerd' +helpers=$(pgrep -d, -f '([a]rch-ipad-(auto-brightness|rotate-output)|[o]marchy-keyboard listen|[i]io-sensor-proxy)') +pidstat -u -w -p "$helpers" 1 60 +shell_pid=$(pgrep -of '(^|/)qs -p /usr/share/omarchy/shell/shell[.]qml$') +perf record -o /var/tmp/omarchy-shell-idle.data -e cpu-clock -F 99 -p "$shell_pid" -- sleep 60 +perf report -i /var/tmp/omarchy-shell-idle.data --stdio --no-children --sort comm,dso +``` + +With steady power, expect one scheduled battery invocation per minute per shell and zero `awk` children from it. After settling, the target for each Python helper is below 0.5% of one core over the minute. Rotation still claims the accelerometer, so darkening the screen need not take iio-sensor-proxy to zero. Check that the light monitor disappears while dark and that the first light change after wake adjusts the panel. RSS savings from replacing Python are a separate proposal. + ## Side mute switch The kernel reports the ring/silent switch (iPhone, older iPads) as `KEY_MUTE` of the `gpio-keys` input device, held down while the switch is on silent. `omarchy-mute-switch` (`/usr/libexec`, started by the session's autostart) mutes the default output while the switch is on silent and unmutes it on ring: quietly at login, with the volume OSD (`omarchy-volume mute-on|mute-off`) when the switch is moved. A suspend and resume, which the kernel reports as a release and a press, changes nothing. Without such a switch it exits at once; it ends with labwc. Logs are in `$XDG_RUNTIME_DIR/omarchy-mute-switch.log`. From fa0e10a36f8637c45bffee7c73d035cfe29590e6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Berkay=20K=C3=B6sebay?= Date: Tue, 1 Dec 2026 18:02:12 +0100 Subject: [PATCH 15/17] docs: propose a single native session helper for light, rotation and keyboard MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Assisted-by: LLM Signed-off-by: Berkay Kösebay --- docs/native-session-helper-proposal.md | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 docs/native-session-helper-proposal.md diff --git a/docs/native-session-helper-proposal.md b/docs/native-session-helper-proposal.md new file mode 100644 index 00000000..5cecd74d --- /dev/null +++ b/docs/native-session-helper-proposal.md @@ -0,0 +1,21 @@ +# Proposal for one native sensor and keyboard daemon + +On the iPhone 5, auto-brightness, rotation and the keyboard policy listener occupy about 15, 12 and 12 MB RSS respectively. Replace those three resident Python processes with one unprivileged C process per labwc session. Budget 3–6 MB RSS for the daemon, including its loaded libraries. That would save roughly **33–36 MB of summed RSS** against the measured 39 MB. Shared Python pages count in more than one process, so the actual RAM recovered will be smaller. Measure summed PSS from `/proc/PID/smaps_rollup` before and after. The estimate excludes powerd, iio-sensor-proxy, the light/acceleration monitor clients and the visible keyboard program. + +## Build and lifetime + +Add one target to the existing Makefile alongside the C Wayland helpers. Use the existing compiler and pkg-config path for armv7h and aarch64. Use libsystemd's sd-event and sd-bus for the event loop, the system bus, fd watches and timers. Install the binary and compatibility entry points through `desktop/install-tree`. + +Start the daemon from the packaged labwc autostart. Keep labwc's existing `omarchy-keyboard listen` command. It can pass its stdin pipe to the daemon over a private Unix socket using `SCM_RIGHTS` and exit immediately. Allow either entry point to start the owner under a runtime lock, since labwc may send facts before autostart runs. On EOF detach the keyboard policy. On compositor exit release sensor claims, close all descriptors and remove the session socket. A sensor arriving late, disappearing or losing its D-Bus owner must allow the other policies to continue. + +## Interfaces to preserve + +| Policy | Compatibility contract | +| --- | --- | +| Light | Keep both helper names, CLI switches, probe/list and dry-run modes, config keys, the `display` preference file and existing status JSON. Claim/release light on `net.hadess.SensorProxy`, consume `LightLevel` in lux, and retain slow IIO fallback. Port the median, asymmetric smoothing, hysteresis, perceptual fade and manual override. Keep the `als-state` and `brightness PANEL NEW EXPECTED` exchanges on powerd's socket. | +| Rotation | Consume the proxy's accelerometer orientation, retain the mount-matrix and bounded motion check, debounce, cooldown and lock/unlock semantics. Keep the rotation-lock file, internal-output selection, transform mapping and optional speaker-transform publication. Issue the Wayland output request only for a settled change. | +| Keyboard | Accept the same newline-delimited labwc facts, manual actions on `$XDG_RUNTIME_DIR/omarchy-keyboard.sock`, and the CLI's hold/release and show/hide behavior. Retain the tap, drag, hardware-key and delayed-hide policy, the visibility and PID files, and wvkbd's SIGUSR1/SIGUSR2 contract. The themed keyboard still runs as its own Wayland client. | + +## Acceptance + +Replay the inputs in the existing policy tests. On the iPhone 5, compare RSS, PSS and 60 s of idle CPU with the same shell and sensor claims. Exercise a dark/wake cycle, manual brightness, a locked half-turn and unlock, keyboard hold/release, and a sensor-proxy restart. The first target is a single resident policy PID at or below 6 MB RSS, zero light reads while dark and no recurring keyboard or rotation wakeups while settled. Powerd continues to own lock, screen power and suspend. From 589ad9de7846f989ff8a5dbda80b1d6c6b9cca0a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Berkay=20K=C3=B6sebay?= Date: Tue, 1 Dec 2026 18:02:12 +0100 Subject: [PATCH 16/17] powerd: watch playback with one pw-dump --monitor instead of polling MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit While the screen was dark, the playback worker ran busctl and a full pw-dump every second: 7.3 % CPU on the iPhone 5 with nothing to do. It now keeps one pw-dump --monitor per dark period and re-reads BlockInhibited only on logind PropertiesChanged (and right before suspend). Falls back to a 10 s pw-dump poll if the monitor fails. iPhone 5, screen dark: 7.27 % -> 0.23 % CPU, 1 wakeup/s. A test tone posts playing/not-playing at its start and end. Assisted-by: LLM Signed-off-by: Berkay Kösebay --- system/overlay/usr/libexec/omarchy-powerd | 177 +++++++++++++++++----- tests/test_powerd.py | 22 ++- 2 files changed, 153 insertions(+), 46 deletions(-) diff --git a/system/overlay/usr/libexec/omarchy-powerd b/system/overlay/usr/libexec/omarchy-powerd index 37b2ccc3..46e70f67 100755 --- a/system/overlay/usr/libexec/omarchy-powerd +++ b/system/overlay/usr/libexec/omarchy-powerd @@ -12,6 +12,7 @@ import os from pathlib import Path import pwd import queue +import re import select import signal import socket @@ -305,17 +306,24 @@ def parse_logind_started(line): return False -def streams_running(dump): - """Whether `pw-dump` output has an audio or video playback stream that is running.""" - try: - for item in json.loads(dump): - info = item.get('info') or {} - media = (info.get('props') or {}).get('media.class', '') - if media.startswith('Stream/Output/') and info.get('state') == 'running': - return True - except (ValueError, AttributeError): - pass - return False +def update_streams(streams, dump): + """Apply one pw-dump array. Objects absent from a monitor update still exist.""" + objects = json.loads(dump) + if not isinstance(objects, list): + raise ValueError('expected a pw-dump array') + for item in objects: + ident = item['id'] + info = item.get('info') or {} + media = (info.get('props') or {}).get('media.class', '') + if media.startswith('Stream/Output/'): + streams[ident] = (media, info.get('state')) + else: + streams.pop(ident, None) + return any(state == 'running' for _, state in streams.values()) + + +# pw-dump ends each pretty-printed array with ']' in column zero. +DUMP_END = re.compile(rb'^(?:\]|\[.*\])[ \t]*\r?\n', re.MULTILINE) EV_KEY, KEY_VOLUMEDOWN, KEY_POWER, KEY_HOMEPAGE = 1, 114, 116, 172 @@ -521,13 +529,13 @@ def command(*argv, timeout=5, **options): return subprocess.run(argv, capture_output=True, text=True, timeout=timeout, **options) -def session_user(): +def session_user(*, check=False): """The desktop user on seat0, or None for the greeter (nothing to lock) or no session.""" - session = command('loginctl', 'show-seat', 'seat0', '-p', 'ActiveSession', '--value').stdout.strip() + session = command('loginctl', 'show-seat', 'seat0', '-p', 'ActiveSession', '--value', check=check).stdout.strip() if not session: return None fields = dict(line.split('=', 1) for line in - command('loginctl', 'show-session', session, '-p', 'Name', '-p', 'Class').stdout.splitlines() + command('loginctl', 'show-session', session, '-p', 'Name', '-p', 'Class', check=check).stdout.splitlines() if '=' in line) if fields.get('Class') != 'user' or not fields.get('Name'): return None @@ -539,11 +547,11 @@ def user_env(user): 'OMARCHY_PATH': SHELL_ROOT, 'PATH': '/usr/local/bin:/usr/bin'} -def spawn_as_user(user, *argv, env=None): +def spawn_as_user(user, *argv, env=None, stdout=subprocess.DEVNULL): """Start ARGV as the user and return at once (as_user waits for it).""" return subprocess.Popen(('setpriv', f'--reuid={user.pw_uid}', f'--regid={user.pw_gid}', '--init-groups', '--', *argv), env={**user_env(user), **(env or {})}, cwd='/', - stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, + stdin=subprocess.DEVNULL, stdout=stdout, stderr=subprocess.DEVNULL, start_new_session=True) @@ -586,7 +594,8 @@ class Daemon: self.cancel = threading.Event() self.dim_saved = None self.dim_level = None - self.dark = threading.Event() + self.playback = None + self.playback_fallback_logged = False self.session_jobs = queue.Queue() self.inhibitor = None self.monitor = None @@ -739,8 +748,20 @@ class Daemon: self.monitor = subprocess.Popen( ['busctl', '--json=short', 'monitor', LOGIND, "--match=type='signal',interface='org.freedesktop.login1.Manager',member='PrepareForSleep'", + "--match=type='signal',path='/org/freedesktop/login1',interface='org.freedesktop.DBus.Properties'," + "member='PropertiesChanged',arg0='org.freedesktop.login1.Manager'", f"--match=type='signal',sender='org.freedesktop.DBus',member='NameOwnerChanged',arg0='{LOGIND}'"], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, bufsize=0) + self.refresh_playback_inhibitor() + + def refresh_playback_inhibitor(self): + # A block inhibitor can be released without a PipeWire change. Re-read it on + # logind notifications (also after reconnect), and keep the final pre-suspend check. + if self.playback is not None: + try: + self.playback.send(b'.') + except BlockingIOError: + pass # a refresh is already pending def read_monitor(self): chunk = os.read(self.monitor.stdout.fileno(), 65536) @@ -757,6 +778,10 @@ class Daemon: log('logind started') self.logind_asleep = False # a new logind is in no sleep self.renew_inhibitor() + self.refresh_playback_inhibitor() + return + if 'PropertiesChanged' in line and 'BlockInhibited' in line: + self.refresh_playback_inhibitor() return sleeping = parse_sleep_signal(line) if sleeping is None: @@ -792,7 +817,15 @@ class Daemon: log(f't={when:.6f} {event}: {before} -> {self.machine.state} {" ".join(actions) or "-"}') for action in actions: getattr(self, 'do_' + action.replace('-', '_'))(before) - self.dark.set() if self.machine.state in (SETTLING, DARK) else self.dark.clear() + if self.machine.state in (SETTLING, DARK): + if self.playback is None: + self.playback, wake = socket.socketpair() + self.playback.setblocking(False) + threading.Thread(target=self.playback_worker, args=(self.playback, wake, self.machine.playing), + daemon=True).start() + elif self.playback is not None: + self.playback.close() # wake the worker even when PipeWire has no updates + self.playback = None def undim(self): panel = self.backlight() @@ -980,6 +1013,7 @@ class Daemon: def block_inhibited(self): result = command('busctl', 'get-property', 'org.freedesktop.login1', '/org/freedesktop/login1', 'org.freedesktop.login1.Manager', 'BlockInhibited') + result.check_returncode() return 'sleep' in result.stdout def request_suspend(self): @@ -1058,23 +1092,87 @@ class Daemon: time.sleep(0.1) return False - def playback_worker(self): - while not self.stopping: - self.dark.wait(1) - if not self.dark.is_set(): - continue - try: - user = session_user() - playing = self.block_inhibited() or ( - user is not None and streams_running(as_user(user, 'pw-dump', timeout=2).stdout)) - except (OSError, KeyError, ValueError, subprocess.SubprocessError) as error: - # No answer is not "nothing is playing". - log(f'playback check: {error}') - time.sleep(1) - continue - if playing != self.machine.playing: - self.post('playing' if playing else 'not-playing') - time.sleep(1) + def playback_fallback(self, error): + if not self.playback_fallback_logged: + log(f'playback monitor: {error}; polling every 10 s') + self.playback_fallback_logged = True + + def playback_worker(self, session, wake, playing): + monitor = None + fallback = False + audio = blocked = None + next_audio = next_inhibitor = 0 + pending = bytearray() + streams = {} + try: + while self.playback is session and not self.stopping: + now = time.monotonic() + if now >= next_inhibitor: + try: + blocked = self.block_inhibited() + next_inhibitor = float('inf') + except (OSError, subprocess.SubprocessError): + blocked, next_inhibitor = None, now + 10 + if now >= next_audio and self.playback is session: + next_audio = now + 10 + user = None + try: + user = session_user(check=True) + if self.playback is not session: + break + if user is None: + audio = False + elif fallback: + result = as_user(user, 'pw-dump', timeout=2) + result.check_returncode() + audio = update_streams({}, result.stdout) + else: + monitor = spawn_as_user(user, 'pw-dump', '--monitor', '--no-colors', stdout=subprocess.PIPE) + next_audio = float('inf') + except (OSError, KeyError, TypeError, AttributeError, ValueError, subprocess.SubprocessError) as error: + audio = None + if not fallback and user is not None: + self.playback_fallback(error) + fallback = True + + # Either source may keep us awake. Silence requires two successful answers. + active = bool(audio or blocked) + known = active or (audio is not None and blocked is not None) + if known and active != playing: + self.post((session, 'playing' if active else 'not-playing')) + playing = active + + deadline = min(next_audio, next_inhibitor) + delay = None if deadline == float('inf') else max(0, deadline - time.monotonic()) + ready, _, _ = select.select([wake, monitor.stdout] if monitor else [wake], [], [], delay) + if wake in ready: + if not wake.recv(4096): + break + next_inhibitor = 0 + if monitor and monitor.stdout in ready: + try: + chunk = os.read(monitor.stdout.fileno(), 65536) + if not chunk: + raise ValueError('pw-dump exited') + # The closing line may be split across reads. + start = pending.rfind(b'\n') + 1 + pending.extend(chunk) + while end := DUMP_END.search(pending, start): + audio = update_streams(streams, pending[:end.end()]) + del pending[:end.end()] + start = 0 + except (OSError, KeyError, TypeError, AttributeError, ValueError) as error: + self.playback_fallback(error) + monitor.terminate() + monitor.wait() + monitor.stdout.close() + monitor, audio, fallback, next_audio = None, None, True, 0 + finally: + wake.close() + if monitor is not None: + monitor.terminate() + monitor.wait() + monitor.stdout.close() # --- control socket ----------------------------------------------------- def control(self, server): @@ -1251,8 +1349,7 @@ class Daemon: self.take_inhibitor() self.start_monitor() self.start_uevents() - for worker in (self.session_worker, self.playback_worker): - threading.Thread(target=worker, daemon=True).start() + threading.Thread(target=self.session_worker, daemon=True).start() log('ready: ON') while not self.stopping: delay = self.timeout() @@ -1298,7 +1395,11 @@ class Daemon: os.read(self.wake_read, 512) while not self.events.empty(): event = self.events.get() - if event.startswith('sleep-over '): + if isinstance(event, tuple): + session, change = event + if self.playback is session: + self.feed(change) + elif event.startswith('sleep-over '): if int(event.split()[1]) == self.sleep_record: self.sleep_finished('unit') else: diff --git a/tests/test_powerd.py b/tests/test_powerd.py index cafc9d6c..3d5d0eb9 100644 --- a/tests/test_powerd.py +++ b/tests/test_powerd.py @@ -516,13 +516,19 @@ def owner(name, new): self.assertFalse(powerd.parse_logind_started('Monitoring bus message stream.')) def test_only_a_running_playback_stream_counts(self): - def node(media, state): - return {'info': {'state': state, 'props': {'media.class': media}}} - self.assertTrue(powerd.streams_running(json.dumps([node('Stream/Output/Audio', 'running')]))) - for nodes in ([node('Stream/Output/Audio', 'idle')], [node('Stream/Input/Audio', 'running')], - [node('Audio/Sink', 'running')], [{'type': 'PipeWire:Interface:Core'}], []): - self.assertFalse(powerd.streams_running(json.dumps(nodes))) - self.assertFalse(powerd.streams_running('not json')) + def update(streams, *nodes): + return powerd.update_streams(streams, json.dumps(nodes)) + def node(ident, media, state): + return {'id': ident, 'info': {'state': state, 'props': {'media.class': media}}} + streams = {} + self.assertTrue(update(streams, node(1, 'Stream/Output/Audio', 'running'))) + self.assertTrue(update(streams, node(2, 'Audio/Sink', 'running'))) + self.assertTrue(update(streams, node(3, 'Stream/Output/Video', 'running'))) + self.assertTrue(update(streams, {'id': 1, 'info': None})) + self.assertFalse(update(streams, node(3, 'Stream/Output/Video', 'idle'))) + self.assertFalse(update(streams, node(1, 'Stream/Input/Audio', 'running'))) + with self.assertRaises(ValueError): + powerd.update_streams(streams, 'not json') class Integration(unittest.TestCase): @@ -862,7 +868,7 @@ def setUp(self): ('STATS', self.stats), ('BACKLIGHTS', self.work / 'backlight'), ('BRIGHTNESS', self.remembered), ('WAKEUP_COUNT', self.work / 'wakeup_count'), ('SOCKET', str(self.work / 'ctl')), - ('session_user', lambda: None), ('command', self.fake_command), ('log', lambda *_: None)): + ('session_user', lambda **_: None), ('command', self.fake_command), ('log', lambda *_: None)): patcher = patch.object(powerd, target, value) patcher.start() self.addCleanup(patcher.stop) From 25502611b37e10d358d29acdb9a5faa8827eceed Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Berkay=20K=C3=B6sebay?= Date: Tue, 1 Dec 2026 18:02:13 +0100 Subject: [PATCH 17/17] Run light, rotation and keyboard policy in one native session helper MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Assisted-by: LLM Signed-off-by: Berkay Kösebay --- .github/workflows/build.yml | 4 + Makefile | 12 +- desktop/configuration/auto-brightness | 656 +--------------------- desktop/configuration/rotate-output | 388 +------------ desktop/install-tree | 3 +- desktop/session/keyboard.c | 243 ++++++++ desktop/session/light.c | 601 ++++++++++++++++++++ desktop/session/main.c | 578 +++++++++++++++++++ desktop/session/rotation.c | 312 ++++++++++ desktop/session/session.h | 50 ++ desktop/shell/bin/omarchy-keyboard | 181 +----- desktop/shell/default/labwc/autostart | 6 +- docs/native-session-trial.md | 93 +++ docs/tablet-sensors.md | 6 + release/audit.py | 5 +- system/overlay/usr/libexec/omarchy-powerd | 11 +- tests/package_tree.py | 2 +- tests/session_replay.py | 37 ++ tests/test_auto_brightness.py | 220 +++++--- tests/test_keyboard_policy.py | 41 +- tests/test_package.py | 2 +- tests/test_rotate_output.py | 465 ++++++++------- tools/measure-session-helpers | 49 ++ 23 files changed, 2439 insertions(+), 1526 deletions(-) create mode 100644 desktop/session/keyboard.c create mode 100644 desktop/session/light.c create mode 100644 desktop/session/main.c create mode 100644 desktop/session/rotation.c create mode 100644 desktop/session/session.h create mode 100644 docs/native-session-trial.md create mode 100644 tests/session_replay.py create mode 100755 tools/measure-session-helpers diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 2bf2b3cf..e9f8804b 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -168,6 +168,10 @@ jobs: run: bash ci/dependencies --tools-only env: ORCHARD_REF: main + - name: Install native policy replay dependencies + run: | + sudo apt-get install -y libsystemd-dev + .venv/bin/pip install dbus-next==0.2.3 - run: .venv/bin/python -m unittest discover -s tests -v supported-devices: # The README's chips and devices (between its supported markers) follow diff --git a/Makefile b/Makefile index 02f07514..d7c293ff 100644 --- a/Makefile +++ b/Makefile @@ -5,16 +5,20 @@ # make WVKBD= WTYPE= # make install DESTDIR= OMARCHY= DBUS_NEXT= # -# The only compiles are the on-screen keyboard (wvkbd with this repository's -# patches) and the startup cursor helper (wtype); desktop/install-tree puts -# every file in place. +# desktop/install-tree installs these native binaries with their session entry points. BUILD ?= build CC ?= cc CFLAGS ?= -O2 PKG_CONFIG ?= pkg-config -all: $(BUILD)/wvkbd-mobintl $(BUILD)/wtype +SESSION_SRC := $(wildcard desktop/session/*.c) +all: $(BUILD)/wvkbd-mobintl $(BUILD)/wtype $(BUILD)/omarchy-session-helper + +$(BUILD)/omarchy-session-helper: $(SESSION_SRC) desktop/session/session.h + mkdir -p $(BUILD) + $(CC) $(CPPFLAGS) $(CFLAGS) -D_GNU_SOURCE -std=gnu11 -Wall -Wextra -Wno-unused-parameter \ + $(SESSION_SRC) $$($(PKG_CONFIG) --cflags --libs libsystemd) -lm $(LDFLAGS) -o $@ $(BUILD)/wvkbd-mobintl: @test -d "$(WVKBD)" || { echo 'Set WVKBD to the wvkbd v0.20 source' >&2; exit 1; } diff --git a/desktop/configuration/auto-brightness b/desktop/configuration/auto-brightness index 484c6516..d5a476f4 100755 --- a/desktop/configuration/auto-brightness +++ b/desktop/configuration/auto-brightness @@ -12,49 +12,15 @@ The power daemon serializes automatic brightness with screen-off/sleep/wake. import argparse import glob import json -import math import os -import pty import re -import select -import shlex import shutil -import signal import socket -import stat -import statistics import subprocess import sys -import time IIO_ROOT = "/sys/bus/iio/devices" BACKLIGHT_ROOT = "/sys/class/backlight" -STATE_INTERVAL = 2.0 # powerd's als-state is request/reply, without change notifications -RAMP_TICK = 1.0 / 30 # loop period while a ramp runs: small, frequent steps look like a fade -RAMP_GAMMA = 2.2 # ramp in perceived brightness (raw ~ perceived ** gamma), not raw PWM -RAMP_MIN_SECS, RAMP_MAX_SECS = 0.3, 3.0 -HOLD_SETTLE = 1.0 # let the power daemon finish restoring brightness after wake -# Panel tuning: the initial brightness curve read too dark on Orchard; lifted ~10-20 points at indoor levels. -DEFAULT_CURVE = "0:15, 5:25, 20:38, 80:58, 250:78, 700:94, 1500:100" -DEFAULTS = { - "enabled": False, - "backlight": "", - "curve": DEFAULT_CURVE, - "min_pct": 5.0, - "max_pct": 100.0, - "lux_scale": 1.0, - "smooth_secs": 3.0, # darkening: slow, so a passing shadow does not dim the panel - "smooth_up_secs": 0.4, # brightening: fast, like iOS (a flashlight should not take seconds) - "hysteresis": 0.20, - "min_pct_step": 2.0, - "min_interval": 2.0, - "min_interval_up": 0.25, - "ramp_pct_per_s": 40.0, - "override_secs": 30.0, - "poll_hz": 4.0, -} - - def log(*args): print("omarchy-auto-brightness:", *args, file=sys.stderr, flush=True) @@ -69,60 +35,23 @@ def state_path(): return os.path.join(base, "omarchy", "display") -def runtime_dir(): - return os.path.join(os.environ.get("XDG_RUNTIME_DIR") or "/tmp", "omarchy") - - def status_path(): return os.path.join(os.environ.get("XDG_RUNTIME_DIR") or "/tmp", "omarchy-auto-brightness.json") -def parse_curve(text): - points = [] - for part in text.replace(";", ",").split(","): - part = part.strip() - if not part: - continue - lux, pct = part.split(":") - points.append((float(lux), float(pct))) - points.sort() - if len(points) < 2 or len({p[0] for p in points}) != len(points): - raise ValueError("needs at least two points with different lux") - return points - - def load_conf(): - conf = dict(DEFAULTS) + # The CLI needs only these two values for switch state and discovery. + conf = {"enabled": False, "backlight": ""} try: with open(os.path.join(config_home(), "omarchy", "als-brightness.conf")) as f: - lines = f.read().splitlines() + for line in f: + key, _, value = line.partition("#")[0].partition("=") + if key.strip() == "enabled": + conf["enabled"] = value.strip().lower() in ("on", "yes", "true", "1") + elif key.strip() == "backlight": + conf["backlight"] = value.strip() except OSError: - lines = [] - for line in lines: - line = line.split("#", 1)[0].strip() - # several "key = value" pairs may share a line only in the docs; the - # file takes one per line - if "=" not in line: - continue - key, value = (part.strip() for part in line.split("=", 1)) - if key not in DEFAULTS: - log(f"als-brightness.conf: unknown key {key}") - elif key == "enabled": - conf[key] = value.lower() in ("on", "yes", "true", "1") - elif key in ("backlight", "curve"): - conf[key] = value - else: - try: - conf[key] = float(value) - except ValueError: - log(f"als-brightness.conf: {key} = {value}: not a number") - try: - conf["curve_points"] = parse_curve(conf["curve"]) - except ValueError as e: - log(f"als-brightness.conf: curve = {conf['curve']}: {e}; using the default") - conf["curve_points"] = parse_curve(DEFAULT_CURVE) - conf["min_pct"] = max(0.0, min(conf["min_pct"], 100.0)) - conf["max_pct"] = max(conf["min_pct"], min(conf["max_pct"], 100.0)) + pass return conf @@ -156,95 +85,13 @@ def set_state(key, value): os.replace(tmp, path) -FORCE_ENABLED = False # --probe runs whatever the switch says - - def is_enabled(conf): - if FORCE_ENABLED: - return True value = read_state().get("auto_brightness") if value in ("on", "off"): return value == "on" return conf["enabled"] -# --- the policy (no I/O, so the tests can drive it) ------------------------------- -def curve_pct(points, lux): - """Brightness percent for a lux level: linear in log(1 + lux) between the - points, flat beyond the ends.""" - if lux <= points[0][0]: - return points[0][1] - if lux >= points[-1][0]: - return points[-1][1] - for (x0, y0), (x1, y1) in zip(points, points[1:]): - if x0 <= lux <= x1: - a, b, v = math.log1p(x0), math.log1p(x1), math.log1p(lux) - return y0 + (y1 - y0) * (v - a) / (b - a) - return points[-1][1] - - -class Smoother: - """Median of the last few readings, then a first-order filter in log(1 + lux).""" - - def __init__(self, tau, window=3, tau_up=None): - self.tau, self.window = max(tau, 0.0), window - self.tau_up = self.tau if tau_up is None else max(tau_up, 0.0) - self.readings = [] - self.level = None # log(1 + lux) - self.time = None - - def feed(self, lux, now): - self.readings = (self.readings + [max(lux, 0.0)])[-self.window:] - target = math.log1p(statistics.median(self.readings)) - tau = self.tau_up if self.level is not None and target > self.level else self.tau - if self.level is None or tau == 0: - self.level = target - else: - alpha = 1.0 - math.exp(-max(now - self.time, 0.0) / tau) - self.level += alpha * (target - self.level) - self.time = now - - @property - def lux(self): - return None if self.level is None else math.expm1(self.level) - - -class Policy: - """When to move and to what.""" - - def __init__(self, conf): - self.conf = conf - self.reset() - - def reset(self): - self.ref_level = None # log(1 + lux) at the last move - self.last_move = -1e9 - - def goal(self, lux): - pct = curve_pct(self.conf["curve_points"], lux) - return max(self.conf["min_pct"], min(pct, self.conf["max_pct"])) - - def decide(self, smoothed, now, current_pct): - """The percent to ramp to, or None to stay.""" - goal = self.goal(smoothed.lux) - if self.ref_level is None: - # First move after starting, a pause or a manual change: go now. - if abs(goal - current_pct) < 1.0: - self.ref_level = smoothed.level - return None - else: - if abs(smoothed.level - self.ref_level) < math.log1p(self.conf["hysteresis"]): - return None - if abs(goal - current_pct) < self.conf["min_pct_step"]: - return None - interval = self.conf["min_interval_up"] if goal > current_pct else self.conf["min_interval"] - if now - self.last_move < interval: - return None - self.ref_level = smoothed.level - self.last_move = now - return goal - - # --- the backlight ------------------------------------------------------------------ def read_number(path, default=None): try: @@ -282,24 +129,6 @@ class Backlight: def pct(self, raw): return 100.0 * raw / self.max if self.max else 0.0 - def raw_for(self, pct): - return max(1, min(self.max, int(round(pct * self.max / 100.0)))) - - def write(self, raw, expected=None): - # Compare-and-set is performed by powerd in its event loop, so an - # automatic ramp cannot race its dark/suspend transition or a manual edit. - current = self.read() - if current is None or current <= 0 or (expected is not None and current != expected): - return False - reply = power_request(f"brightness {self.name} {raw} {current}") - ok = reply == "ok" - if not ok and not self.failed and reply != "held": - log("powerd brightness request failed:", reply or "unavailable") - self.failed = not ok - return ok - - -# --- sensor sources: poll(timeout) -> [lux, ...] ----------------------------------------- def find_iio_light(root): """The first IIO device with in_illuminance_input (or raw and scale).""" for dev in sorted(glob.glob(os.path.join(root, "iio:device*"))): @@ -321,198 +150,6 @@ def read_iio_lux(dev): return (raw + offset) * scale -class IioSource: - kind = "iio" - - def __init__(self, root, hz): - self.root = root - self.interval = max(STATE_INTERVAL, 1.0 / hz) if hz > 0 else STATE_INTERVAL - self.due = 0.0 - self.warned = False - - def poll(self, timeout): - remaining = self.due - time.monotonic() - if remaining > 0: - time.sleep(min(timeout, remaining)) - return [] # recheck the panel before touching the sensor - self.due = time.monotonic() + self.interval - dev = find_iio_light(self.root) - lux = read_iio_lux(dev) if dev else None - if lux is None: - if not self.warned: - log("no readable IIO light sensor under", self.root) - self.warned = True - return [] - self.warned = False - return [lux] - - def close(self): - pass - - -class LineSource: - """Lux readings, one number per line, from a FIFO or a file (--mock).""" - - kind = "mock" - - def __init__(self, path): - self.path = path - self.buf = b"" - self.fd = None - self.offset = 0 - self.pending = [] - if not os.path.exists(path): - os.mkfifo(path, 0o600) - self.fifo = stat.S_ISFIFO(os.stat(path).st_mode) - if self.fifo: - self.fd = os.open(path, os.O_RDWR | os.O_NONBLOCK) - else: - with open(path) as f: - self.pending = [v for v in map(self.parse, f.read().splitlines()) if v is not None][-1:] - self.offset = os.path.getsize(path) - - @staticmethod - def parse(line): - line = line.split("#", 1)[0].strip() - try: - return float(line) - except ValueError: - return None - - def poll(self, timeout): - out = list(self.pending) - self.pending = [] - if self.fifo: - ready, _, _ = select.select([self.fd], [], [], timeout) - if ready: - self.buf += os.read(self.fd, 4096) - *lines, self.buf = self.buf.split(b"\n") - out += [self.parse(ln.decode(errors="replace")) for ln in lines] - else: - time.sleep(min(timeout, 0.2)) - try: - size = os.path.getsize(self.path) - except OSError: - size = self.offset - if size < self.offset: - self.offset = 0 - if size > self.offset: - with open(self.path, "rb") as f: - f.seek(self.offset) - data = f.read() - self.offset += len(data) - out += [self.parse(ln.decode(errors="replace")) for ln in data.splitlines()] - return [v for v in out if v is not None] - - def close(self): - if self.fd is not None: - os.close(self.fd) - - -class ProxySource: - """iio-sensor-proxy through monitor-sensor, on a pty so its output isn't - block-buffered. It prints the level when it changes, so the daemon holds - the last value. Restarts monitor-sensor if it exits.""" - - kind = "proxy" - CHANGED = re.compile(r"Light changed:\s*([-+0-9.eE]+)\s*\((\w+)\)") - HAS = re.compile(r"Has ambient light sensor.*?value:\s*([-+0-9.eE]+),\s*unit:\s*(\w+)", re.I) - - def __init__(self): - self.proc = None - self.master = None - self.buf = b"" - self.retry_at = 0.0 - self.cmd = None - - @staticmethod - def command(): - override = os.environ.get("IPAD_ALS_MONITOR_CMD") - if override: - return shlex.split(override) - cmd = ["monitor-sensor"] - try: - help_text = subprocess.run(cmd + ["--help"], capture_output=True, text=True, timeout=5) - if "--light" in help_text.stdout + help_text.stderr: - cmd.append("--light") - except (OSError, subprocess.TimeoutExpired): - pass - return cmd - - def start(self): - if self.cmd is None: - self.cmd = self.command() - master, slave = pty.openpty() - try: - self.proc = subprocess.Popen(self.cmd, stdin=subprocess.DEVNULL, stdout=slave, stderr=slave, close_fds=True) - except OSError: - os.close(master) - raise - finally: - os.close(slave) - self.master = master - self.buf = b"" - log("started", " ".join(self.cmd)) - - def stop(self): - if self.proc: - self.proc.terminate() - try: - self.proc.wait(timeout=3) - except subprocess.TimeoutExpired: - self.proc.kill() - self.proc.wait() - if self.master is not None: - os.close(self.master) - self.proc = self.master = None - - def poll(self, timeout): - if self.proc is None: - if time.monotonic() < self.retry_at: - time.sleep(timeout) - return [] - try: - self.start() - except OSError as e: - log("cannot start monitor-sensor:", e) - self.retry_at = time.monotonic() + 5 - return [] - ready, _, _ = select.select([self.master], [], [], timeout) - if not ready: - if self.proc.poll() is not None: - self.exited() - return [] - try: - data = os.read(self.master, 4096) - except OSError: # EIO: the child closed the pty - data = b"" - if not data: - self.exited() - return [] - self.buf += data - *lines, self.buf = self.buf.split(b"\n") - out = [] - for raw in lines: - text = raw.decode(errors="replace").strip() - m = self.CHANGED.search(text) or self.HAS.search(text) - if m: - if m.group(2).lower() != "lux": - log(f"iio-sensor-proxy reports {m.group(2)}, not lux: ignoring") - continue - out.append(float(m.group(1))) - elif text: - log("monitor-sensor:", text) - return out - - def exited(self): - log("monitor-sensor exited; retrying in 3 s") - self.stop() - self.retry_at = time.monotonic() + 3 - - def close(self): - self.stop() - - def proxy_has_light(): try: out = subprocess.run( @@ -528,41 +165,12 @@ def have_monitor_sensor(): return bool(os.environ.get("IPAD_ALS_MONITOR_CMD")) or shutil.which("monitor-sensor") is not None -def make_source(args, conf): - if args.mock: - return LineSource(args.mock) - root = args.mock_iio or IIO_ROOT - if args.mock_iio: - return IioSource(root, conf["poll_hz"]) - if args.source == "proxy": - return ProxySource() - if args.source == "iio": - return IioSource(root, conf["poll_hz"]) - announced = False - deadline = time.monotonic() + float(os.environ.get("IPAD_ALS_DISCOVERY_SECS", "15")) - while True: - if have_monitor_sensor() and proxy_has_light(): - return ProxySource() - if find_iio_light(root): - return IioSource(root, conf["poll_hz"]) - if args.probe is not None: - log("no ambient light sensor: iio-sensor-proxy has none and there is no IIO device") - sys.exit(1) - if time.monotonic() >= deadline: - log("no ambient light sensor after discovery window; exiting") - sys.exit(0) - if not announced: - log("no ambient light sensor yet (iio-sensor-proxy has none, no IIO device); waiting") - announced = True - time.sleep(3) - - def list_sensors(args, conf): print("iio-sensor-proxy HasAmbientLight:", proxy_has_light() if shutil.which("busctl") else "no busctl") print("monitor-sensor:", "found" if have_monitor_sensor() else "missing") dev = find_iio_light(args.mock_iio or IIO_ROOT) print("IIO light sensor:", dev or "none") - if dev: + if dev and power_request("als-state") == "lit": print(" lux:", read_iio_lux(dev)) name = find_backlight(conf["backlight"]) print("backlight:", name or "none") @@ -587,208 +195,6 @@ def power_request(request): return "" -def holds(): - # No answer is a hold too: never infer that an unavailable power daemon - # permits the automatic controller to light the panel. - return [] if power_request("als-state") == "lit" else ["powerd"] - - -# --- the daemon ------------------------------------------------------------------------- -class Daemon: - def __init__(self, conf, source, backlight, dry, debug): - self.conf, self.source, self.backlight, self.dry, self.debug = conf, source, backlight, dry, debug - self.smoother = Smoother(conf["smooth_secs"], tau_up=conf["smooth_up_secs"]) - self.policy = Policy(conf) - self.latest = None # the last lux reading - self.next_sample = 0.0 - self.last_written = None # raw value we last set; a different reading is someone else's - self.goal_raw = None - self.next_step = 0.0 - self.override_until = 0.0 - self.hold = [] - self.settle_until = 0.0 - self.active = False - self.moves = 0 - self.stop = False - self.shown = None - self.last_status = None - - # -- helpers - def tolerance(self): - return max(2, int(round(self.backlight.max * 0.01))) - - def pause(self, why): - """Forget what we were doing, so that what comes next starts from the - backlight as it is.""" - self.last_written = None - self.goal_raw = None - self.policy.reset() - if self.active: - log("paused:", why) - self.active = False - - def tick(self, now): - conf = self.conf - if not is_enabled(conf): - self.pause("off") - self.write_status(now, enabled=False) - return False - raw = self.backlight.read() - hold = [] if self.dry else holds() - if raw is None or raw <= 0: - hold = hold or ["backlight"] - if hold != self.hold: - if hold: - log("holding for", ", ".join(hold)) - elif self.hold: - self.settle_until = now + HOLD_SETTLE - self.hold = hold - if hold or now < self.settle_until: - self.pause("hold") - self.write_status(now, enabled=True) - return False - # A change we didn't make: a brightness key, the menu. - if self.last_written is not None and abs(raw - self.last_written) > self.tolerance(): - self.override_until = now + conf["override_secs"] - log(f"brightness changed by hand ({self.backlight.pct(self.last_written):.0f} -> " - f"{self.backlight.pct(raw):.0f} %): paused for {conf['override_secs']:.0f} s") - self.pause("manual change") - if now < self.override_until: - self.write_status(now, enabled=True, override=self.override_until - now) - return True - if not self.active: - self.active = True - log("auto-brightness on") - # sample - if self.latest is not None and now >= self.next_sample: - self.next_sample = now + 1.0 / max(conf["poll_hz"], 0.5) - self.smoother.feed(self.latest * conf["lux_scale"], now) - goal = self.policy.decide(self.smoother, now, self.backlight.pct(raw)) - if self.debug: - log("lux %.1f smoothed %.1f -> %s" % - (self.latest * conf["lux_scale"], self.smoother.lux, - "%.0f %%" % goal if goal is not None else "stay")) - if goal is not None: - self.goal_raw = self.backlight.raw_for(goal) - self.start_ramp(raw, now) - log("lux %.0f: brightness %.0f %% -> %.0f %% over %.2f s" % - (self.smoother.lux, self.backlight.pct(raw), goal, self.ramp_secs)) - # ramp - if self.goal_raw is not None: - self.step(raw, now) - self.write_status(now, enabled=True) - return True - - # Perceived brightness in [0, 1]: equal steps here look equal on the panel. - def perceived(self, raw): - return (max(raw, 0) / self.backlight.max) ** (1.0 / RAMP_GAMMA) if self.backlight.max else 0.0 - - def raw_from_perceived(self, p): - return max(1, min(self.backlight.max, int(round(self.backlight.max * max(p, 0.0) ** RAMP_GAMMA)))) - - def start_ramp(self, raw, now): - """Fade from the current level to goal_raw: the duration follows the perceived - change (ramp_pct_per_s in perceived percent), eased in and out.""" - self.ramp_from, self.ramp_start = raw, now - delta = abs(self.perceived(self.goal_raw) - self.perceived(raw)) * 100.0 - speed = max(self.conf["ramp_pct_per_s"], 1.0) - self.ramp_secs = max(RAMP_MIN_SECS, min(delta / speed, RAMP_MAX_SECS)) - - def step(self, raw, now): - t = min(1.0, (now - self.ramp_start) / self.ramp_secs) if self.ramp_secs > 0 else 1.0 - if t >= 1.0: - new = self.goal_raw - else: - eased = t * t * (3.0 - 2.0 * t) # smoothstep: no jolt at the start or the end - p0, p1 = self.perceived(self.ramp_from), self.perceived(self.goal_raw) - new = self.raw_from_perceived(p0 + (p1 - p0) * eased) - if new == raw: - if t >= 1.0: - self.goal_raw = None - self.last_written = raw - return - if self.dry: - log(f"would set brightness {new} of {self.backlight.max} (dry run)") - self.goal_raw = None - return - if self.backlight.write(new, expected=raw): - self.last_written = new - self.moves += 1 - if new == self.goal_raw: - self.goal_raw = None - else: - self.goal_raw = None # a manual change or a dark transition: decide again later - - def ramping(self): - return self.goal_raw is not None - - def write_status(self, now, enabled, override=0.0): - if self.shown is not None and now - self.shown < 1.0: - return - self.shown = now - raw = self.backlight.read() - data = { - "pid": os.getpid(), - "source": self.source.kind, - "enabled": enabled, - "backlight": self.backlight.name, - "brightness_pct": None if raw is None else round(self.backlight.pct(raw), 1), - "lux": self.latest, - "smoothed_lux": None if self.smoother.lux is None else round(self.smoother.lux, 1), - "hold": self.hold, - "override_secs_left": round(override, 1), - "moves": self.moves, - } - if data == self.last_status: - return - tmp = status_path() + ".tmp" - try: - with open(tmp, "w") as f: - json.dump(dict(data, time=time.time()), f) - os.replace(tmp, status_path()) - self.last_status = data - except OSError: - pass - - def run(self, seconds=None): - end = time.monotonic() + seconds if seconds else None - log(f"source {self.source.kind}, backlight {self.backlight.name} (max {self.backlight.max})" - + (", dry run" if self.dry else "") + ("" if is_enabled(self.conf) else "; off until switched on")) - compositor = os.environ.get("LABWC_PID") - while not self.stop and (end is None or time.monotonic() < end): - if compositor: - try: - os.kill(int(compositor), 0) - except (OSError, ValueError): - break - now = time.monotonic() - wait = STATE_INTERVAL if end is None else min(STATE_INTERVAL, max(0, end - now)) - if not self.tick(now): - if isinstance(self.source, ProxySource): - self.source.stop() # dropping monitor-sensor releases its ClaimLight - self.latest = None - if now < self.settle_until: - wait = min(wait, self.settle_until - now) - time.sleep(wait) - continue - # Reuse the last signalled lux while the median and low-pass filter - # settle. Stable light needs no intermediate policy ticks. - if self.latest is not None and now >= self.override_until: - target = max(0.0, self.latest * self.conf["lux_scale"]) - if (self.smoother.level is None or self.smoother.readings != [target] * self.smoother.window - or abs(math.log1p(target) - self.smoother.level) > 0.001): - wait = min(wait, max(0.0, self.next_sample - now)) - if self.ramping(): - wait = min(wait, RAMP_TICK) - for lux in self.source.poll(wait): - self.latest = lux - self.source.close() - try: - os.unlink(status_path()) - except OSError: - pass - - # --- commands ------------------------------------------------------------------------------- def running_pid(): try: @@ -853,39 +259,15 @@ def main(): if args.command == "available": return 0 if find_iio_light(args.mock_iio or IIO_ROOT) and find_backlight(conf["backlight"]) else 1 - if args.probe is not None: - global FORCE_ENABLED - args.dry_run = args.debug = True - FORCE_ENABLED = True - name = find_backlight(conf["backlight"]) - if not name: - log("no backlight under", backlight_root()) - if args.probe is not None: - return 1 - while not name: # the panel may appear after the compositor starts - compositor = os.environ.get("LABWC_PID") - if compositor: - try: - os.kill(int(compositor), 0) - except (OSError, ValueError): - return 0 - time.sleep(STATE_INTERVAL) - name = find_backlight(conf["backlight"]) - source = make_source(args, conf) - daemon = Daemon(conf, source, Backlight(name), args.dry_run, args.debug) - def stop(*_): - daemon.stop = True - - def reload(*_): - daemon.conf.update(load_conf()) - daemon.smoother.tau = daemon.conf["smooth_secs"] - daemon.smoother.tau_up = daemon.conf["smooth_up_secs"] - - signal.signal(signal.SIGTERM, stop) - signal.signal(signal.SIGINT, stop) - signal.signal(signal.SIGHUP, reload) - daemon.run(args.probe) - return 0 + helper = "/usr/libexec/omarchy-session-helper" + options = ["daemon"] + if args.source: options += ["--source", args.source] + if args.mock: options += ["--mock", args.mock] + if args.mock_iio: options += ["--mock-iio", args.mock_iio] + if args.dry_run: options.append("--dry-run") + if args.probe is not None: options += ["--probe", str(args.probe)] + if args.debug: options.append("--debug") + os.execv(helper, [helper, *options]) if __name__ == "__main__": diff --git a/desktop/configuration/rotate-output b/desktop/configuration/rotate-output index 747bf370..de5327a6 100644 --- a/desktop/configuration/rotate-output +++ b/desktop/configuration/rotate-output @@ -1,386 +1,2 @@ -#!/usr/bin/python3 -"""Debounced iio-sensor-proxy rotation with a persistent user lock. - -Only a sustained orientation is applied. Repeated identical sensor messages do -not reset the deadline; undefined/flat readings cancel a pending transition. -A cooldown prevents rapid flips back. Unlock applies the latest stable reading. -A quick half turn becomes one 180 degree change instead of two of 90: a settled -reading waits a little longer while the tablet is still being turned, or while -gravity already points at another orientation than the one reported (the -sensor proxy reports the final orientation up to a second late). -""" -import collections -import glob -import json -import math -import os -from pathlib import Path -import selectors -import signal -import re -import subprocess -import time - -TRANSFORMS = {'normal': 'normal', 'bottom-up': '180', 'left-up': '90', 'right-up': '270'} -J120_SPEAKERS = Path('/sys/firmware/devicetree/base/sound-speaker-transport') - - -class Orientation: - def __init__(self, settle=0.4, cooldown=0.75, hold=0.6, lag=1.2): - self.settle = settle - self.cooldown = cooldown - self.hold = hold # longest extra wait while the tablet is still turning - self.lag = lag # longest extra wait for the report to catch up with gravity - self.pending = None - self.since = 0.0 - self.applied = None - self.last_apply = float('-inf') - - def observe(self, value, now): - value = value if value in TRANSFORMS else None - if value != self.pending: - self.pending, self.since = value, now - - def waiting(self): - return self.pending is not None and self.pending != self.applied - - def ready(self, now, locked=False, turning=False, facing=None): - if (locked or self.pending is None or self.pending == self.applied - or now - self.since < self.settle or now - self.last_apply < self.cooldown): - return None - if turning and now - self.since < self.settle + self.hold: - return None - if facing not in (None, self.pending) and now - self.since < self.settle + self.lag: - return None - return self.pending - - def committed(self, value, now): - self.applied, self.last_apply = value, now - - -class Turning: - """Whether the tablet is still being turned in the plane of its screen. - - From the accelerometer's raw gravity vector, read only while a change is - pending. Lying flat gives no usable angle and never delays a rotation. - """ - def __init__(self, directory, speed=40.0, window=0.25): - self.directory = directory - self.speed = speed # degrees per second - self.window = window - self.samples = collections.deque() - self.facing = None - self.disagreed = 0 - self.matrix = self.read_mount_matrix(directory) - - @staticmethod - def read_mount_matrix(directory): - candidates = [] - # Match iio-sensor-proxy's udev override before using kernel metadata. - try: - result = subprocess.run( - ['udevadm', 'info', '--query=property', '--path', str(Path(directory).resolve())], - stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True, - timeout=1, check=True) - candidates.extend(line.split('=', 1)[1] for line in result.stdout.splitlines() - if line.startswith('ACCEL_MOUNT_MATRIX=')) - except (OSError, subprocess.SubprocessError): - pass - for name in ('mount_matrix', 'in_accel_mount_matrix', 'in_mount_matrix'): - try: - candidates.append(Path(directory, name).read_text()) - except OSError: - pass - for text in candidates: - try: - rows = [[float(cell) for cell in row.split(',')] for row in text.split(';')] - if len(rows) == 3 and all(len(row) == 3 and any(row) - and all(map(math.isfinite, row)) for row in rows): - return rows[:2] - except ValueError: - pass - return [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0]] - - def read(self): - return [int(Path(self.directory, f'in_accel_{axis}_raw').read_text()) for axis in 'xyz'] - - def sample(self, now): - try: - x, y, z = self.read() - except (OSError, ValueError): - self.samples.clear() - return - length = math.sqrt(x * x + y * y + z * z) - if not length or math.hypot(x, y) < 0.25 * length: - self.forget() - return - # The orientation gravity points at now, as iio-sensor-proxy names it - # after the mount matrix, with no hysteresis and no delay. - across, along = (row[0] * x + row[1] * y + row[2] * z for row in self.matrix) - if abs(along) >= abs(across): - self.facing = 'normal' if along < 0 else 'bottom-up' - else: - self.facing = 'right-up' if across < 0 else 'left-up' - self.samples.append((now, math.degrees(math.atan2(y, x)))) - while now - self.samples[0][0] > self.window: - self.samples.popleft() - - def forget(self): - self.samples.clear() - self.facing = None - - def judged(self, applied): - """Stop comparing on a board where gravity and the reports never agree.""" - if self.facing is not None: - self.disagreed = 0 if self.facing == applied else self.disagreed + 1 - - def trusted_facing(self): - return self.facing if self.disagreed < 3 else None - - def turning(self): - if len(self.samples) < 2: - return False - (start, first), (end, last) = self.samples[0], self.samples[-1] - if end - start < 0.1: - return False - change = abs((last - first + 180) % 360 - 180) - return change / (end - start) > self.speed - - -def orientation(line): - # New monitor-sensor versions append a separate ', tilt: face-up' field. - # Only the orientation token belongs to the rotation state machine. - match = re.search(r'orientation(?: changed)?:\s*([a-z-]+)(?=[,\s)]|$)', line) - return match.group(1) if match else None - - -def trace(message): - if os.environ.get('ORCHARD_ROTATION_TRACE') == '1': - print(f'rotation trace t={time.monotonic():.3f} {message}', flush=True) - - -def internal_output(outputs): - return next((name for name in outputs if name.startswith(('eDP-', 'DSI-', 'LVDS-'))), - outputs[0] if len(outputs) == 1 else None) - - -def publish_speaker_transform(path, transform): - try: - staging = path.with_suffix('.new') - staging.write_text(transform + '\n') - staging.replace(path) - except OSError as error: - print(f'speaker transform update failed: {error}', flush=True) - - -def seed_speaker_transform(path): - # A locked rotation may never make a new request during this session. - try: - result = subprocess.check_output(['wlr-randr', '--json'], text=True, timeout=3) - transforms = {output['name']: output['transform'] for output in json.loads(result) - if output.get('enabled')} - transform = transforms.get(internal_output(list(transforms))) - if transform in TRANSFORMS.values(): - publish_speaker_transform(path, transform) - except (OSError, ValueError, subprocess.SubprocessError) as error: - print(f'speaker transform query failed: {error}', flush=True) - - -def apply(value, speaker_transform=None): - started = time.monotonic() - trace(f'output query start orientation={value}') - result = subprocess.run(['wlr-randr'], capture_output=True, text=True, timeout=3, check=True) - # Prefer the internal panel, never arbitrarily rotate an external monitor. - outputs = [line.split()[0] for line in result.stdout.splitlines() if line and not line[0].isspace()] - output = internal_output(outputs) - if output is None: - return False - queried = time.monotonic() - trace(f'output query done ms={(queried - started) * 1000:.0f}; request {TRANSFORMS[value]}') - subprocess.run(['wlr-randr', '--output', output, '--transform', TRANSFORMS[value]], - check=True, timeout=4) - trace(f'output request done ms={(time.monotonic() - queried) * 1000:.0f}') - if speaker_transform is not None: - publish_speaker_transform(speaker_transform, TRANSFORMS[value]) - print(f'rotation applied: {output} {value} -> {TRANSFORMS[value]}', flush=True) - return True - - -def watch_unlock(lock): - # Watch the existing inode, so removing the lock wakes a settled pose - # even when monitor-sensor has nothing more to say. - import ctypes - libc = ctypes.CDLL(None) - if not hasattr(libc, 'inotify_init1'): - return None - fd = libc.inotify_init1(os.O_CLOEXEC | os.O_NONBLOCK) - if fd < 0: - return None - if libc.inotify_add_watch(fd, os.fsencode(lock), 0x400 | 0x800) < 0: # DELETE_SELF | MOVE_SELF - os.close(fd) - return None - return fd - - -def main(): - lock = Path(os.environ.get('XDG_CONFIG_HOME', str(Path.home() / '.config'))) / 'omarchy/rotation-lock' - state = Orientation(float(os.environ.get('ROTATE_SETTLE', '.4')), - float(os.environ.get('ROTATE_COOLDOWN', '.75'))) - parent = int(os.environ.get('LABWC_PID', '0')) - runtime = os.environ.get('XDG_RUNTIME_DIR') - speaker_transform = None - if runtime and J120_SPEAKERS.is_dir(): - speaker_transform = Path(runtime) / 'omarchy-j120-speaker-transform' - seed_speaker_transform(speaker_transform) - sensors = glob.glob(os.environ.get('ROTATE_ACCEL', '/sys/bus/iio/devices/iio:device*') + '/in_accel_x_raw') - motion = Turning(os.path.dirname(sensors[0])) if sensors else None - discovery_timeout = float(os.environ.get('ROTATE_DISCOVERY_TIMEOUT', '15')) - started = time.monotonic() - saw_proxy = False - selector = selectors.DefaultSelector() - def start_monitor(): - process = subprocess.Popen(['monitor-sensor', '--accel'], stdout=subprocess.PIPE) - os.set_blocking(process.stdout.fileno(), False) - selector.register(process.stdout, selectors.EVENT_READ) - return process - def stop_monitor(process): - process.terminate() - try: - process.wait(timeout=2) - except subprocess.TimeoutExpired: - process.kill() - process.wait() - process.stdout.close() - monitor = start_monitor() - restart_at = None - retry_apply_at = 0.0 - lock_fd = parent_fd = None - running = True - def stop(*_): - raise SystemExit(0) # interrupt even an indefinite selector wait - signal.signal(signal.SIGTERM, stop) - signal.signal(signal.SIGINT, stop) - buffered = b'' - eof = False - try: - if parent and hasattr(os, 'pidfd_open'): - try: - parent_fd = os.pidfd_open(parent) - except ProcessLookupError: - return - except OSError: - pass # older kernels: fall back to the liveness check - else: - selector.register(parent_fd, selectors.EVENT_READ, 'parent') - while running: - now = time.monotonic() - deadlines = [] - if parent and parent_fd is None: - try: - os.kill(parent, 0) - except ProcessLookupError: - break - deadlines.append(now + 2) - if not sensors and not saw_proxy and discovery_timeout > 0: - deadlines.append(started + discovery_timeout) - if restart_at is not None: - deadlines.append(restart_at) - if eof and not parent: - deadlines.append(state.since + state.settle + state.cooldown + 5) - if state.waiting(): - if lock.exists(): - if lock_fd is None: - lock_fd = watch_unlock(lock) - if lock_fd is not None: - selector.register(lock_fd, selectors.EVENT_READ, 'unlock') - if lock_fd is None: - deadlines.append(now + 2 if lock.exists() else now) - elif now < retry_apply_at: - deadlines.append(retry_apply_at) - elif motion: - deadlines.append(now + 0.1) # gravity only while a turn is settling - else: - deadlines.append(max(state.since + state.settle, state.last_apply + state.cooldown)) - wait = max(0.0, min(deadlines) - now) if deadlines else None - for key, _ in selector.select(wait): - if key.data == 'parent': - return - if key.data == 'unlock': - selector.unregister(lock_fd) - os.close(lock_fd) - lock_fd = None - continue - data = os.read(key.fd, 8192) - if not data: - eof = True - selector.unregister(key.fd) - continue - buffered += data - while b'\n' in buffered: - line, buffered = buffered.split(b'\n', 1) - decoded = line.decode(errors='replace') - if '=== No accelerometer' in decoded and not sensors: - print('rotation: no accelerometer; exiting', flush=True) - running = False - break - if '=== Has accelerometer' in decoded or 'iio-sensor-proxy appeared' in decoded: - saw_proxy = True - value = orientation(decoded) - if value is not None: - saw_proxy = True - trace(f'sensor orientation={value}') - if value != state.pending: - retry_apply_at = 0.0 - state.observe(value, time.monotonic()) - now = time.monotonic() - if not running: - break - if not sensors and not saw_proxy and discovery_timeout > 0 and now - started >= discovery_timeout: - print('rotation: no accelerometer or iio-sensor-proxy after discovery window; exiting', flush=True) - break - locked = lock.exists() - if motion: - if state.waiting() and not locked and now >= retry_apply_at: - motion.sample(now) - else: - motion.forget() - value = state.ready(now, locked, bool(motion and motion.turning()), - motion.trusted_facing() if motion else None) - if value is not None and now >= retry_apply_at: - trace(f'stable orientation={value} waited_ms={(now - state.since) * 1000:.0f}') - try: - if apply(value, speaker_transform): - state.committed(value, now) - if motion: - motion.judged(value) - else: - retry_apply_at = now + 60 # no eligible output - except (OSError, subprocess.SubprocessError) as error: - print(f'rotation failed: {error}', flush=True) - retry_apply_at = now + 2 - if eof: - # No accelerated apply on EOF: wait out any pending stability window. - if not parent: - if locked or not state.waiting() or now >= state.since + state.settle + state.cooldown + 5: - break - continue - # Inside a session the sensor reader may end (iio-sensor-proxy - # not up yet at login, or restarted). Rotation must not stay - # dead until the next login: start it again, at most every 2 s. - if restart_at is None: - print('rotation: monitor-sensor ended; restarting', flush=True) - restart_at = now + 2 - elif now >= restart_at: - stop_monitor(monitor) - monitor = start_monitor() - buffered, eof, restart_at = b'', False, None - finally: - selector.close() - for fd in (lock_fd, parent_fd): - if fd is not None: - os.close(fd) - stop_monitor(monitor) - - -if __name__ == '__main__': - main() +#!/bin/sh +exec /usr/libexec/omarchy-session-helper "$@" diff --git a/desktop/install-tree b/desktop/install-tree index ed917a7f..9977ce4d 100755 --- a/desktop/install-tree +++ b/desktop/install-tree @@ -19,7 +19,7 @@ here=$(cd "$(dirname "$0")" && pwd) project=$(dirname "$here") shell=$here/shell config=$here/configuration omarchy=$root/usr/share/omarchy -for input in "$build/wvkbd-mobintl" "$build/wtype" "$build/wtype.LICENSE" "$upstream/themes" "$upstream/bin" \ +for input in "$build/omarchy-session-helper" "$build/wvkbd-mobintl" "$build/wtype" "$build/wtype.LICENSE" "$upstream/themes" "$upstream/bin" \ "$upstream/themes/jade-horse/colors.toml" "$upstream/icons/papercraft" "$upstream/applications/foot.desktop" "$upstream/default/hypr/toggles/bar-glassy.lua" "$dbus_next/dbus_next/__init__.py"; do [[ -e $input ]] || { echo "Missing input: $input" >&2; exit 1; } done @@ -78,6 +78,7 @@ done # The keyboard and the startup cursor helper. put "$build/wvkbd-mobintl" "$omarchy/trials/wvkbd-mobintl-v0.20-font18-special15-state" 755 +put "$build/omarchy-session-helper" "$root/usr/libexec/omarchy-session-helper" 755 put "$build/wtype" "$root/usr/libexec/omarchy-wtype" 755 put "$build/wtype.LICENSE" "$root/usr/share/licenses/omarchy-wtype/LICENSE" diff --git a/desktop/session/keyboard.c b/desktop/session/keyboard.c new file mode 100644 index 00000000..df99d359 --- /dev/null +++ b/desktop/session/keyboard.c @@ -0,0 +1,243 @@ +#include "session.h" +#include +#include +#include +#include + +static struct { + unsigned field, keyboards; + double touched, tapped, hide_at; + bool pressing, opened, hardware, held, hide_asked; +} policy; +static sd_event_source *pipe_source, *hide_timer; +static char partial[256]; +static size_t used; +static bool overflow, replay, shown; +static const char *action; +static sd_event_source *startup; + +static int started(sd_event_source *s, const siginfo_t *info, void *data) +{ + startup = sd_event_source_unref(startup); + return 0; +} + +static bool visible(void) { return replay ? shown : number(runtime, "omarchy-keyboard-visible", 0) == 1; } + +static void display(bool show) +{ + if (replay) { + shown = show; + action = show ? "show" : "hide"; + return; + } + pid_t pid = number(runtime, "omarchy-keyboard.pid", 0); + char exe[64], binary[PATH_MAX]; + struct stat expected, actual; + snprintf(exe, sizeof exe, "/proc/%d/exe", pid); + join(binary, sizeof binary, env_or("OMARCHY_PATH", "/usr/share/omarchy"), + "trials/wvkbd-mobintl-v0.20-font18-special15-state"); + if (pid > 0 && !stat(binary, &expected) && !stat(exe, &actual) && expected.st_dev == actual.st_dev && + expected.st_ino == actual.st_ino) { + if (kill(pid, show ? SIGUSR2 : SIGUSR1) == 0) + return; + } + // Only the cold path needs theme loading and wvkbd's startup handshake. + if (!show || startup) + return; + pid = fork(); + if (pid == 0) { + sigset_t empty; + sigemptyset(&empty); + sigprocmask(SIG_SETMASK, &empty, NULL); + execlp("omarchy-keyboard", "omarchy-keyboard", "policy-show", NULL); + _exit(127); + } else if (pid > 0) + sd_event_add_child(loop, &startup, pid, WEXITED, started, NULL); +} + +static void open_keyboard(void) +{ + policy.touched = policy.tapped = policy.hide_at = 0; + policy.hide_asked = false; + if (policy.hardware) + return; + policy.opened = true; + if (!visible()) + display(true); +} + +static bool digits(const char *s) +{ + if (!s || !*s) + return false; + for (; *s; s++) + if (!isdigit((unsigned char)*s)) + return false; + return true; +} + +static void fact(char *line, double t) +{ + char *save = NULL, *word[4] = {0}; + unsigned n = 0; + for (char *s = strtok_r(line, " \t\r\n", &save); s && n < 4; s = strtok_r(NULL, " \t\r\n", &save)) + word[n++] = s; + if (!n) + return; + if (!strcmp(word[0], "field")) { + if (n == 3 && !strcmp(word[1], "on") && digits(word[2])) { + policy.field = strtoul(word[2], NULL, 10); + policy.hide_at = 0; + if ((policy.pressing && t < policy.touched) || (policy.field < 2 && t < policy.tapped)) + open_keyboard(); + } else if (n == 2 && !strcmp(word[1], "off")) { + policy.field = 0; + if (policy.opened && !policy.held) + policy.hide_at = t + .25; + } + } else if (n == 1 && !strcmp(word[0], "show")) { + if (t < policy.touched) + open_keyboard(); + } else if (n == 1 && !strcmp(word[0], "hide")) { + if (policy.opened) { + policy.hide_at = t + .25; + policy.hide_asked = true; + } + } else if (n == 1 && !strcmp(word[0], "press")) { + policy.touched = t + .6; + policy.pressing = true; + } else if (n == 3 && !strcmp(word[0], "release") && digits(word[1]) && digits(word[2])) { + policy.pressing = false; + if (strtoul(word[1], NULL, 10) <= 350 && strtoul(word[2], NULL, 10) <= 12) { + policy.touched = policy.tapped = t + .6; + if (policy.field == 1) + open_keyboard(); + } else + policy.touched = policy.tapped = 0; + } else if (n == 1 && !strcmp(word[0], "key") && policy.keyboards) { + policy.hardware = true; + policy.touched = policy.tapped = 0; + policy.opened = false; + if (visible()) + display(false); + } else if (n == 2 && !strcmp(word[0], "keyboards") && digits(word[1])) { + policy.keyboards = strtoul(word[1], NULL, 10); + if (!policy.keyboards) + policy.hardware = false; + } +} + +static void person(const char *s, double t) +{ + if (!strcmp(s, "hold")) { + policy.held = true; + policy.hide_asked = false; + policy.hide_at = 0; + } else if (!strcmp(s, "release")) { + policy.held = false; + if (policy.opened && !policy.field) + policy.hide_at = t + .25; + } else if (!strcmp(s, "quiet")) { + policy.touched = policy.tapped = 0; + } else if (!strcmp(s, "show") || !strcmp(s, "hide")) { + policy.opened = false; + policy.hide_at = 0; + if (!strcmp(s, "show")) + policy.hardware = false; + } +} + +static void tick(double t) +{ + if (!policy.hide_at || t < policy.hide_at) + return; + if (policy.opened && (policy.hide_asked || !policy.field)) { + policy.opened = false; + display(false); + } + policy.hide_at = 0; + policy.hide_asked = false; +} + +static int expire(sd_event_source *s, uint64_t usec, void *data) +{ + tick(now()); + return 0; +} + +void keyboard_person(const char *line) +{ + if (!pipe_source) + return; + person(line, now()); + timer(&hide_timer, policy.hide_at, expire); +} + +void keyboard_detach(void) +{ + pipe_source = sd_event_source_unref(pipe_source); + hide_timer = sd_event_source_unref(hide_timer); + memset(&policy, 0, sizeof policy); + overflow = false; + used = 0; +} + +static int input(sd_event_source *s, int fd, uint32_t events, void *data) +{ + char buffer[4096]; + ssize_t n = read(fd, buffer, sizeof buffer); + if (n <= 0) { + keyboard_detach(); + return 0; + } + for (ssize_t i = 0; i < n; i++) { + if (buffer[i] == '\n') { + partial[used] = 0; + if (!overflow) + fact(partial, now()); + used = 0; + overflow = false; + } else if (used < sizeof partial - 1) + partial[used++] = buffer[i]; + else + overflow = true; + } + timer(&hide_timer, policy.hide_at, expire); + return 0; +} + +void keyboard_attach(int fd) +{ + keyboard_detach(); + if (sd_event_add_io(loop, &pipe_source, fd, EPOLLIN, input, NULL) < 0) { + close(fd); + return; + } + sd_event_source_set_io_fd_own(pipe_source, 1); +} + +int replay_keyboard(void) +{ + char line[512]; + replay = true; + while (fgets(line, sizeof line, stdin)) { + double t; + int offset, vis; + if (sscanf(line, "%lf %d %n", &t, &vis, &offset) != 2) + return 2; + shown = vis; + action = "-"; + char *cmd = line + offset; + cmd[strcspn(cmd, "\n")] = 0; + if (!strncmp(cmd, "person ", 7)) + person(cmd + 7, t); + else if (!strcmp(cmd, "tick")) + tick(t); + else + fact(cmd, t); + printf("%s %d\n", action, policy.hardware); + fflush(stdout); + } + return 0; +} diff --git a/desktop/session/light.c b/desktop/session/light.c new file mode 100644 index 00000000..57257c94 --- /dev/null +++ b/desktop/session/light.c @@ -0,0 +1,601 @@ +#include "session.h" +#include +#include +#include +#include +#include +#include +#include +#include + +struct point { + double lux, pct; +}; +static const struct point defaults[] = {{0, 15}, {5, 25}, {20, 38}, {80, 58}, + {250, 78}, {700, 94}, {1500, 100}}; +static struct point *curve; +static size_t points; +static struct settings { + double min_pct, max_pct, lux_scale, smooth_secs, smooth_up_secs, hysteresis, min_pct_step; + double min_interval, min_interval_up, ramp_pct_per_s, override_secs, poll_hz; + char backlight[256]; + bool enabled; +} cfg; +static char panel[256], panel_dir[PATH_MAX], sensor[PATH_MAX], status_file[PATH_MAX]; +static int maximum, goal, last_written, ramp_from, moves; +static double ramp_start, ramp_secs, override_until, settle_until, next_iio, next_sample; +static double policy_due = INFINITY; +static double readings[3], level = NAN, latest = NAN, ref = NAN, fed, moved = -INFINITY; +static unsigned count; +static bool has_light, claimed, need_level, was_held, enabled; +static const char *hold, *source; +static sd_event_source *deadline; +static char last_status[1024]; + +static char *trim(char *s) +{ + while (isspace((unsigned char)*s)) + s++; + size_t n = strlen(s); + while (n && isspace((unsigned char)s[n - 1])) + s[--n] = 0; + return s; +} + +static int compare_point(const void *a, const void *b) +{ + double x = ((const struct point *)a)->lux, y = ((const struct point *)b)->lux; + return (x > y) - (x < y); +} + +static void parse_curve(char *line) +{ + struct point *p = NULL; + size_t n = 0; + for (char *s; (s = strsep(&line, ",;"));) { + char extra; + double x, y; + if (!*trim(s)) + continue; + if (sscanf(s, " %lf : %lf %c", &x, &y, &extra) != 2 || !isfinite(x) || x < 0 || !isfinite(y)) + goto invalid; + void *larger = realloc(p, (n + 1) * sizeof *p); + if (!larger) + goto invalid; + p = larger; + p[n++] = (struct point){x, y}; + } + if (n < 2) + goto invalid; + qsort(p, n, sizeof *p, compare_point); + for (size_t i = 1; i < n; i++) + if (p[i].lux == p[i - 1].lux) + goto invalid; + free(curve); + curve = p; + points = n; + return; +invalid: + free(p); +} + +static void setting(char *key, char *value) +{ + if (!strcmp(key, "enabled")) { + cfg.enabled = !strcasecmp(value, "on") || !strcasecmp(value, "yes") || !strcasecmp(value, "true") || + !strcmp(value, "1"); + } else if (!strcmp(key, "backlight")) + snprintf(cfg.backlight, sizeof cfg.backlight, "%s", value); + else if (!strcmp(key, "curve")) + parse_curve(value); + else { + struct { + const char *name; + double *slot; + } keys[] = { +#define KEY(name) {#name, &cfg.name} + KEY(min_pct), + KEY(max_pct), + KEY(lux_scale), + KEY(smooth_secs), + KEY(smooth_up_secs), + KEY(hysteresis), + KEY(min_pct_step), + KEY(min_interval), + KEY(min_interval_up), + KEY(ramp_pct_per_s), + KEY(override_secs), + KEY(poll_hz) +#undef KEY + }; + char *end; + double x = strtod(value, &end); + if (*end || end == value || !isfinite(x)) + return; + for (size_t i = 0; i < sizeof keys / sizeof *keys; i++) + if (!strcmp(key, keys[i].name)) + *keys[i].slot = x; + } +} + +static void read_settings(const char *dir, const char *name, bool prefs) +{ + char path[PATH_MAX], *line = NULL; + size_t capacity = 0; + join(path, sizeof path, dir, name); + FILE *f = fopen(path, "re"); + if (!f) + return; + while (getline(&line, &capacity, f) >= 0) { + line[strcspn(line, "#")] = 0; + char *eq = strchr(line, '='); + if (!eq) + continue; + *eq++ = 0; + char *key = trim(line), *value = trim(eq); + if (!prefs) + setting(key, value); + else if (!strcmp(key, "auto_brightness")) { + if (!strcmp(value, "on")) + enabled = true; + if (!strcmp(value, "off")) + enabled = false; + } + } + free(line); + fclose(f); +} + +void light_config(void) +{ + cfg = (struct settings){.min_pct = 5, + .max_pct = 100, + .lux_scale = 1, + .smooth_secs = 3, + .smooth_up_secs = .4, + .hysteresis = .20, + .min_pct_step = 2, + .min_interval = 2, + .min_interval_up = .25, + .ramp_pct_per_s = 40, + .override_secs = 30, + .poll_hz = 4}; + free(curve); + curve = NULL; + points = 0; + read_settings(config, "als-brightness.conf", false); + cfg.min_pct = fmin(100, fmax(0, cfg.min_pct)); + cfg.max_pct = fmin(100, fmax(cfg.min_pct, cfg.max_pct)); + enabled = cfg.enabled; + read_settings(state, "display", true); + enabled |= probe_light; + ref = NAN; + next_sample = 0; +} + +static bool find_attr(char *out, size_t size, const char *dir, const char *pattern) +{ + char path[PATH_MAX]; + glob_t files = {0}; + join(path, sizeof path, dir, pattern); + bool found = glob(path, 0, NULL, &files) == 0; + if (found) { + snprintf(out, size, "%s", files.gl_pathv[0]); + *strrchr(out, '/') = 0; + } + globfree(&files); + return found; +} + +static void discover(void) +{ + const char *root = env_or("IPAD_ALS_BACKLIGHT_ROOT", "/sys/class/backlight"); + char dir[PATH_MAX] = ""; + if (cfg.backlight[0]) + join(dir, sizeof dir, root, cfg.backlight); + else + find_attr(dir, sizeof dir, root, "*/max_brightness"); + if (strcmp(dir, panel_dir)) { + snprintf(panel_dir, sizeof panel_dir, "%s", dir); + snprintf(panel, sizeof panel, "%s", *dir ? strrchr(dir, '/') + 1 : ""); + last_written = goal = 0; + ref = NAN; + } + maximum = *dir ? number(dir, "max_brightness", 0) : 0; + const char *iio = env_or("IPAD_ALS_IIO_ROOT", "/sys/bus/iio/devices"); + sensor[0] = 0; + if (!find_attr(sensor, sizeof sensor, iio, "iio:device*/in_illuminance_input")) + find_attr(sensor, sizeof sensor, iio, "iio:device*/in_illuminance_raw"); +} + +static double iio_lux(void) +{ + double x = number(sensor, "in_illuminance_input", NAN); + if (isfinite(x)) + return x; + return (number(sensor, "in_illuminance_raw", NAN) + number(sensor, "in_illuminance_offset", 0)) * + number(sensor, "in_illuminance_scale", 1); +} + +// Read only new bytes. Keep an incomplete FIFO line for the next arrival. +static double mock_lux(void) +{ + static int fd = -1; + static char line[128]; + static size_t n; + static bool overflow; + struct stat st; + if (fd < 0) { + if (stat(mock_file, &st) < 0 && mkfifo(mock_file, 0600) < 0) + return NAN; + if (stat(mock_file, &st) < 0) + return NAN; + fd = open(mock_file, (S_ISFIFO(st.st_mode) ? O_RDWR : O_RDONLY) | O_NONBLOCK | O_CLOEXEC); + } + if (fd < 0 || fstat(fd, &st) < 0) + return NAN; + if (S_ISREG(st.st_mode) && lseek(fd, 0, SEEK_CUR) > st.st_size) { + lseek(fd, 0, SEEK_SET); + n = 0; + } + double result = latest; + char data[4096]; + ssize_t got; + while ((got = read(fd, data, sizeof data)) > 0) { + for (ssize_t i = 0; i < got; i++) { + if (data[i] == '\n') { + line[n] = 0; + line[strcspn(line, "#")] = 0; + char *end; + double x = strtod(line, &end); + if (!overflow && end != line && !*trim(end) && isfinite(x)) + result = x; + n = 0; + overflow = false; + } else if (n < sizeof line - 1) + line[n++] = data[i]; + else + overflow = true; + } + } + return result; +} + +static bool power(const char *request, const char *want) +{ + struct sockaddr_un addr = {.sun_family = AF_UNIX}; + const char *path = env_or("IPAD_ALS_POWER_SOCKET", "/run/omarchy-powerd.sock"); + if (strlen(path) >= sizeof addr.sun_path) + return false; + strcpy(addr.sun_path, path); + int fd = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0); + if (fd < 0) + return false; + struct timeval limit = {.tv_usec = 500000}; + setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &limit, sizeof limit); + setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &limit, sizeof limit); + char reply[64] = {0}; + bool ok = connect(fd, (struct sockaddr *)&addr, sizeof addr) == 0 && + send(fd, request, strlen(request), MSG_NOSIGNAL) == (ssize_t)strlen(request); + if (ok) { + size_t used = 0; + while (used < sizeof reply - 1 && !strchr(reply, '\n')) { + ssize_t n = recv(fd, reply + used, sizeof reply - used - 1, 0); + if (n <= 0) + break; + used += n; + } + ok = !strcmp(trim(reply), want); + } + close(fd); + return ok; +} + +static double target_pct(double lux) +{ + const struct point *p = curve ? curve : defaults; + size_t n = curve ? points : sizeof defaults / sizeof *defaults; + double pct = p[n - 1].pct; + if (lux <= p[0].lux) + pct = p[0].pct; + else + for (size_t i = 1; i < n; i++) + if (lux <= p[i].lux) { + double a = log1p(p[i - 1].lux), b = log1p(p[i].lux); + pct = p[i - 1].pct + (p[i].pct - p[i - 1].pct) * (log1p(lux) - a) / (b - a); + break; + } + return fmax(cfg.min_pct, fmin(cfg.max_pct, pct)); +} + +static void feed(double lux, double t) +{ + if (count == 3) { + memmove(readings, readings + 1, 2 * sizeof *readings); + count--; + } + readings[count++] = fmax(0, lux); + double a = readings[0], b = readings[1], c = readings[2]; + double med = count == 1 ? a : count == 2 ? (a + b) / 2 : fmax(fmin(a, b), fmin(fmax(a, b), c)); + double target = log1p(med), tau = target > level ? cfg.smooth_up_secs : cfg.smooth_secs; + if (!isfinite(level) || tau <= 0) + level = target; + else + level += (-expm1(-fmax(0, t - fed) / tau)) * (target - level); + fed = t; +} + +static double decide(double pct, double t, double *next) +{ + double goal_pct = target_pct(expm1(level)); + if (isnan(ref)) { + if (fabs(goal_pct - pct) < 1) { + ref = level; + return NAN; + } + } else { + if (fabs(level - ref) < log1p(cfg.hysteresis) || fabs(goal_pct - pct) < cfg.min_pct_step) + return NAN; + double due = moved + (goal_pct > pct ? cfg.min_interval_up : cfg.min_interval); + if (t < due) { + *next = fmin(*next, due); + return NAN; + } + } + ref = level; + moved = t; + return goal_pct; +} + +static double perceived(int raw) { return pow((double)raw / maximum, 1. / 2.2); } + +static void start_ramp(int raw, int target, double t) +{ + goal = target; + ramp_from = raw; + ramp_start = t; + ramp_secs = fmin(3, fmax(.3, 100 * fabs(perceived(goal) - perceived(raw)) / fmax(1, cfg.ramp_pct_per_s))); +} + +static int ramp_value(double t) +{ + double f = fmax(0, (t - ramp_start) / ramp_secs); + if (f >= 1) + return goal; + double p = perceived(ramp_from) + (perceived(goal) - perceived(ramp_from)) * f * f * (3 - 2 * f); + return fmax(1, lrint(maximum * pow(p, 2.2))); +} + +static void release_light(void) +{ + if (claimed) + claim("ReleaseLight"); + claimed = false; + need_level = true; + latest = NAN; +} + +void light_proxy(bool available) +{ + if (!available) + release_light(); + has_light = available; +} + +void light_changed(void) +{ + if (claimed) + need_level = true; +} + +static const char *json_number(double x, char buf[64]) +{ + if (!isfinite(x)) + return "null"; + snprintf(buf, 64, "%.10g", x); + return buf; +} + +static void status(int raw, double t) +{ + char data[1024], text[1200], pct[64], lux[64], smoothed[64]; + // Kernel device names are used as one powerd protocol token and one JSON string. + if (strpbrk(panel, "\"\\\r\n\t ")) + return; + snprintf(data, sizeof data, + "\"pid\":%d,\"source\":\"%s\",\"enabled\":%s,\"backlight\":\"%s\"," + "\"brightness_pct\":%s,\"lux\":%s,\"smoothed_lux\":%s,\"hold\":[%s],\"override_secs_left\":%.1f," + "\"moves\":%d", + getpid(), source, enabled ? "true" : "false", panel, + json_number(raw >= 0 && maximum > 0 ? nearbyint(1000. * raw / maximum) / 10 : NAN, pct), + json_number(latest, lux), json_number(nearbyint(expm1(level) * 10) / 10, smoothed), + hold ? hold : "", fmax(0, override_until - t), moves); + if (strcmp(data, last_status)) { + snprintf(text, sizeof text, "{%s,\"time\":%lld}\n", data, (long long)time(NULL)); + atomic_text(status_file, text); + strcpy(last_status, data); + } +} + +static int expire(sd_event_source *s, uint64_t usec, void *data) +{ + light_update(); + return 0; +} + +void light_update(void) +{ + double t = now(), next = INFINITY; + // Discovery reads device metadata only. Every lux read below follows the live power check. + if (!maximum) + discover(); + int raw = maximum > 0 ? number(panel_dir, "brightness", -1) : -1; + source = has_light && strcmp(light_source, "iio") ? "proxy" : "iio"; + hold = NULL; + if (enabled && !(dry_light && (mock_file || getenv("IPAD_ALS_IIO_ROOT"))) && !power("als-state\n", "lit")) + hold = "\"powerd\""; + else if (enabled && raw <= 0) + hold = "\"backlight\""; + if (was_held && !hold && enabled) + settle_until = t + 1; + was_held = hold != NULL; + if (!enabled || hold || t < settle_until) { + release_light(); + ref = NAN; + goal = last_written = 0; + if (enabled && !hold && t < settle_until) + next = settle_until; + goto done; + } + if (last_written && abs(raw - last_written) > fmax(2, nearbyint(maximum * .01))) { + override_until = t + cfg.override_secs; + goal = 0; + ref = NAN; + } + last_written = raw; + if (!mock_file && !strcmp(source, "proxy")) { + if (!claimed) { + claimed = claim("ClaimLight"); + need_level = true; + if (!claimed) + next = t + 3; // A transient failure while the owner is present. + } + if (claimed && need_level) { + char *unit = get_string("LightLevelUnit"); + double x; + if (unit && !strcmp(unit, "lux") && + sd_bus_get_property_trivial(bus, PROXY, SENSOR_PATH, PROXY, "LightLevel", NULL, 'd', &x) >= 0) + latest = isfinite(x) ? x : NAN; + else + latest = NAN; + need_level = false; + free(unit); + } + } + if (mock_file) { + source = "mock"; + latest = mock_lux(); + next = fmin(next, t + .2); + } else if (!claimed && strcmp(light_source, "proxy") && sensor[0]) { + source = "iio"; + if (t >= next_iio) { + latest = iio_lux(); + next_iio = t + fmax(2, cfg.poll_hz > 0 ? 1 / cfg.poll_hz : 2); + } + next = fmin(next, next_iio); + } + if (t < override_until) { + next = fmin(next, fmin(t + 1, override_until)); + goto done; + } + if (isfinite(latest)) { + double target = fmax(0, latest * cfg.lux_scale); + if (t >= next_sample) { + next_sample = t + 1 / fmax(.5, cfg.poll_hz); + feed(target, t); + policy_due = INFINITY; + double pct = decide(100. * raw / maximum, t, &policy_due); + if (isfinite(pct)) + start_ramp(raw, fmax(1, fmin(maximum, lrint(pct * maximum / 100))), t); + if (debug_light) + fprintf(stderr, "lux %.1f smoothed %.1f target %.1f\n", latest, expm1(level), pct); + } + if (isfinite(policy_due)) + next = fmin(next, fmax(policy_due, next_sample)); + if (count < 3 || readings[0] != target || readings[1] != target || readings[2] != target || + fabs(log1p(target) - level) > .001) + next = fmin(next, next_sample); + } + if (goal) { + int value = ramp_value(t); + if (value != raw) { + char request[384]; + snprintf(request, sizeof request, "brightness %s %d %d\n", panel, value, raw); + if (dry_light) { + fprintf(stderr, "would set brightness %d of %d (dry run)\n", value, maximum); + goal = 0; + } else if (number(panel_dir, "brightness", -1) == raw && power(request, "ok")) { + raw = last_written = value; + moves++; + } else + goal = 0; + } + if (goal == raw) + goal = 0; + if (goal) + next = fmin(next, t + 1. / 30); + } +done: + if (!light_only) + status(raw, t); + timer(&deadline, isfinite(next) ? next : 0, expire); +} + +void light_init(void) +{ + join(status_file, sizeof status_file, runtime, "omarchy-auto-brightness.json"); + light_config(); + discover(); +} + +void light_rediscover(void) +{ + discover(); + light_update(); +} + +void light_cleanup(void) +{ + release_light(); + if (!light_only) + unlink(status_file); +} + +int replay_light(void) +{ + char buf[128]; + double x, t; + light_config(); + while (fgets(buf, sizeof buf, stdin)) { + int raw, target; + double result = NAN; + if (sscanf(buf, "feed %lf %lf", &t, &x) == 2) { + feed(x, t); + result = expm1(level); + } else if (sscanf(buf, "curve %lf", &x) == 1) + result = target_pct(x); + else if (sscanf(buf, "ref %lf %lf", &ref, &moved) == 2) + result = ref; + else if (sscanf(buf, "decide %lf %lf %lf", &t, &level, &x) == 3) { + double next = INFINITY; + result = decide(x, t, &next); + } else if (sscanf(buf, "ramp %d %d %d", &maximum, &raw, &target) == 3) { + start_ramp(raw, target, 0); + result = ramp_secs; + } else if (sscanf(buf, "step %lf", &t) == 1) + result = ramp_value(t); + printf("%.15g\n", result); + fflush(stdout); + } + return 0; +} + +bool light_listening(void) { return claimed; } +bool light_available(void) +{ + return maximum > 0 && (mock_file || (has_light && strcmp(light_source, "iio")) || + (sensor[0] && strcmp(light_source, "proxy"))); +} + +void light_select_source(void) +{ + release_light(); + light_rediscover(); +} + +void light_owner_lost(void) +{ + // Claims went away with the D-Bus unique name. + claimed = has_light = false; + release_light(); +} diff --git a/desktop/session/main.c b/desktop/session/main.c new file mode 100644 index 00000000..b4821b1b --- /dev/null +++ b/desktop/session/main.c @@ -0,0 +1,578 @@ +#include "session.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +sd_event *loop; +sd_bus *bus; +char runtime[PATH_MAX], config[PATH_MAX], state[PATH_MAX]; +const char *light_source; +bool debug_light, light_only, dry_light, probe_light; +const char *mock_file; +static bool accel_claimed; +static sd_event_source *bus_retry, *accel_retry; +static sd_device_monitor *devices; + +const char *env_or(const char *key, const char *fallback) +{ + const char *s = getenv(key); + return s && *s ? s : fallback; +} + +void join(char *out, size_t size, const char *dir, const char *name) +{ + if (snprintf(out, size, "%s/%s", dir, name) >= (int)size) { + fputs("session helper: path too long\n", stderr); + exit(1); + } +} + +double now(void) +{ + struct timespec ts; + clock_gettime(CLOCK_MONOTONIC, &ts); + return ts.tv_sec + ts.tv_nsec * 1e-9; +} + +void timer(sd_event_source **slot, double when, sd_event_time_handler_t callback) +{ + if (!when) { + if (*slot) + sd_event_source_set_enabled(*slot, SD_EVENT_OFF); + return; + } + uint64_t usec = (uint64_t)ceil(when * 1e6); + if (!*slot) + sd_event_add_time(loop, slot, CLOCK_MONOTONIC, usec, 1000, callback, NULL); + else { + sd_event_source_set_time(*slot, usec); + sd_event_source_set_enabled(*slot, SD_EVENT_ONESHOT); + } +} + +double number(const char *dir, const char *name, double fallback) +{ + char path[PATH_MAX]; + double x; + join(path, sizeof path, dir, name); + FILE *f = fopen(path, "re"); + if (!f) + return fallback; + bool ok = fscanf(f, "%lf", &x) == 1 && isfinite(x); + fclose(f); + return ok ? x : fallback; +} + +void atomic_text(const char *path, const char *text) +{ + char tmp[PATH_MAX]; + if (snprintf(tmp, sizeof tmp, "%s.XXXXXX", path) >= (int)sizeof tmp) + return; + int fd = mkostemp(tmp, O_CLOEXEC); + if (fd < 0) + return; + bool ok = write(fd, text, strlen(text)) == (ssize_t)strlen(text); + if (close(fd) == 0 && ok && rename(tmp, path) == 0) + return; + unlink(tmp); +} + +bool claim(const char *method) +{ + return bus && sd_bus_call_method(bus, PROXY, SENSOR_PATH, PROXY, method, NULL, NULL, "") >= 0; +} + +bool get_bool(const char *name) +{ + int yes = 0; + return bus && sd_bus_get_property_trivial(bus, PROXY, SENSOR_PATH, PROXY, name, NULL, 'b', &yes) >= 0 && + yes; +} + +char *get_string(const char *name) +{ + char *value = NULL; + if (bus) + sd_bus_get_property_string(bus, PROXY, SENSOR_PATH, PROXY, name, NULL, &value); + return value; +} + +static void orientation(void) +{ + char *value = get_string("AccelerometerOrientation"); + rotation_observe(value); + free(value); +} + +static int refresh_accel(sd_event_source *s, uint64_t t, void *data) +{ + bool available = get_bool("HasAccelerometer"); + if (!available) { + if (accel_claimed) + claim("ReleaseAccelerometer"); + accel_claimed = false; + rotation_lost(); + } else { + if (!accel_claimed) + accel_claimed = claim("ClaimAccelerometer"); + if (accel_claimed) + orientation(); + } + timer(&accel_retry, available && !accel_claimed ? now() + 3 : 0, refresh_accel); + return 0; +} + +static void proxy_ready(void) +{ + if (!light_only) + refresh_accel(NULL, 0, NULL); + light_proxy(get_bool("HasAmbientLight")); + light_changed(); + light_update(); +} + +static void proxy_lost(void) +{ + accel_claimed = false; + timer(&accel_retry, 0, refresh_accel); + rotation_lost(); + light_owner_lost(); + light_update(); +} + +static int owner_changed(sd_bus_message *m, void *unused, sd_bus_error *error) +{ + const char *name, *old, *current; + if (sd_bus_message_read(m, "sss", &name, &old, ¤t) < 0) + return 0; + if (*old) + proxy_lost(); + if (*current) + proxy_ready(); + return 0; +} + +enum property { LIGHT_VALUE = 1, LIGHT_DEVICE = 2, POSE = 4, ACCEL_DEVICE = 8 }; +static int property(const char *s) +{ + if (!strcmp(s, "LightLevel") || !strcmp(s, "LightLevelUnit")) + return LIGHT_VALUE; + if (!strcmp(s, "HasAmbientLight")) + return LIGHT_DEVICE; + if (!strcmp(s, "AccelerometerOrientation")) + return POSE; + if (!strcmp(s, "HasAccelerometer")) + return ACCEL_DEVICE; + return 0; +} + +static int changed(sd_bus_message *m, void *unused, sd_bus_error *error) +{ + const char *name; + int flags = 0; + if (sd_bus_message_read(m, "s", &name) < 0 || strcmp(name, PROXY)) + return 0; + if (sd_bus_message_enter_container(m, 'a', "{sv}") < 0) + return 0; + while (sd_bus_message_enter_container(m, 'e', "sv") > 0) { + if (sd_bus_message_read(m, "s", &name) < 0) + return 0; + flags |= property(name); + if (sd_bus_message_skip(m, "v") < 0 || sd_bus_message_exit_container(m) < 0) + return 0; + } + if (sd_bus_message_exit_container(m) < 0 || sd_bus_message_enter_container(m, 'a', "s") < 0) + return 0; + while (sd_bus_message_read(m, "s", &name) > 0) + flags |= property(name); + if (!light_only && (flags & ACCEL_DEVICE)) + refresh_accel(NULL, 0, NULL); + else if ((flags & POSE) && accel_claimed) + orientation(); + if (flags & LIGHT_DEVICE) + light_proxy(get_bool("HasAmbientLight")); + if ((flags & LIGHT_DEVICE) || ((flags & LIGHT_VALUE) && light_listening())) { + light_changed(); + light_update(); + } + return 0; +} + +static int connect_bus(sd_event_source *s, uint64_t usec, void *data); +static int disconnected(sd_bus_message *m, void *unused, sd_bus_error *error) +{ + timer(&bus_retry, now() + 1, connect_bus); + proxy_lost(); + return 0; +} + +static int connect_bus(sd_event_source *s, uint64_t usec, void *data) +{ + bus = sd_bus_flush_close_unref(bus); + int rc = sd_bus_open_system(&bus); + if (rc >= 0) { + sd_bus_set_method_call_timeout(bus, 750000); + sd_bus_set_exit_on_disconnect(bus, 0); + rc = sd_bus_add_match(bus, NULL, + "type='signal',sender='org.freedesktop.DBus',interface='org.freedesktop.DBus'," + "member='NameOwnerChanged',arg0='" PROXY "'", + owner_changed, NULL); + } + if (rc >= 0) + rc = sd_bus_match_signal(bus, NULL, PROXY, SENSOR_PATH, "org.freedesktop.DBus.Properties", + "PropertiesChanged", changed, NULL); + if (rc >= 0) + rc = sd_bus_match_signal(bus, NULL, NULL, "/org/freedesktop/DBus/Local", "org.freedesktop.DBus.Local", + "Disconnected", disconnected, NULL); + if (rc >= 0) + rc = sd_bus_attach_event(bus, loop, 0); + if (rc < 0) { + timer(&bus_retry, now() + 3, connect_bus); + light_update(); + } else + proxy_ready(); + return 0; +} + +static int uevent(sd_device_monitor *monitor, sd_device *dev, void *data) +{ + const char *subsystem; + sd_device_action_t action; + if (sd_device_get_subsystem(dev, &subsystem) >= 0 && !strcmp(subsystem, "backlight") && + sd_device_get_action(dev, &action) >= 0 && action == SD_DEVICE_CHANGE) + light_update(); + else + light_rediscover(); + return 0; +} + +static int fs_event(sd_event_source *s, const struct inotify_event *e, void *data) +{ + const char *name = data; + if (!e->len || strcmp(e->name, name)) + return 0; + if (!strcmp(name, "rotation-lock")) + rotation_update(); + else { + if (!strcmp(name, "display") || !strcmp(name, "als-brightness.conf")) + light_config(); + light_rediscover(); + } + return 0; +} + +static void watch(const char *dir, const char *name) +{ + int r = sd_event_add_inotify( + loop, NULL, dir, IN_CREATE | IN_MOVED_TO | IN_DELETE | IN_MOVED_FROM | IN_CLOSE_WRITE | IN_ATTRIB, + fs_event, (void *)name); + if (r < 0) + fprintf(stderr, "session helper: cannot watch %s: %s\n", dir, strerror(-r)); +} + +static int finish(void) +{ + light_cleanup(); + if (accel_claimed) + claim("ReleaseAccelerometer"); + accel_claimed = false; + return sd_event_exit(loop, 0); +} + +static int stop(sd_event_source *s, const struct signalfd_siginfo *si, void *data) +{ + if (si->ssi_signo == SIGHUP) { + light_config(); + light_rediscover(); + return 0; + } + return finish(); +} + +static int compositor_gone(sd_event_source *s, int fd, uint32_t events, void *data) { return finish(); } + +static void directories(void) +{ + char base[PATH_MAX]; + const char *home = env_or("HOME", "/tmp"); + snprintf(runtime, sizeof runtime, "%s", env_or("XDG_RUNTIME_DIR", "/tmp")); + join(base, sizeof base, home, ".config"); + join(config, sizeof config, env_or("XDG_CONFIG_HOME", base), "omarchy"); + join(base, sizeof base, home, ".local/state"); + join(state, sizeof state, env_or("XDG_STATE_HOME", base), "omarchy"); +} + +static void mkdirs(const char *path) +{ + char copy[PATH_MAX]; + snprintf(copy, sizeof copy, "%s", path); + for (char *p = copy + 1; *p; p++) + if (*p == '/') { + *p = 0; + mkdir(copy, 0700); + *p = '/'; + } + mkdir(copy, 0700); +} + +static int send_pipe(int fd) +{ + union { + struct cmsghdr align; + char bytes[CMSG_SPACE(sizeof(int))]; + } control = {0}; + struct iovec iov = {.iov_base = "listen", .iov_len = 6}; + struct msghdr m = { + .msg_iov = &iov, .msg_iovlen = 1, .msg_control = &control, .msg_controllen = sizeof control}; + struct cmsghdr *c = CMSG_FIRSTHDR(&m); + c->cmsg_level = SOL_SOCKET; + c->cmsg_type = SCM_RIGHTS; + c->cmsg_len = CMSG_LEN(sizeof(int)); + int input = STDIN_FILENO; + memcpy(CMSG_DATA(c), &input, sizeof input); + return sendmsg(fd, &m, MSG_NOSIGNAL) == 6 ? 0 : -1; +} + +static int command(sd_event_source *s, int fd, uint32_t events, void *data) +{ + char buf[64]; + union { + struct cmsghdr align; + char bytes[CMSG_SPACE(sizeof(int) * 8)]; + } control; + struct iovec iov = {.iov_base = buf, .iov_len = sizeof buf - 1}; + struct msghdr m = { + .msg_iov = &iov, .msg_iovlen = 1, .msg_control = &control, .msg_controllen = sizeof control}; + ssize_t n = recvmsg(fd, &m, MSG_CMSG_CLOEXEC); + if (n < 0) + return 0; + buf[n] = 0; + bool attach = !strcmp(buf, "listen") && !(m.msg_flags & (MSG_TRUNC | MSG_CTRUNC)); + for (struct cmsghdr *c = CMSG_FIRSTHDR(&m); c; c = CMSG_NXTHDR(&m, c)) { + if (c->cmsg_level != SOL_SOCKET || c->cmsg_type != SCM_RIGHTS) + continue; + int *fds = (int *)CMSG_DATA(c); + size_t count = (c->cmsg_len - CMSG_LEN(0)) / sizeof(int); + for (size_t i = 0; i < count; i++) { + struct stat st; + if (attach && count == 1 && fstat(fds[i], &st) == 0 && S_ISFIFO(st.st_mode)) + keyboard_attach(fds[i]); + else + close(fds[i]); + } + } + if (!strncmp(buf, "source ", 7)) { + const char *sources[] = {"auto", "proxy", "iio"}; + for (unsigned i = 0; i < 3; i++) + if (!strcmp(buf + 7, sources[i])) { + light_source = sources[i]; + light_select_source(); + } + } else if (!strcmp(buf, "debug")) + debug_light = true; + else if (!attach) + keyboard_person(buf); + return 0; +} + +static bool watch_compositor(void) +{ + pid_t pid = atoi(env_or("LABWC_PID", "0")); + int fd = -1; + if (pid > 0) + fd = syscall(SYS_pidfd_open, pid, 0); + bool pidfd = fd >= 0; + if (fd < 0) { + // labwc may spawn its listener before exporting LABWC_PID. An idle client + // connection observes compositor shutdown even when the facts pipe is replaced. + const char *display = getenv("WAYLAND_DISPLAY"); + if (!display) + return pid <= 0; + char path[PATH_MAX]; + struct sockaddr_un addr = {.sun_family = AF_UNIX}; + if (*display == '/') + snprintf(path, sizeof path, "%s", display); + else + join(path, sizeof path, runtime, display); + if (strlen(path) >= sizeof addr.sun_path) + return false; + strcpy(addr.sun_path, path); + fd = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0); + if (fd < 0 || connect(fd, (struct sockaddr *)&addr, sizeof addr) < 0) + return false; + } + return sd_event_add_io(loop, NULL, fd, (pidfd ? EPOLLIN : 0) | EPOLLHUP | EPOLLERR | EPOLLRDHUP, + compositor_gone, NULL) >= 0 && + (pid <= 0 || kill(pid, 0) == 0); +} + +static int owner_socket(char *socket_path, bool listen, bool explicit_source) +{ + char lock_path[PATH_MAX]; + struct stat rt; + if (stat(runtime, &rt) || rt.st_uid != getuid() || (rt.st_mode & 0022)) { + fputs("session helper needs a private XDG_RUNTIME_DIR\n", stderr); + return -1; + } + join(lock_path, sizeof lock_path, runtime, "omarchy-session.lock"); + join(socket_path, PATH_MAX, runtime, "omarchy-keyboard.sock"); + struct sockaddr_un addr = {.sun_family = AF_UNIX}; + if (strlen(socket_path) >= sizeof addr.sun_path) + return -1; + strcpy(addr.sun_path, socket_path); + // Serialize discovery, bind and stale-socket replacement, including a listener-first login. + int lock = open(lock_path, O_RDWR | O_CREAT | O_CLOEXEC | O_NOFOLLOW, 0600); + if (lock < 0 || flock(lock, LOCK_EX) < 0) + return -1; + int fd = socket(AF_UNIX, SOCK_DGRAM | SOCK_CLOEXEC, 0); + if (fd < 0) + return -1; + if (connect(fd, (struct sockaddr *)&addr, sizeof addr) == 0) { + if (listen && send_pipe(fd) < 0) + return -1; + if (explicit_source) { + char request[32]; + snprintf(request, sizeof request, "source %s", light_source); + if (send(fd, request, strlen(request), 0) < 0) + return -1; + } + if (debug_light && send(fd, "debug", 5, 0) < 0) + return -1; + exit(0); + } + if (errno != ENOENT && errno != ECONNREFUSED) + return -1; + unlink(socket_path); + umask(0077); + if (bind(fd, (struct sockaddr *)&addr, sizeof addr) < 0) + return -1; + if (listen) { + pid_t pid = fork(); + if (pid < 0) + return -1; + if (pid > 0) + exit(0); + setsid(); + } + close(lock); + return fd; +} + +static int end_probe(sd_event_source *s, uint64_t t, void *data) { return finish(); } + +int main(int argc, char **argv) +{ + directories(); + if (argc == 2 && !strcmp(argv[1], "replay-keyboard")) + return replay_keyboard(); + if (argc == 2 && !strcmp(argv[1], "replay-rotation")) + return replay_rotation(); + if (argc == 2 && !strcmp(argv[1], "replay-light")) + return replay_light(); + bool listen = false, explicit_source = false; + double seconds = 0; + light_source = env_or("IPAD_ALS_SOURCE", "auto"); + for (int i = 1; i < argc; i++) { + if (!strcmp(argv[i], "listen")) + listen = true; + else if (!strcmp(argv[i], "--debug")) + debug_light = true; + else if (!strcmp(argv[i], "--dry-run")) + dry_light = light_only = true; + else if (!strcmp(argv[i], "--probe")) { + seconds = i + 1 < argc && argv[i + 1][0] != '-' ? atof(argv[++i]) : 20; + if (!(seconds > 0)) + return 2; + probe_light = dry_light = light_only = debug_light = true; + } else if (!strcmp(argv[i], "--mock") && i + 1 < argc) { + mock_file = argv[++i]; + light_only = true; + } else if (!strcmp(argv[i], "--mock-iio") && i + 1 < argc) { + setenv("IPAD_ALS_IIO_ROOT", argv[++i], 1); + light_source = "iio"; + light_only = true; + } else if (!strcmp(argv[i], "--source") && i + 1 < argc) { + light_source = argv[++i]; + explicit_source = true; + } else if (strcmp(argv[i], "daemon")) + return 2; + } + char socket_path[PATH_MAX] = ""; + int fd = -1; + if (!light_only && (fd = owner_socket(socket_path, listen, explicit_source)) < 0) { + perror("omarchy-session-helper"); + return 1; + } + if (sd_event_default(&loop) < 0) + return 1; + sigset_t signals; + sigemptyset(&signals); + int watched[] = {SIGTERM, SIGINT, SIGHUP, SIGCHLD}; + for (int i = 0; i < 4; i++) + sigaddset(&signals, watched[i]); + sigprocmask(SIG_BLOCK, &signals, NULL); + for (int i = 0; i < 3; i++) + sd_event_add_signal(loop, NULL, watched[i], stop, NULL); + if (!watch_compositor()) { + unlink(socket_path); + return 0; + } + if (fd >= 0 && sd_event_add_io(loop, NULL, fd, EPOLLIN, command, NULL) < 0) + return 1; + if (listen) { + keyboard_attach(fcntl(STDIN_FILENO, F_DUPFD_CLOEXEC, 3)); + int null = open("/dev/null", O_RDONLY); + if (null >= 0) { + dup2(null, STDIN_FILENO); + close(null); + } + } + mkdirs(config); + mkdirs(state); + watch(config, "rotation-lock"); + watch(config, "als-brightness.conf"); + watch(state, "display"); + char power_dir[PATH_MAX]; + snprintf(power_dir, sizeof power_dir, "%s", env_or("IPAD_ALS_POWER_SOCKET", "/run/omarchy-powerd.sock")); + char *base = strrchr(power_dir, '/'); + if (base) { + *base++ = 0; + watch(*power_dir ? power_dir : "/", base); + } + if (!light_only) + rotation_init(); + light_init(); + if (sd_device_monitor_new(&devices) >= 0) { + sd_device_monitor_filter_add_match_subsystem_devtype(devices, "backlight", NULL); + sd_device_monitor_filter_add_match_subsystem_devtype(devices, "iio", NULL); + sd_device_monitor_attach_event(devices, loop); + sd_device_monitor_start(devices, uevent, NULL); + } + connect_bus(NULL, 0, NULL); + sd_event_source *end = NULL; + if (probe_light) + timer(&end, now() + seconds, end_probe); + int rc = probe_light && !light_available() ? -ENODEV : sd_event_loop(loop); + if (rc == -ENODEV) + fputs("no backlight or ambient light sensor\n", stderr); + light_cleanup(); + if (accel_claimed) + claim("ReleaseAccelerometer"); + keyboard_detach(); + unlink(socket_path); + if (fd >= 0) + close(fd); + sd_device_monitor_unref(devices); + sd_bus_flush_close_unref(bus); + sd_event_unref(loop); + return rc < 0; +} diff --git a/desktop/session/rotation.c b/desktop/session/rotation.c new file mode 100644 index 00000000..a529bb23 --- /dev/null +++ b/desktop/session/rotation.c @@ -0,0 +1,312 @@ +#include "session.h" +#include +#include +#include +#include +#include + +enum pose { UNKNOWN, NORMAL, BOTTOM, LEFT, RIGHT }; +static const char *names[] = {"undefined", "normal", "bottom-up", "left-up", "right-up"}; +static const char *transforms[] = {"", "normal", "180", "90", "270"}; +static enum pose pending, applied, facing, requested; +static double since, last_apply = -INFINITY, retry_at, settle = .4, cooldown = .75; +static char accel[PATH_MAX], lockfile[PATH_MAX], speaker[PATH_MAX]; +static double matrix[3][3] = {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}}; +static struct sample { + double time, angle; +} history[8]; +static int samples, disagreements; +static sd_event_source *deadline, *child; + +static enum pose pose(const char *s) +{ + for (int i = NORMAL; s && i <= RIGHT; i++) + if (!strcmp(names[i], s)) + return i; + return UNKNOWN; +} + +static void observe(enum pose p, double t) +{ + if (pending != p) { + pending = p; + since = t; + retry_at = 0; + } +} + +static bool ready(double t, bool locked, bool moving, enum pose gravity) +{ + if (locked || !pending || pending == applied || t < since + settle || t < last_apply + cooldown) + return false; + if (moving && t < since + settle + .6) + return false; + return !gravity || gravity == pending || t >= since + settle + 1.2; +} + +static void sample(double x, double y, double z, double t) +{ + double length = hypot(hypot(x, y), z); + if (!isfinite(length) || !length || hypot(x, y) < .25 * length) { + samples = 0; + facing = UNKNOWN; + return; + } + double across = matrix[0][0] * x + matrix[0][1] * y + matrix[0][2] * z; + double along = matrix[1][0] * x + matrix[1][1] * y + matrix[1][2] * z; + facing = fabs(along) >= fabs(across) ? (along < 0 ? NORMAL : BOTTOM) : (across < 0 ? RIGHT : LEFT); + while (samples && (t - history[0].time > .25 || samples == 8)) { + samples--; + memmove(history, history + 1, samples * sizeof *history); + } + history[samples++] = (struct sample){t, atan2(y, x) * 180 / M_PI}; +} + +static bool turning(void) +{ + if (samples < 2) + return false; + struct sample last = history[samples - 1]; + double dt = last.time - history[0].time; + return dt >= .1 && fabs(remainder(last.angle - history[0].angle, 360)) > 40 * dt; +} + +static bool parse_matrix(const char *s) +{ + double m[3][3]; + for (int r = 0; r < 3; r++) { + for (int c = 0; c < 3; c++) { + char *end; + m[r][c] = strtod(s, &end); + if (end == s || !isfinite(m[r][c])) + return false; + while (isspace((unsigned char)*end)) + end++; + if (c < 2 || r < 2) { + if (*end++ != (c < 2 ? ',' : ';')) + return false; + } else if (*end) + return false; + s = end; + } + if (!m[r][0] && !m[r][1] && !m[r][2]) + return false; + } + memcpy(matrix, m, sizeof matrix); + return true; +} + +static void discover_accel(void) +{ + char pattern[PATH_MAX], resolved[PATH_MAX]; + glob_t files = {0}; + join(pattern, sizeof pattern, env_or("ROTATE_ACCEL", "/sys/bus/iio/devices/iio:device*"), + "in_accel_x_raw"); + if (glob(pattern, 0, NULL, &files) == 0) { + snprintf(accel, sizeof accel, "%s", files.gl_pathv[0]); + *strrchr(accel, '/') = 0; + } + globfree(&files); + if (!*accel) + return; + sd_device *dev = NULL; + const char *value; + if (realpath(accel, resolved)) + sd_device_new_from_syspath(&dev, resolved); + bool found = + dev && sd_device_get_property_value(dev, "ACCEL_MOUNT_MATRIX", &value) >= 0 && parse_matrix(value); + sd_device_unref(dev); + const char *attrs[] = {"mount_matrix", "in_accel_mount_matrix", "in_mount_matrix"}; + for (int i = 0; !found && i < 3; i++) { + char path[PATH_MAX], buf[256]; + join(path, sizeof path, accel, attrs[i]); + FILE *f = fopen(path, "re"); + if (f) { + found = fgets(buf, sizeof buf, f) && parse_matrix(buf); + fclose(f); + } + } +} + +struct output { + char name[256], transform[32]; + bool enabled; +}; +static bool internal(const char *s) +{ + return !strncmp(s, "eDP-", 4) || !strncmp(s, "DSI-", 4) || !strncmp(s, "LVDS-", 5); +} + +// This runs in a short-lived child. A slow compositor cannot stall input or light. +static int apply(enum pose orientation) +{ + FILE *p = popen("timeout 3 wlr-randr", "r"); + if (!p) + return 1; + struct output current = {0}, selected = {0}; + char line[1024]; + int count = 0; + for (;;) { + bool end = !fgets(line, sizeof line, p); + if (end || !isspace((unsigned char)line[0])) { + if (current.name[0] && (orientation || current.enabled)) { + if (!count || (!internal(selected.name) && internal(current.name))) + selected = current; + count++; + } + if (end) + break; + current = (struct output){0}; + sscanf(line, "%255s", current.name); + } else { + char value[32]; + if (sscanf(line, " Enabled: %31s", value) == 1) + current.enabled = !strcmp(value, "yes"); + if (sscanf(line, " Transform: %31s", value) == 1) + snprintf(current.transform, sizeof current.transform, "%s", value); + } + } + if (pclose(p) || !count || (count > 1 && !internal(selected.name))) + return 1; + const char *transform = orientation ? transforms[orientation] : selected.transform; + if (orientation) { + pid_t pid = fork(); + if (pid == 0) { + execlp("timeout", "timeout", "4", "wlr-randr", "--output", selected.name, "--transform", + transform, NULL); + _exit(127); + } + int status; + if (pid < 0 || waitpid(pid, &status, 0) < 0 || status) + return 1; + } + if (speaker[0]) { + for (int i = NORMAL; i <= RIGHT; i++) + if (!strcmp(transform, transforms[i])) { + char text[64]; + snprintf(text, sizeof text, "%s\n", transform); + atomic_text(speaker, text); + } + } + return 0; +} + +static int finished(sd_event_source *s, const siginfo_t *info, void *data) +{ + child = sd_event_source_unref(child); + if (requested) { + if (info->si_code == CLD_EXITED && !info->si_status) { + applied = requested; + last_apply = now(); + if (facing) + disagreements = facing == applied ? 0 : disagreements + 1; + } else + retry_at = now() + 2; + } + rotation_update(); + return 0; +} + +static void start_request(enum pose p) +{ + pid_t pid = fork(); + if (!pid) { + sigset_t empty; + sigemptyset(&empty); + sigprocmask(SIG_SETMASK, &empty, NULL); + _exit(apply(p)); + } + if (pid > 0 && sd_event_add_child(loop, &child, pid, WEXITED, finished, NULL) >= 0) { + requested = p; + sd_event_source_set_child_process_own(child, 1); + } else + retry_at = now() + 2; +} + +static int expire(sd_event_source *s, uint64_t usec, void *data) +{ + rotation_update(); + return 0; +} + +void rotation_update(void) +{ + double t = now(), next = 0; + if (!pending || applied == pending || access(lockfile, F_OK) == 0 || child) { + samples = 0; + facing = UNKNOWN; + } else if (t < retry_at) + next = retry_at; + else { + if (*accel) + sample(number(accel, "in_accel_x_raw", NAN), number(accel, "in_accel_y_raw", NAN), + number(accel, "in_accel_z_raw", NAN), t); + if (ready(t, false, turning(), disagreements < 3 ? facing : UNKNOWN)) { + start_request(pending); + if (!child) + next = retry_at; + } else + next = *accel ? t + .1 : fmax(since + settle, last_apply + cooldown); + } + timer(&deadline, next, expire); +} + +void rotation_observe(const char *value) +{ + enum pose p = pose(value); + if (p && !pending && !*accel) + discover_accel(); + observe(p, now()); + rotation_update(); +} + +void rotation_lost(void) +{ + rotation_observe(NULL); + *accel = 0; + disagreements = 0; +} + +void rotation_init(void) +{ + settle = atof(env_or("ROTATE_SETTLE", ".4")); + cooldown = atof(env_or("ROTATE_COOLDOWN", ".75")); + join(lockfile, sizeof lockfile, config, "rotation-lock"); + if (!access("/sys/firmware/devicetree/base/sound-speaker-transport", F_OK)) { + join(speaker, sizeof speaker, runtime, "omarchy-j120-speaker-transform"); + start_request(UNKNOWN); + } +} + +int replay_rotation(void) +{ + char buf[512], cmd[32], value[128]; + double t, x, y, z; + int locked, moving; + while (fgets(buf, sizeof buf, stdin)) { + const char *out = "-"; + if (sscanf(buf, "%31s", cmd) != 1) + return 2; + if (!strcmp(cmd, "observe") && sscanf(buf, "%*s %lf %127s", &t, value) == 2) + observe(pose(value), t); + else if (!strcmp(cmd, "commit") && sscanf(buf, "%*s %lf %127s", &t, value) == 2) { + applied = pose(value); + last_apply = t; + } else if (!strcmp(cmd, "ready") && + sscanf(buf, "%*s %lf %d %d %127s", &t, &locked, &moving, value) == 4) + out = ready(t, locked, moving, pose(value)) ? names[pending] : "-"; + else if (!strcmp(cmd, "matrix")) + parse_matrix(buf + 7); + else if (!strcmp(cmd, "sample") && sscanf(buf, "%*s %lf %lf %lf %lf", &t, &x, &y, &z) == 4) + sample(x, y, z, t); + else if (!strcmp(cmd, "judged") && sscanf(buf, "%*s %127s", value) == 1 && facing) + disagreements = facing == pose(value) ? 0 : disagreements + 1; + else if (!strcmp(cmd, "facing")) + out = disagreements < 3 && facing ? names[facing] : "-"; + else if (!strcmp(cmd, "turning")) + out = turning() ? "1" : "0"; + puts(out); + fflush(stdout); + } + return 0; +} diff --git a/desktop/session/session.h b/desktop/session/session.h new file mode 100644 index 00000000..f1d29abb --- /dev/null +++ b/desktop/session/session.h @@ -0,0 +1,50 @@ +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include +#include + +extern sd_event *loop; +extern sd_bus *bus; +extern char runtime[PATH_MAX], config[PATH_MAX], state[PATH_MAX]; +extern const char *light_source; +extern bool debug_light; +#define PROXY "net.hadess.SensorProxy" +#define SENSOR_PATH "/net/hadess/SensorProxy" +const char *env_or(const char *key, const char *fallback); +double now(void); +void timer(sd_event_source **slot, double when, sd_event_time_handler_t callback); +void join(char *out, size_t size, const char *dir, const char *name); +double number(const char *dir, const char *name, double fallback); +void atomic_text(const char *path, const char *text); +bool claim(const char *method); +bool get_bool(const char *name); +char *get_string(const char *name); +void keyboard_attach(int fd); +void keyboard_person(const char *line); +void keyboard_detach(void); +void rotation_init(void); +void rotation_observe(const char *value); +void rotation_update(void); +void rotation_lost(void); +void light_init(void); +void light_config(void); +void light_update(void); +void light_changed(void); +void light_proxy(bool available); +void light_cleanup(void); +void light_owner_lost(void); +bool light_listening(void); +bool light_available(void); +void light_select_source(void); +void light_rediscover(void); +extern bool light_only, dry_light, probe_light; +extern const char *mock_file; +int replay_keyboard(void); +int replay_rotation(void); +int replay_light(void); diff --git a/desktop/shell/bin/omarchy-keyboard b/desktop/shell/bin/omarchy-keyboard index 9c586068..439d5d57 100644 --- a/desktop/shell/bin/omarchy-keyboard +++ b/desktop/shell/bin/omarchy-keyboard @@ -16,7 +16,6 @@ taps, keys typed on a physical keyboard, how many such keyboards there are. """ import os from pathlib import Path -import selectors import signal import socket import subprocess @@ -80,149 +79,6 @@ def hide(): os.kill(pid, signal.SIGUSR1) -class Policy: - """When the keyboard opens and closes on its own. - - It opens when the person taps a text field, never because a program moved - focus, and never for a press that becomes a drag or a long press (selecting - text). Apps on text-input version 2 ask for it themselves (`show`), and are - heard right after a touch only: Qt asks whenever a field gets focus, also - one an app focuses on start. A request that comes just before its field - reports itself (a tap that turns a label into a field) is kept a moment. - Version 1 apps cannot ask: for them a tap counts when a field is on at the - end of it, or comes on right after it (a tap that focused a field, a tap in - a terminal, which has text input whenever it is focused; a tap that moved - focus off a field turns it off before the tap ends). - - It closes when the app asks, and shortly after no field is on any more, if - it opened on its own. One the person put away stays away until the next - tap on a field. - - Typing on a physical keyboard closes it and stops taps from opening it, - until the person opens it (swipe up, bar button) or no physical keyboard is - left. Being connected alone changes nothing. - """ - - TAP_MS = 350 # longer is a long press - TAP_PX = 12 # further is a drag - TOUCH_WINDOW = 0.6 # a touch to an app's request, a tap to a field coming on - SHOW_WAIT = 0.5 # a request to its field coming on - HIDE_DELAY = 0.25 # focus moving from one field to the next - - def __init__(self, show, hide, visible, now=time.monotonic): - self._show, self._hide, self._visible, self.now = show, hide, visible, now - self.field = 0 # the focused field's text-input version, 0 when none - self.touched_until = 0.0 # a press, or the release of a tap, just happened - self.tapped_until = 0.0 # a tap just ended - self.asked_until = 0.0 # an app asked before its field came on - self.hide_at = None - self.hide_asked = False # the app asked to hide; held back like a field going off - self.pressing = False # a finger is down on the focused surface - self.opened_here = False - self.hardware = False # typing on a physical keyboard - self.held = False # the control center is over the app (hold … release) - self.keyboards = 0 - - def _open(self): - self.touched_until = self.tapped_until = self.asked_until = 0.0 - self.hide_at, self.hide_asked = None, False - if self.hardware: - return - self.opened_here = True - if not self._visible(): # a field taking focus and the app asking are one tap - self._show() - - def _close(self): - self.hide_at, self.hide_asked = None, False - if self.opened_here: - self.opened_here = False - self._hide() - - def fact(self, line): - now = self.now() - words = line.split() - if words[:2] == ["field", "on"] and len(words) == 3 and words[2].isdigit(): - self.field, self.hide_at = int(words[2]), None - # A field that takes focus while the finger is down was tapped, - # whatever version: Qt does not ask again for a keyboard it - # thinks is still up, after one that closed on its own. - if now < self.asked_until or (self.pressing and now < self.touched_until) \ - or (self.field < 2 and now < self.tapped_until): - self._open() - elif words == ["field", "off"]: - self.field = 0 - if self.opened_here and not self.held: - self.hide_at = now + self.HIDE_DELAY - elif words == ["show"]: - # Asked for right after a touch: Qt asks only for a text item it - # focused, and may enable its text input only at the next input - # event (a field tapped again after focus went elsewhere), so the - # request is enough. The keyboard types through key presses. - if now < self.touched_until: - self._open() - elif words == ["hide"]: - # Held back a moment: an app that asks to hide and show again at - # once (to be heard after the person put the keyboard away) must - # not make an open keyboard blink. - if self.opened_here: - self.hide_at, self.hide_asked = now + self.HIDE_DELAY, True - elif words == ["press"]: - self.touched_until = now + self.TOUCH_WINDOW - self.pressing = True - elif words[:1] == ["release"] and len(words) == 3 and words[1].isdigit() and words[2].isdigit(): - self.pressing = False - if int(words[1]) <= self.TAP_MS and int(words[2]) <= self.TAP_PX: - self.touched_until = self.tapped_until = now + self.TOUCH_WINDOW - if 0 < self.field < 2: - self._open() - else: - self.touched_until = self.tapped_until = 0.0 - elif words == ["key"]: - if self.keyboards > 0: - self.hardware = True - self.touched_until = self.tapped_until = self.asked_until = 0.0 - self.opened_here = False - if self._visible(): - self._hide() - elif words[:1] == ["keyboards"] and len(words) == 2 and words[1].isdigit(): - self.keyboards = int(words[1]) - if self.keyboards == 0: - self.hardware = False - - def person(self, action): - """The person opened or closed it (swipe up, bar button).""" - if action == "hold": - # The control center opens over the app and takes the keyboard: - # the app's field goes off, and the keyboard stays, under it. - self.held, self.hide_at, self.hide_asked = True, None, False - return - if action == "release": - # Closed again: the keyboard goes only if no field came back. - self.held = False - if self.opened_here and not self.field: - self.hide_at = self.now() + self.HIDE_DELAY - return - if action == "quiet": - # A launcher opening a window to read, not to type in (About's - # terminal): the tap that started it does not count for the field - # its window brings. A tap in the window still opens the keyboard. - self.touched_until = self.tapped_until = self.asked_until = 0.0 - return - self.opened_here = False - self.hide_at = None - if action == "show": - self.hardware = False - - def deadline(self): - return self.hide_at - - def tick(self): - if self.hide_at is not None and self.now() >= self.hide_at: - if self.hide_asked or not self.field: - self._close() - self.hide_at, self.hide_asked = None, False - - def tell_policy(action): """Lets a running policy know what the person did; nothing when none runs.""" try: @@ -232,39 +88,6 @@ def tell_policy(action): pass -def listen(): - policy = Policy(show, hide, visible) - try: - policy_socket.unlink() - except FileNotFoundError: - pass - person = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM) - person.bind(str(policy_socket)) - os.set_blocking(sys.stdin.fileno(), False) - events = selectors.DefaultSelector() - events.register(sys.stdin.buffer, selectors.EVENT_READ, "facts") - events.register(person, selectors.EVENT_READ, "person") - pending = b"" - while True: - deadline = policy.deadline() - timeout = None if deadline is None else max(0.0, deadline - policy.now()) - for key, _ in events.select(timeout): - if key.data == "person": - policy.person(person.recv(64).decode(errors="replace").strip()) - continue - chunk = os.read(sys.stdin.fileno(), 4096) - if not chunk: - return # the compositor went away - pending += chunk - while b"\n" in pending: - line, pending = pending.split(b"\n", 1) - try: - policy.fact(line.decode(errors="replace")) - except Exception as error: # a bad line must not end the session's keyboard - print("omarchy-keyboard: " + repr(error), file=sys.stderr) - policy.tick() - - def phone(): """A phone: the screen's short side under 480 logical pixels, the width under which the shell lays itself out as on a phone too.""" @@ -327,7 +150,9 @@ def main(mode): elif mode in ("quiet", "hold", "release"): tell_policy(mode) elif mode == "listen": - listen() + os.execl("/usr/libexec/omarchy-session-helper", "omarchy-session-helper", "listen") + elif mode == "policy-show": + show() elif mode == "restart": if pid := live_pid(): os.kill(pid, signal.SIGTERM) diff --git a/desktop/shell/default/labwc/autostart b/desktop/shell/default/labwc/autostart index 083226f7..5f6e811b 100755 --- a/desktop/shell/default/labwc/autostart +++ b/desktop/shell/default/labwc/autostart @@ -9,12 +9,10 @@ rm -f "$XDG_RUNTIME_DIR/omarchy-overview-open" # Hardware output timing and mode come from the kernel bundle. # On the verified native portrait panel, set logical scale before mapping UI. /usr/libexec/arch-ipad-scale-output > "$XDG_RUNTIME_DIR/arch-ipad-display.log" 2>&1 || true -# Turn the panel with the device (iio-sensor-proxy); a no-op without an accelerometer. -/usr/libexec/arch-ipad-rotate-output > "$XDG_RUNTIME_DIR/arch-ipad-rotation.log" 2>&1 & +# Share light, rotation and the compositor's keyboard listener in one session process. +/usr/libexec/omarchy-session-helper > "$XDG_RUNTIME_DIR/arch-ipad-auto-brightness.log" 2>&1 & # Let user services launched after the compositor see its actual Wayland socket. systemctl --user import-environment WAYLAND_DISPLAY XDG_CURRENT_DESKTOP XDG_SESSION_TYPE > "$XDG_RUNTIME_DIR/arch-ipad-user-env.log" 2>&1 -# Sensor policy follows the compositor lifetime; it stays off until enabled. -/usr/libexec/arch-ipad-auto-brightness > "$XDG_RUNTIME_DIR/arch-ipad-auto-brightness.log" 2>&1 & # The output's mute follows the side mute switch; exits without one. /usr/libexec/omarchy-mute-switch > "$XDG_RUNTIME_DIR/omarchy-mute-switch.log" 2>&1 & # Keep the theme-coloured keyboard resident but hidden until the user taps Show. diff --git a/docs/native-session-trial.md b/docs/native-session-trial.md new file mode 100644 index 00000000..ed6042cf --- /dev/null +++ b/docs/native-session-trial.md @@ -0,0 +1,93 @@ +# N42 session helper trial + +Run from this checkout in Bash. The trial needs a running labwc session, a +configured SSH host alias for the test device, and a helper built for its CPU. +Set OMARCHY_TRIAL_HOST to the SSH alias and verify the host key before the trial. + +```bash +set -e +n42=(ssh -o StrictHostKeyChecking=yes -o ConnectTimeout=10 "${OMARCHY_TRIAL_HOST:?set the SSH host alias}") +stage=$(mktemp -d) +trial=$("${n42[@]}" 'mktemp -d /var/tmp/native-session.XXXXXX') +echo "Keep this phone path for rollback: $trial" +cp tools/measure-session-helpers "$stage/" +cp out/armv7h/omarchy-session-helper "$stage/" +``` + +Merge the notification change with the phone's installed powerd to retain any N42 power fixes. The existing packaged autostart can keep calling both compatibility names. This trial also keeps local autostart additions. + +```bash +"${n42[@]}" 'cat /usr/libexec/omarchy-powerd' > "$stage/powerd.original" +git show HEAD^:system/overlay/usr/libexec/omarchy-powerd > "$stage/powerd.base" +git merge-file -p "$stage/powerd.original" "$stage/powerd.base" \ + system/overlay/usr/libexec/omarchy-powerd > "$stage/omarchy-powerd" +cp desktop/configuration/auto-brightness "$stage/arch-ipad-auto-brightness" +cp desktop/configuration/rotate-output "$stage/arch-ipad-rotate-output" +cp desktop/shell/bin/omarchy-keyboard "$stage/" +COPYFILE_DISABLE=1 tar -C "$stage" -cf - . | "${n42[@]}" "tar -C '$trial' -xf -" +``` + +Tap a field once and dismiss the keyboard to start the old listener. Use the same light setting, shell layout, ambient light, orientation and charger state for both measurements. Sample with the panel lit and the scene settled. Repeat each sample in the dark with the same suspend inhibitor on both revisions. + +```bash +"${n42[@]}" "python3 '$trial/measure-session-helpers' old" +``` + +Install from the USB session. Restarting greetd ends the current graphical session. + +```bash +"${n42[@]}" "cd '$trial' && bash -se" <<'INSTALL' +cmp powerd.original /usr/libexec/omarchy-powerd +test ! -e /usr/libexec/omarchy-session-helper +mkdir backup +for f in /usr/libexec/{omarchy-powerd,arch-ipad-auto-brightness,arch-ipad-rotate-output} \ + /usr/share/omarchy/bin/omarchy-keyboard; do + cp -a --parents "$f" backup/ +done +systemctl stop greetd +for f in /usr/libexec/{omarchy-session-helper,arch-ipad-auto-brightness,arch-ipad-rotate-output,omarchy-powerd} \ + /usr/share/omarchy/bin/omarchy-keyboard; do + install -m755 "${f##*/}" "$f.native-new" + mv -f "$f.native-new" "$f" +done +systemctl restart omarchy-powerd +systemctl start greetd +INSTALL +``` + +After login, tap and dismiss the keyboard and let the scene settle again. + +```bash +"${n42[@]}" "python3 '$trial/measure-session-helpers' native" +``` + +The acceptance threshold is 6,144 KiB RSS for the single resident policy PID. Subtract native PSS from summed old PSS for the estimated physical-memory saving. CPU is the change in user and system ticks divided by elapsed time on one core. The sample excludes powerd, wvkbd and the sensor service. + +## Functional checks + +Run the user commands inside the graphical session and observe the panel and touch input. + +- Enable ALS with `omarchy-auto-brightness on`. Brighten and shade the sensor. Check the fade and `omarchy-auto-brightness status`. Darken with the power button, change the light, then wake. Expect a dark hold, released light claim, and adjustment after the one-second wake settle. To inspect claims and property reads during this check, run `sudo busctl monitor --system net.hadess.SensorProxy` from another terminal. With direct IIO selected, `sudo strace -e openat -p PID` should show zero illuminance attribute opens while dark. Stop tracing before measuring CPU. +- Set `omarchy-brightness-display --no-osd 35%` with ALS active. Check that the selected level holds for the configured override interval (30 s by default), then automatic adjustment resumes. +- Run `omarchy-rotation-lock on`, turn through 180°, wait, then run `omarchy-rotation-lock off`. Expect one final transform and matching touch coordinates without moving the phone again. +- Tap a text field, run `omarchy-keyboard hold`, move focus away, then run `omarchy-keyboard release`. The keyboard should stay open during hold and hide after release if no field returns. Also check manual show/hide, a drag, and typing on a physical keyboard. +- Run `sudo systemctl restart iio-sensor-proxy`. Check that the keyboard still works, lux and orientation return, and the native PID stays the same. + +## Rollback + +In the same Mac shell, or after setting `trial` to the phone path printed during staging, restore the saved files and start a fresh session. + +```bash +"${n42[@]}" "cd '$trial' && bash -se" <<'ROLLBACK' +test -f backup/usr/libexec/omarchy-powerd +systemctl stop greetd +for f in /usr/libexec/{omarchy-powerd,arch-ipad-auto-brightness,arch-ipad-rotate-output} \ + /usr/share/omarchy/bin/omarchy-keyboard; do + cp -a "backup$f" "$f.rollback" + mv -f "$f.rollback" "$f" +done +rm -f /usr/libexec/omarchy-session-helper +systemctl restart omarchy-powerd +systemctl start greetd +ROLLBACK +``` diff --git a/docs/tablet-sensors.md b/docs/tablet-sensors.md index 52d6d8f7..d30909fe 100644 --- a/docs/tablet-sensors.md +++ b/docs/tablet-sensors.md @@ -23,6 +23,12 @@ Both fresh desktop staging and the public-root builder include the helper and it Host checks cover the retained light policy, switch state, missing power daemon, stale-value/dark-panel refusal, manual pause, actual socket writes, rotation debounce/lock/unlock and compositor exit, plus staging and public-root inclusion. Physical lux response, all four orientation directions, touch mapping and power-button/idle/sleep coexistence still need a device run. +## Native session helper + +The packaged labwc session runs one unprivileged `omarchy-session-helper`. It claims sensors directly on the system bus; old autostarts can still launch either sensor helper. Labwc hands its facts pipe to the same process via `omarchy-keyboard listen`. The user commands, status JSON, rotation lock and themed wvkbd process keep their existing interfaces. + +Powerd updates its socket timestamp when its ALS hold changes. The session helper watches that event, rechecks `als-state` before reading light, and supplies the expected old value on automatic writes. With stable proxy readings the helper arms no periodic policy timer. Direct IIO fallback samples at most once every two seconds while enabled and lit. The following profile describes the earlier Python implementation. For the native comparison see [the N42 trial instructions](native-session-trial.md). + ## Background helper cost On 2026-12-01, a 60-second shell profile on the iPhone 5 attributed 4.2% of samples to the battery helper and 3.4% to `awk`. At idle, auto-brightness used about 2% CPU and iio-sensor-proxy 1.4%. Process RSS was 15 MB for auto-brightness, 12 MB each for rotation and the keyboard listener, and 21 MB for the separate power daemon. diff --git a/release/audit.py b/release/audit.py index cd218a00..7ad7b136 100644 --- a/release/audit.py +++ b/release/audit.py @@ -15,8 +15,9 @@ from .public_root import sha -# The two compiled helpers of the omarchy-a package, of the root's architecture. -HELPERS = {'usr/libexec/omarchy-wtype': 'startup cursor helper', +# The compiled helpers of the omarchy-a package, of the root's architecture. +HELPERS = {'usr/libexec/omarchy-session-helper': 'session policy helper', + 'usr/libexec/omarchy-wtype': 'startup cursor helper', 'usr/share/omarchy/trials/wvkbd-mobintl-v0.20-font18-special15-state': 'on-screen keyboard'} def private_firmware(orchard=None): diff --git a/system/overlay/usr/libexec/omarchy-powerd b/system/overlay/usr/libexec/omarchy-powerd index 46e70f67..2167cdb9 100755 --- a/system/overlay/usr/libexec/omarchy-powerd +++ b/system/overlay/usr/libexec/omarchy-powerd @@ -1175,6 +1175,9 @@ class Daemon: monitor.stdout.close() # --- control socket ----------------------------------------------------- + def als_lit(self): + return self.machine.state == ON and self.fade is None and self.dim_saved is None + def control(self, server): connection, _ = server.accept() with connection: @@ -1206,7 +1209,7 @@ class Daemon: reply = b'ok\n' connection.sendall(reply) elif request == 'als-state': - connection.sendall(b'lit\n' if self.machine.state == ON and self.fade is None and self.dim_saved is None else b'dark\n') + connection.sendall(b'lit\n' if self.als_lit() else b'dark\n') elif request == 'dim': panel = self.backlight() if self.machine.state == ON and self.dim_saved is None and panel: @@ -1351,7 +1354,13 @@ class Daemon: self.start_uevents() threading.Thread(target=self.session_worker, daemon=True).start() log('ready: ON') + als_lit = self.als_lit() while not self.stopping: + # Notify inotify clients when their als-state answer changes. The + # control request remains authoritative, including after a restart. + if als_lit != self.als_lit(): + als_lit = self.als_lit() + os.utime(SOCKET, None) delay = self.timeout() watched = [*self.keys, *self.covers, server, self.wake_read, self.monitor.stdout] if self.uevents: diff --git a/tests/package_tree.py b/tests/package_tree.py index 4e715a84..77136f55 100644 --- a/tests/package_tree.py +++ b/tests/package_tree.py @@ -32,7 +32,7 @@ def inputs(base): """BUILD, OMARCHY and DBUS_NEXT for install-tree, under BASE.""" build, upstream, wheel = base / 'build', base / 'omarchy', base / 'wheel' build.mkdir() - for name in ('wvkbd-mobintl', 'wtype'): + for name in ('wvkbd-mobintl', 'wtype', 'omarchy-session-helper'): (build / name).write_bytes(elf()) (build / 'wtype.LICENSE').write_text('MIT\n') (upstream / 'themes/jade-horse/backgrounds').mkdir(parents=True) diff --git a/tests/session_replay.py b/tests/session_replay.py new file mode 100644 index 00000000..3137d8d9 --- /dev/null +++ b/tests/session_replay.py @@ -0,0 +1,37 @@ +"""Run the compiled session helper behind the existing policy input replays.""" +import functools +import os +from pathlib import Path +import subprocess + +PROJECT = Path(__file__).resolve().parents[1] + + +@functools.cache +def binary(): + if override := os.environ.get("OMARCHY_TEST_SESSION_HELPER"): + return Path(override).resolve() + build = PROJECT / "out" / "session-tests" + target = build / "omarchy-session-helper" + subprocess.run(["make", f"BUILD={build}", str(target)], cwd=PROJECT, check=True) + return target + + +def replay(test, policy): + process = subprocess.Popen([binary(), "replay-" + policy], stdin=subprocess.PIPE, + stdout=subprocess.PIPE, text=True) + + def close(): + process.stdin.close() + process.wait(timeout=3) + process.stdout.close() + test.assertEqual(process.returncode, 0) + test.addCleanup(close) + + def exchange(line): + process.stdin.write(line + "\n") + process.stdin.flush() + result = process.stdout.readline() + test.assertTrue(result, "session helper exited during replay") + return result.strip() + return exchange diff --git a/tests/test_auto_brightness.py b/tests/test_auto_brightness.py index 247bae35..f5bc5a91 100644 --- a/tests/test_auto_brightness.py +++ b/tests/test_auto_brightness.py @@ -1,106 +1,172 @@ -"""Ported ALS policy and power-daemon cooperation, with no hardware access.""" -import importlib.machinery -import importlib.util +"""Replay the ALS policy and its power-daemon exchanges without sensor hardware.""" +from importlib.machinery import SourceFileLoader +from importlib.util import module_from_spec, spec_from_loader +import json import math import os from pathlib import Path +import socketserver +import subprocess import tempfile +import threading +import time import unittest from unittest.mock import patch -PROJECT = Path(__file__).resolve().parents[1] -loader = importlib.machinery.SourceFileLoader('auto_brightness', str(PROJECT/'desktop/configuration/auto-brightness')) -spec = importlib.util.spec_from_loader(loader.name, loader) -a = importlib.util.module_from_spec(spec); loader.exec_module(a) +from session_replay import PROJECT, binary, replay + +loader = SourceFileLoader('auto_brightness', str(PROJECT/'desktop/configuration/auto-brightness')) +a = module_from_spec(spec_from_loader(loader.name, loader)) +loader.exec_module(a) + class AutoBrightness(unittest.TestCase): def setUp(self): - temp = tempfile.TemporaryDirectory(); self.addCleanup(temp.cleanup) - self.root = Path(temp.name); self.panel = self.root/'backlight/panel'; self.panel.mkdir(parents=True) - (self.panel/'max_brightness').write_text('1000\n'); self.set_raw(500) - self.env = patch.dict(os.environ, {'XDG_CONFIG_HOME':str(self.root/'config'), - 'XDG_STATE_HOME':str(self.root/'state'), 'XDG_RUNTIME_DIR':str(self.root), - 'IPAD_ALS_BACKLIGHT_ROOT':str(self.root/'backlight')}) - self.env.start(); self.addCleanup(self.env.stop) + temp = tempfile.TemporaryDirectory() + self.addCleanup(temp.cleanup) + self.root = Path(temp.name) + self.panel = self.root/'backlight/panel' + self.panel.mkdir(parents=True) + (self.panel/'max_brightness').write_text('1000\n') + self.set_raw(500) + self.sock = self.root/'power.sock' + env = patch.dict(os.environ, {'XDG_CONFIG_HOME': str(self.root/'config'), + 'XDG_STATE_HOME': str(self.root/'state'), 'XDG_RUNTIME_DIR': str(self.root), + 'IPAD_ALS_BACKLIGHT_ROOT': str(self.root/'backlight'), 'IPAD_ALS_POWER_SOCKET': str(self.sock), + 'IPAD_ALS_IIO_ROOT': str(self.root/'iio')}) + env.start() + self.addCleanup(env.stop) self.conf = a.load_conf() - def set_raw(self, value): (self.panel/'brightness').write_text(str(value)+'\n') + def set_raw(self, value): + (self.panel/'brightness').write_text(str(value)+'\n') def test_default_off_and_persisted_switch(self): self.assertFalse(a.is_enabled(self.conf)) - a.set_state('auto_brightness','on'); self.assertTrue(a.is_enabled(self.conf)) - a.set_state('auto_brightness','off'); self.assertFalse(a.is_enabled(self.conf)) + a.set_state('auto_brightness', 'on') + self.assertTrue(a.is_enabled(self.conf)) + a.set_state('auto_brightness', 'off') + self.assertFalse(a.is_enabled(self.conf)) def test_curve_and_median_ignore_one_spike(self): - points = a.parse_curve(a.DEFAULT_CURVE) - self.assertEqual(a.curve_pct(points, 80), 58) - self.assertEqual(a.curve_pct(points, 100000), 100) - smooth = a.Smoother(0) - for i, lux in enumerate((20,20,20,20000,20)): smooth.feed(lux,float(i)) - self.assertAlmostEqual(smooth.lux,20) + send = replay(self, 'light') + self.assertEqual(float(send('curve 80')), 58) + self.assertEqual(float(send('curve 100000')), 100) + for t, lux in enumerate((20, 20, 20, 20000, 20)): + smoothed = float(send(f'feed {t} {lux}')) + self.assertAlmostEqual(smoothed, 20) def test_brightening_is_fast_and_darkening_slow(self): - # Hands-on test 2026-11-08: a flashlight took seconds to register, then moved in steps. - up=a.Smoother(3.0,tau_up=0.4); down=a.Smoother(3.0,tau_up=0.4) - for t in (0.0,0.25,0.5): up.feed(20,t); down.feed(2000,t) - for t in (0.75,1.0,1.25,1.5): up.feed(2000,t); down.feed(20,t) - self.assertGreater(up.lux,800) # most of the way within ~1 s of a flashlight - self.assertGreater(down.lux,300) # a shadow does not dim at once - policy=a.Policy(self.conf); policy.ref_level=0.0; policy.last_move=10.0 - class S: level=math.log1p(1000); lux=1000 - self.assertIsNotNone(policy.decide(S,10.3,30.0)) # brighter: 0.25 s spacing - policy.last_move=10.0 - class D: level=math.log1p(0.5); lux=0.5 - policy.ref_level=math.log1p(1000) - self.assertIsNone(policy.decide(D,10.3,90.0)) # darker: keeps the 2 s spacing + up, down = replay(self, 'light'), replay(self, 'light') + for t in (0, .25, .5): + up(f'feed {t} 20') + down(f'feed {t} 2000') + for t in (.75, 1, 1.25, 1.5): + bright, dark = float(up(f'feed {t} 2000')), float(down(f'feed {t} 20')) + self.assertGreater(bright, 800) + self.assertGreater(dark, 300) + up('ref 0 10') + self.assertTrue(math.isfinite(float(up(f'decide 10.3 {math.log1p(1000)} 30')))) + down(f'ref {math.log1p(1000)} 10') + self.assertTrue(math.isnan(float(down(f'decide 10.3 {math.log1p(.5)} 90')))) + + def start(self): + self.requests = [] + self.reply = 'lit' + sensor = self.root/'iio/iio:device0' + sensor.mkdir(parents=True) + (sensor/'in_illuminance_input').write_text('1500') + a.set_state('auto_brightness', 'on') + child = subprocess.Popen([binary(), '--source', 'iio']) + def stop(): + child.terminate() + child.wait(timeout=3) + self.addCleanup(stop) + + def serve(self): + case = self + class Handler(socketserver.StreamRequestHandler): + def handle(self): + request = self.rfile.readline().decode().strip() + case.requests.append(request) + if request == 'als-state': + reply = case.reply + else: + _, panel, new, old = request.split() + current = (case.panel/'brightness').read_text().strip() + reply = 'held' + if case.reply == 'lit' and panel == 'panel' and old == current and int(old) > 0: + case.set_raw(new) + reply = 'ok' + self.wfile.write((reply+'\n').encode()) + server = socketserver.UnixStreamServer(str(self.sock), Handler) + thread = threading.Thread(target=server.serve_forever, kwargs={'poll_interval': .02}) + thread.start() + self.addCleanup(server.server_close) + self.addCleanup(thread.join) + self.addCleanup(server.shutdown) + os.utime(self.sock) + + def status(self, predicate): + path = self.root/'omarchy-auto-brightness.json' + end = time.monotonic() + 5 + data = {} + while time.monotonic() < end: + if path.exists(): + data = json.loads(path.read_text()) + if predicate(data): + return data + time.sleep(.02) + self.fail(f'status deadline: {data}') def test_powerd_missing_or_dark_is_a_hold(self): - for reply in ('','dark'): - with patch.object(a,'power_request',return_value=reply): self.assertEqual(a.holds(),['powerd']) - with patch.object(a,'power_request',return_value='lit'): self.assertEqual(a.holds(),[]) + self.start() + self.status(lambda d: d['hold'] == ['powerd'] and d['lux'] is None) + self.reply = 'dark' + self.serve() + time.sleep(.1) + self.assertFalse(any(r.startswith('brightness ') for r in self.requests)) + self.reply = 'lit' + os.utime(self.sock) + self.status(lambda d: not d['hold'] and d['lux'] == 1500) def test_automatic_write_is_compare_and_set_through_powerd(self): - panel=a.Backlight('panel') - with patch.object(a,'power_request',return_value='ok') as request: - self.assertTrue(panel.write(600,expected=500)) - request.assert_called_once_with('brightness panel 600 500') - for raw in (0,501): - self.set_raw(raw) - with patch.object(a,'power_request') as request: - self.assertFalse(panel.write(600,expected=500)); request.assert_not_called() + self.start() + self.serve() + self.status(lambda d: d['moves'] >= 1) + writes = [r.split() for r in self.requests if r.startswith('brightness ')] + self.assertEqual(writes[0][1::2], ['panel', '500']) + for before, after in zip(writes, writes[1:]): + self.assertEqual(before[2], after[3]) + self.set_raw(0) + os.utime(self.sock) + self.status(lambda d: d['hold'] == ['backlight']) + self.assertEqual((self.panel/'brightness').read_text().strip(), '0') def test_hysteresis_and_manual_override(self): - panel=a.Backlight('panel'); self.conf['enabled']=True - daemon=a.Daemon(self.conf,type('Source',(),{'kind':'test'})(),panel,False,False) - daemon.last_written=500; self.set_raw(300); daemon.latest=1500 - with patch.object(a,'holds',return_value=[]), patch.object(panel,'write') as write: - daemon.tick(10.0) - self.assertGreater(daemon.override_until,10.0); write.assert_not_called() + self.start() + self.serve() + self.status(lambda d: d['moves'] > 0) + self.set_raw(300) + os.utime(self.sock) + self.status(lambda d: d['override_secs_left'] > 0) + self.assertEqual((self.panel/'brightness').read_text().strip(), '300') def test_ramp_is_a_smooth_perceptual_fade(self): - panel=a.Backlight('panel'); self.conf['enabled']=True - daemon=a.Daemon(self.conf,type('Source',(),{'kind':'test'})(),panel,False,False) - self.set_raw(100); daemon.goal_raw=800; daemon.start_ramp(100,0.0) - self.assertGreaterEqual(daemon.ramp_secs,a.RAMP_MIN_SECS); self.assertLessEqual(daemon.ramp_secs,a.RAMP_MAX_SECS) - written=[] - def fake_write(new,expected=None): - self.assertEqual(expected,int((self.panel/'brightness').read_text())); self.set_raw(new); written.append(new); return True - with patch.object(panel,'write',side_effect=fake_write): - t=0.0 - while daemon.ramping() and t<10: - daemon.step(int((self.panel/'brightness').read_text()),t); t+=a.RAMP_TICK - self.assertEqual(written[-1],800); self.assertFalse(daemon.ramping()) - self.assertEqual(written,sorted(written)) # monotonic, no overshoot - self.assertGreater(len(written),10) # a fade of many small steps, not a few jumps - p=[daemon.perceived(w) for w in [100]+written] - steps=[b-c for c,b in zip(p,p[1:])] - self.assertLess(max(steps),0.08) # no single step brighter than ~8% perceived - self.assertLess(steps[0],max(steps)) # eased in: starts gentler than the middle + send = replay(self, 'light') + seconds = float(send('ramp 1000 100 800')) + self.assertTrue(.3 <= seconds <= 3) + written = [int(send(f'step {i/30}')) for i in range(math.ceil(seconds*30)+1)] + self.assertEqual(written[-1], 800) + self.assertEqual(written, sorted(written)) + self.assertGreater(len(set(written)), 10) + p = [(v/1000)**(1/2.2) for v in written] + steps = [b-a for a,b in zip(p,p[1:])] + self.assertLess(max(steps), .08) + self.assertLess(steps[0], max(steps)) def test_the_package_stages_the_helper_and_the_session_starts_it(self): - install=(PROJECT/'desktop/install-tree').read_text() - self.assertIn('$config/auto-brightness usr/libexec/arch-ipad-auto-brightness 755',install) - self.assertIn('exec /usr/libexec/arch-ipad-auto-brightness',(PROJECT/'desktop/shell/bin/omarchy-auto-brightness').read_text()) - self.assertIn('/usr/libexec/arch-ipad-auto-brightness',(PROJECT/'desktop/shell/default/labwc/autostart').read_text()) - -if __name__=='__main__': unittest.main() + install = (PROJECT/'desktop/install-tree').read_text() + self.assertIn('$config/auto-brightness usr/libexec/arch-ipad-auto-brightness 755', install) + self.assertIn('exec /usr/libexec/arch-ipad-auto-brightness', (PROJECT/'desktop/shell/bin/omarchy-auto-brightness').read_text()) + self.assertIn('/usr/libexec/omarchy-session-helper', (PROJECT/'desktop/shell/default/labwc/autostart').read_text()) diff --git a/tests/test_keyboard_policy.py b/tests/test_keyboard_policy.py index f8a6fbaa..4d154b02 100644 --- a/tests/test_keyboard_policy.py +++ b/tests/test_keyboard_policy.py @@ -2,6 +2,7 @@ from importlib.util import module_from_spec, spec_from_loader from pathlib import Path import unittest +from session_replay import replay PROJECT = Path(__file__).resolve().parents[1] SCRIPT = PROJECT / 'desktop/shell/bin/omarchy-keyboard' @@ -34,23 +35,25 @@ def setUp(self): self.shown = False self.calls = [] - def show(): - self.shown = True - self.calls.append('show') + self.send = replay(self, 'keyboard') - def hide(): - self.shown = False - self.calls.append('hide') + def event(self, line): + action, hardware = self.send(f'{self.clock()} {int(self.shown)} {line}').split() + self.hardware = bool(int(hardware)) + if action != '-': + self.calls.append(action) + self.shown = action == 'show' - self.policy = load().Policy(show, hide, lambda: self.shown, now=self.clock) + def person(self, action): + self.event('person ' + action) def facts(self, *lines): for line in lines: - self.policy.fact(line) + self.event(line) def wait(self, seconds): self.clock.t += seconds - self.policy.tick() + self.event('tick') # Programs moving focus @@ -73,20 +76,20 @@ def test_a_panel_focusing_its_search_after_a_tap_elsewhere_does_not(self): def test_the_control_center_opening_over_a_typing_app_keeps_the_keyboard(self): self.facts('field on 2', 'press', TAP, 'show') # typing in foot - self.policy.person('hold') # the control center takes the keyboard + self.person('hold') # the control center takes the keyboard self.facts('field off') self.wait(1) self.assertEqual(self.calls, ['show']) - self.policy.person('release') # closed: the app's field comes back + self.person('release') # closed: the app's field comes back self.facts('field on 2') self.wait(1) self.assertEqual(self.calls, ['show']) def test_closing_the_control_center_with_no_field_back_puts_it_away(self): self.facts('field on 2', 'press', TAP, 'show') - self.policy.person('hold') + self.person('hold') self.facts('field off') - self.policy.person('release') + self.person('release') self.wait(1) self.assertEqual(self.calls, ['show', 'hide']) @@ -125,7 +128,7 @@ def test_a_version_1_field_coming_on_right_after_a_tap_opens_it(self): def test_a_window_opened_to_read_after_a_tap_does_not_open_it(self): # About: the menu tap starts a terminal whose text input comes on at once. self.facts('press', TAP) - self.policy.person('quiet') + self.person('quiet') self.facts('field on 1') self.assertEqual(self.calls, []) # A tap in that window still opens it. @@ -173,7 +176,7 @@ def test_the_app_can_close_it(self): def test_a_tap_after_the_person_put_it_away_opens_it_again(self): # Qt is not told of the swipe; the field asks hide-then-show to be heard. self.facts('field on 2', 'press', 'show') - self.policy.person('hide') + self.person('hide') self.shown = False # the swipe put it away self.calls.clear() self.wait(1) @@ -217,7 +220,7 @@ def test_hide_then_show_at_once_does_not_blink_an_open_keyboard(self): def test_one_the_person_opened_stays_when_the_field_goes(self): self.facts('field on 2') - self.policy.person('show') + self.person('show') self.facts('field off') self.wait(1) self.facts('hide') @@ -225,7 +228,7 @@ def test_one_the_person_opened_stays_when_the_field_goes(self): def test_one_the_person_put_away_stays_away_until_the_next_tap(self): self.facts('field on 2', 'press', 'show') - self.policy.person('hide') + self.person('hide') self.shown = False # the swipe put it away self.wait(1) self.facts('show', 'field off', 'field on 2') @@ -249,10 +252,10 @@ def test_a_connected_keyboard_alone_changes_nothing(self): def test_opening_it_by_hand_ends_physical_typing(self): self.facts('keyboards 1', 'field on 2', 'key') - self.policy.person('show') + self.person('show') self.facts('press', 'show') self.assertEqual(self.calls, ['show']) - self.assertFalse(self.policy.hardware) + self.assertFalse(self.hardware) def test_no_physical_keyboard_left_ends_physical_typing(self): self.facts('keyboards 1', 'field on 2', 'key', 'keyboards 0', 'press', 'show') diff --git a/tests/test_package.py b/tests/test_package.py index 237b676a..d2bb4ed4 100644 --- a/tests/test_package.py +++ b/tests/test_package.py @@ -353,7 +353,7 @@ def test_changed_files_links_modes_and_a_missing_install_step_fail(self): audit.verify_package_setup(self.ENTRIES, hashes) def test_the_compiled_helpers_are_of_the_roots_architecture(self): - self.assertEqual(set(audit.HELPERS), {'usr/libexec/omarchy-wtype', + self.assertEqual(set(audit.HELPERS), {'usr/libexec/omarchy-wtype', 'usr/libexec/omarchy-session-helper', 'usr/share/omarchy/trials/wvkbd-mobintl-v0.20-font18-special15-state'}) from release.architecture import check_elf check_elf(elf('aarch64'), 'aarch64') diff --git a/tests/test_rotate_output.py b/tests/test_rotate_output.py index ddb74428..0b661591 100644 --- a/tests/test_rotate_output.py +++ b/tests/test_rotate_output.py @@ -1,16 +1,17 @@ -"""desktop/configuration/rotate-output: iio-sensor-proxy orientations to output transforms.""" +"""Replay SensorProxy orientations, raw motion and labwc exit against the native helper.""" +import asyncio import os -import sys -import runpy from pathlib import Path -import shutil -import subprocess import tempfile -import threading import unittest -SCRIPT = Path(__file__).resolve().parents[1] / 'desktop/configuration/rotate-output' +from dbus_next import PropertyAccess +from dbus_next.aio import MessageBus +from dbus_next.service import ServiceInterface, dbus_property, method +from session_replay import binary, replay + +PROXY = 'net.hadess.SensorProxy' RANDR = '''#!/bin/sh if [ "$#" -eq 0 ]; then printf 'Unknown-1 "Apple panel"\\n Enabled: yes\\n' @@ -20,229 +21,263 @@ ''' -def monitor(events): - """A monitor-sensor stand-in: (delay before the line in seconds, line).""" - lines = ['#!/bin/sh', "echo ' Waiting for iio-sensor-proxy to appear'"] - for delay, line in events: - lines += [f'sleep {delay}', f"echo '{line}'"] - return '\n'.join(lines) + '\n' - - -BASH = shutil.which('bash') - - -def bash_major(): - out = subprocess.run([BASH, '-c', 'echo ${BASH_VERSINFO[0]}'], capture_output=True, text=True) - return int(out.stdout.strip() or 0) - - -class RotateOutput(unittest.TestCase): - def run_script(self, events, locked=False, extra_env=None, timeout=20): - with tempfile.TemporaryDirectory() as tmp: - root = Path(tmp) - bin_dir = root / 'bin' - bin_dir.mkdir() - body = events if isinstance(events, str) else monitor(events) - for name, body in (('monitor-sensor', body), ('wlr-randr', RANDR)): - (bin_dir / name).write_text(body) - (bin_dir / name).chmod(0o755) - config = root / 'config' - if locked: - (config / 'omarchy').mkdir(parents=True) - (config / 'omarchy/rotation-lock').touch() - log = root / 'randr.log' - env = {**os.environ, 'PATH': f'{bin_dir}:{os.environ["PATH"]}', - 'XDG_CONFIG_HOME': str(config), 'RANDR_LOG': str(log), 'ROTATE_SETTLE': '0.1', - 'ROTATE_COOLDOWN': '0', - **(extra_env or {})} - subprocess.run([sys.executable, str(SCRIPT)], env=env, check=True, timeout=timeout) - return log.read_text().splitlines() if log.exists() else [] - - def test_held_orientations_become_transforms_of_the_panel(self): - events = [(0, '=== Has accelerometer (orientation: normal)'), - (0.3, ' Accelerometer orientation changed: left-up'), - (0.3, ' Accelerometer orientation changed: bottom-up'), - (0.3, ' Accelerometer orientation changed: undefined'), - (0.3, ' Accelerometer orientation changed: right-up'), - (0.3, ' Accelerometer orientation changed: normal')] - self.assertEqual(self.run_script(events), [ - '--output Unknown-1 --transform normal', - '--output Unknown-1 --transform 90', - '--output Unknown-1 --transform 180', - '--output Unknown-1 --transform 270', - '--output Unknown-1 --transform normal', - ]) - - def test_passing_through_an_orientation_rotates_once(self): - events = [(0, '=== Has accelerometer (orientation: normal)'), - (0.3, ' Accelerometer orientation changed: left-up'), - (0.02, ' Accelerometer orientation changed: bottom-up'), - (0.3, ' Accelerometer orientation changed: bottom-up')] - self.assertEqual(self.run_script(events), [ - '--output Unknown-1 --transform normal', - '--output Unknown-1 --transform 180', - ]) - - def test_lock_holds_the_orientation(self): - events = [(0, '=== Has accelerometer (orientation: normal)'), - (0.3, ' Accelerometer orientation changed: left-up')] - self.assertEqual(self.run_script(events, locked=True), []) - - - def test_ends_with_the_compositor(self): - # monitor-sensor never ends by itself; the helper must stop it once - # the compositor is gone instead of outliving the session - sensor = ("#!/bin/sh\necho '=== Has accelerometer (orientation: normal)'\n" - "exec sleep 60\n") - compositor = subprocess.Popen(['sleep', '1']) - # reap it as soon as it exits, as the session manager reaps labwc - reaper = threading.Thread(target=compositor.wait) - reaper.start() - try: - lines = self.run_script(sensor, extra_env={'LABWC_PID': str(compositor.pid)}, - timeout=10) - finally: - reaper.join() - self.assertEqual(lines, ['--output Unknown-1 --transform normal']) - - def test_exits_cleanly_when_board_has_no_accelerometer(self): - # On boards without an accelerometer (e.g. J96), exit instead of sitting - # in memory polling forever. - sensor = ("#!/bin/sh\necho ' Waiting for iio-sensor-proxy to appear'\n" - "echo '=== No accelerometer'\nexec sleep 60\n") - compositor = subprocess.Popen(['sleep', '15']) - try: - lines = self.run_script(sensor, extra_env={'LABWC_PID': str(compositor.pid), - 'ROTATE_ACCEL': '/nonexistent'}, - timeout=5) - self.assertEqual(lines, []) - finally: - compositor.terminate() - compositor.wait() - - def test_exits_cleanly_when_proxy_never_appears(self): - # When iio-sensor-proxy is not running on a board with no IIO accel, - # monitor-sensor only prints 'Waiting for iio-sensor-proxy to appear'. - sensor = ("#!/bin/sh\necho ' Waiting for iio-sensor-proxy to appear'\n" - "exec sleep 60\n") - compositor = subprocess.Popen(['sleep', '15']) - try: - lines = self.run_script(sensor, extra_env={'LABWC_PID': str(compositor.pid), - 'ROTATE_ACCEL': '/nonexistent', - 'ROTATE_DISCOVERY_TIMEOUT': '0.3'}, - timeout=5) - self.assertEqual(lines, []) - finally: - compositor.terminate() - compositor.wait() - - def test_sensor_reader_ending_inside_a_session_is_restarted(self): - # At login iio-sensor-proxy may not answer yet: the first reader ends - # at once. Rotation must come back without a new login. - sensor = ('#!/bin/sh\nif [ ! -e "$RANDR_LOG.started" ]; then : > "$RANDR_LOG.started"; exit 1; fi\n' - "echo '=== Has accelerometer (orientation: left-up)'\nexec sleep 60\n") - compositor = subprocess.Popen(['sleep', '4']) - reaper = threading.Thread(target=compositor.wait) - reaper.start() - try: - lines = self.run_script(sensor, extra_env={'LABWC_PID': str(compositor.pid)}, - timeout=15) - finally: - reaper.join() - self.assertEqual(lines, ['--output Unknown-1 --transform 90']) +class Sensor(ServiceInterface): + def __init__(self): + super().__init__(PROXY) + self.light = self.light_claimed = False + self.light_reads = 0 + self.available = True + self.pose = 'undefined' + self.claimed = False + @dbus_property(access=PropertyAccess.READ) + def HasAccelerometer(self) -> 'b': + return self.available -class RotationPolicy(unittest.TestCase): - def test_monitor_sensor_tilt_suffix_is_not_part_of_orientation(self): - parse = runpy.run_path(str(SCRIPT))['orientation'] - self.assertEqual(parse('=== Has accelerometer (orientation: normal, tilt: face-up)'), 'normal') - self.assertEqual(parse('Accelerometer orientation changed: left-up, tilt: upright'), 'left-up') - self.assertEqual(parse('Accelerometer orientation changed: undefined'), 'undefined') - self.assertIsNone(parse('Accelerometer tilt changed: face-up')) + @dbus_property(access=PropertyAccess.READ) + def HasAmbientLight(self) -> 'b': + return self.light + + @dbus_property(access=PropertyAccess.READ) + def LightLevel(self) -> 'd': + self.light_reads += 1 + return 80. + + @dbus_property(access=PropertyAccess.READ) + def LightLevelUnit(self) -> 's': + return 'lux' + + @method() + def ClaimLight(self): + self.light_claimed = True + + @method() + def ReleaseLight(self): + self.light_claimed = False + + @dbus_property(access=PropertyAccess.READ) + def AccelerometerOrientation(self) -> 's': + return self.pose + + @method() + def ClaimAccelerometer(self): + self.claimed = True + + @method() + def ReleaseAccelerometer(self): + self.claimed = False + + def turn(self, pose): + self.pose = pose + self.emit_properties_changed({'AccelerometerOrientation': pose}) + + +class RotateOutput(unittest.IsolatedAsyncioTestCase): + async def asyncSetUp(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.root = Path(tmp.name) + self.log = self.root/'randr.log' + self.lock = self.root/'config/omarchy/rotation-lock' + self.lock.parent.mkdir(parents=True) + randr = self.root/'wlr-randr' + randr.write_text(RANDR) + randr.chmod(0o755) + self.daemon = await asyncio.create_subprocess_exec( + 'dbus-daemon', '--session', '--nofork', '--print-address=1', stdout=asyncio.subprocess.PIPE) + address = (await self.daemon.stdout.readline()).decode().strip() + self.bus = await MessageBus(bus_address=address).connect() + self.sensor = Sensor() + self.bus.export('/net/hadess/SensorProxy', self.sensor) + self.compositor = await asyncio.create_subprocess_exec('sleep', '30') + self.env = {**os.environ, 'PATH': f'{self.root}:{os.environ["PATH"]}', + 'XDG_CONFIG_HOME': str(self.root/'config'), 'XDG_STATE_HOME': str(self.root/'state'), + 'XDG_RUNTIME_DIR': str(self.root), 'RANDR_LOG': str(self.log), + 'DBUS_SYSTEM_BUS_ADDRESS': address, 'LABWC_PID': str(self.compositor.pid), + 'ROTATE_ACCEL': '/nonexistent', 'ROTATE_SETTLE': '0.1', 'ROTATE_COOLDOWN': '0'} + self.child = None + + async def asyncTearDown(self): + for p in (self.child, self.compositor): + if p and p.returncode is None: + p.terminate() + await asyncio.wait_for(p.wait(), 3) + self.bus.disconnect() + await self.bus.wait_for_disconnect() + self.daemon.terminate() + await self.daemon.wait() + + async def until(self, condition): + async with asyncio.timeout(4): + while not condition(): + await asyncio.sleep(.02) - def policy(self): - return runpy.run_path(str(SCRIPT))['Orientation']() + def lines(self): + return self.log.read_text().splitlines() if self.log.exists() else [] + + async def start(self, owner=True): + if owner: + await self.bus.request_name(PROXY) + self.child = await asyncio.create_subprocess_exec(binary(), env=self.env) + await self.until(lambda: (self.root/'omarchy-keyboard.sock').exists()) + if owner and self.sensor.available: + await self.until(lambda: self.sensor.claimed) + + async def test_held_orientations_become_transforms_of_the_panel(self): + await self.start() + for value in ('normal', 'left-up', 'bottom-up', 'undefined', 'right-up', 'normal'): + self.sensor.turn(value) + await asyncio.sleep(.3) + self.assertEqual(self.lines(), [f'--output Unknown-1 --transform {value}' + for value in ('normal','90','180','270','normal')]) + + async def test_passing_through_an_orientation_rotates_once(self): + self.sensor.pose = 'normal' + await self.start() + await self.until(lambda: len(self.lines()) == 1) + self.sensor.turn('left-up') + await asyncio.sleep(.02) + self.sensor.turn('bottom-up') + await asyncio.sleep(.3) + self.sensor.turn('bottom-up') + await asyncio.sleep(.2) + self.assertEqual(self.lines(), ['--output Unknown-1 --transform normal', '--output Unknown-1 --transform 180']) + + async def test_lock_holds_the_orientation(self): + self.lock.touch() + self.sensor.pose = 'normal' + await self.start() + self.sensor.turn('left-up') + await asyncio.sleep(.3) + self.assertEqual(self.lines(), []) + self.lock.unlink() + await self.until(lambda: self.lines()) + self.assertEqual(self.lines(), ['--output Unknown-1 --transform 90']) + + async def test_ends_with_the_compositor(self): + self.sensor.pose = 'normal' + await self.start() + await self.until(lambda: self.lines()) + self.compositor.terminate() + await asyncio.wait_for(self.child.wait(), 3) + self.assertFalse((self.root/'omarchy-keyboard.sock').exists()) + self.assertFalse(self.sensor.claimed) + + async def test_no_accelerometer_leaves_other_policies_available(self): + self.sensor.available = False + await self.start() + await asyncio.sleep(.2) + self.assertFalse(self.sensor.claimed) + self.assertIsNone(self.child.returncode) + self.assertEqual(self.lines(), []) + + async def test_proxy_arriving_after_login_claims_the_accelerometer(self): + await self.start(owner=False) + await asyncio.sleep(.2) + self.assertEqual(self.lines(), []) + self.sensor.pose = 'normal' + await self.bus.request_name(PROXY) + await self.until(lambda: self.lines()) + self.assertEqual(self.lines(), ['--output Unknown-1 --transform normal']) + + async def test_sensor_reader_ending_inside_a_session_is_restarted(self): + panel = self.root/'backlight/panel' + panel.mkdir(parents=True) + (panel/'brightness').write_text('58') + (panel/'max_brightness').write_text('100') + (self.lock.parent/'als-brightness.conf').write_text('enabled=on') + power = self.root/'power.sock' + self.env.update(IPAD_ALS_BACKLIGHT_ROOT=str(panel.parent), IPAD_ALS_POWER_SOCKET=str(power)) + lit = True + + async def answer(reader, writer): + request = await reader.readline() + self.assertEqual(request, b'als-state\n') + writer.write(b'lit\n' if lit else b'dark\n') + await writer.drain() + writer.close() + + server = await asyncio.start_unix_server(answer, path=power) + self.addCleanup(server.close) + self.sensor.light = True + await self.start() + await self.until(lambda: self.sensor.light_claimed) + lit = False + os.utime(power) + await self.until(lambda: not self.sensor.light_claimed) + reads = self.sensor.light_reads + self.sensor.emit_properties_changed({}, ['LightLevel']) + await asyncio.sleep(.2) + self.assertEqual(self.sensor.light_reads, reads) + lit = True + os.utime(power) + await self.until(lambda: self.sensor.light_claimed) + await self.bus.release_name(PROXY) + self.sensor.claimed = self.sensor.light_claimed = False + self.sensor.pose = 'left-up' + await self.bus.request_name(PROXY) + await self.until(lambda: self.lines()) + self.assertTrue(self.sensor.claimed) + self.assertTrue(self.sensor.light_claimed) + self.assertEqual(self.lines(), ['--output Unknown-1 --transform 90']) + + +class RotationPolicy(unittest.TestCase): + def setUp(self): + self.send = replay(self, 'rotation') def test_repeated_messages_do_not_restart_stability_window(self): - p = self.policy() - p.observe('left-up', 0) - p.observe('left-up', .3) - self.assertEqual(p.ready(.41), 'left-up') + self.send('observe 0 left-up') + self.send('observe .3 left-up') + self.assertEqual(self.send('ready .41 0 0 -'), 'left-up') def test_cooldown_stops_flip_flopping(self): - p = self.policy() - p.observe('normal', 0) - p.committed('normal', 1) - p.observe('left-up', 1.1) - self.assertIsNone(p.ready(1.6)) - self.assertEqual(p.ready(1.8), 'left-up') + self.send('observe 0 normal') + self.send('commit 1 normal') + self.send('observe 1.1 left-up') + self.assertEqual(self.send('ready 1.6 0 0 -'), '-') + self.assertEqual(self.send('ready 1.8 0 0 -'), 'left-up') def test_undefined_cancels_and_unlock_uses_current_reading(self): - p = self.policy() - p.observe('left-up', 0) - p.observe('undefined', .5) - self.assertIsNone(p.ready(3)) - p.observe('right-up', 4) - self.assertIsNone(p.ready(5, locked=True)) - self.assertEqual(p.ready(6, locked=False), 'right-up') + self.send('observe 0 left-up') + self.send('observe .5 undefined') + self.assertEqual(self.send('ready 3 0 0 -'), '-') + self.send('observe 4 right-up') + self.assertEqual(self.send('ready 5 1 0 -'), '-') + self.assertEqual(self.send('ready 6 0 0 -'), 'right-up') def test_still_turning_holds_a_settled_reading_for_a_bounded_time(self): - module = type("M", (), runpy.run_path(str(SCRIPT))) - state = module.Orientation(settle=0.4, cooldown=0, hold=0.6) - state.observe('left-up', 0.0) - self.assertEqual(state.ready(0.45, turning=False), 'left-up') - self.assertIsNone(state.ready(0.45, turning=True)) - state.observe('bottom-up', 0.5) - self.assertIsNone(state.ready(0.6, turning=True)) - self.assertEqual(state.ready(0.95, turning=False), 'bottom-up') - # a tablet that never stops moving still rotates - self.assertEqual(state.ready(1.6, turning=True), 'bottom-up') + self.send('observe 0 left-up') + self.assertEqual(self.send('ready .45 0 0 -'), 'left-up') + self.assertEqual(self.send('ready .45 0 1 -'), '-') + self.send('observe .5 bottom-up') + self.assertEqual(self.send('ready .6 0 1 -'), '-') + self.assertEqual(self.send('ready .95 0 0 -'), 'bottom-up') + self.assertEqual(self.send('ready 1.6 0 1 -'), 'bottom-up') def test_report_lagging_behind_gravity_is_waited_for(self): - # J71b, 2026-11-10: half turn over the side, gravity at the final - # orientation at 0.3 s, the proxy still said right-up until 0.9 s later. - module = type("M", (), runpy.run_path(str(SCRIPT))) - state = module.Orientation(settle=0.4, cooldown=0, hold=0.6, lag=1.2) - state.observe('right-up', 0.0) - self.assertIsNone(state.ready(0.5, facing='normal')) - self.assertEqual(state.ready(0.5, facing='right-up'), 'right-up') - self.assertEqual(state.ready(0.5, facing=None), 'right-up') - self.assertEqual(state.ready(1.7, facing='normal'), 'right-up') - state.observe('normal', 1.2) - self.assertEqual(state.ready(1.65, facing='normal'), 'normal') + self.send('observe 0 right-up') + self.assertEqual(self.send('ready .5 0 0 normal'), '-') + for facing in ('right-up', '-'): + self.assertEqual(self.send(f'ready .5 0 0 {facing}'), 'right-up') + self.assertEqual(self.send('ready 1.7 0 0 normal'), 'right-up') + self.send('observe 1.2 normal') + self.assertEqual(self.send('ready 1.65 0 0 normal'), 'normal') def test_facing_follows_the_mount_matrix_and_gives_up_when_never_agreeing(self): - module = type("M", (), runpy.run_path(str(SCRIPT))) - motion = module.Turning('/nonexistent') - motion.matrix = [[-1.0, 0.0, 0.0], [0.0, -1.0, 0.0]] # J71b - for raw, name in (((2000, 65000, 3000), 'normal'), ((1000, -66000, 600), 'bottom-up'), - ((57000, -2000, 9000), 'right-up'), ((-60000, 900, 9000), 'left-up')): - motion.read = lambda raw=raw: raw - motion.sample(0.0) - self.assertEqual(motion.trusted_facing(), name) + self.send('matrix -1,0,0;0,-1,0;0,0,1') + for raw, name in [('2000 65000 3000','normal'),('1000 -66000 600','bottom-up'), + ('57000 -2000 9000','right-up'),('-60000 900 9000','left-up')]: + self.send(f'sample 0 {raw}') + self.assertEqual(self.send('facing'), name) for _ in range(3): - motion.judged('normal') - self.assertIsNone(motion.trusted_facing()) + self.send('judged normal') + self.assertEqual(self.send('facing'), '-') def test_turning_is_read_from_the_gravity_angle(self): - module = type("M", (), runpy.run_path(str(SCRIPT))) - motion = module.Turning('/nonexistent') - readings = iter([(65000, 0, 3000), (60000, 25000, 3000), (46000, 46000, 3000)]) - motion.read = lambda: next(readings) - for now in (0.0, 0.1, 0.2): - motion.sample(now) - self.assertTrue(motion.turning()) - still = module.Turning('/nonexistent') - still.read = lambda: (65000, 200, 3000) - for now in (0.0, 0.1, 0.2): - still.sample(now) - self.assertFalse(still.turning()) - flat = module.Turning('/nonexistent') - flat.read = lambda: (5000, 1300, 65900) - for now in (0.0, 0.1, 0.2): - flat.sample(now) - self.assertFalse(flat.turning()) - - -if __name__ == '__main__': - unittest.main() + for vectors, result in [(['65000 0 3000','60000 25000 3000','46000 46000 3000'], '1'), + (['65000 200 3000']*3, '0'), (['5000 1300 65900']*3, '0')]: + send = replay(self, 'rotation') + for t, raw in zip((0, .1, .2), vectors): + send(f'sample {t} {raw}') + self.assertEqual(send('turning'), result) diff --git a/tools/measure-session-helpers b/tools/measure-session-helpers new file mode 100755 index 00000000..ad400798 --- /dev/null +++ b/tools/measure-session-helpers @@ -0,0 +1,49 @@ +#!/usr/bin/env python3 +"""Measure the old three policy processes or the native owner for one idle minute.""" +import os +from pathlib import Path +import sys +import time + +mode, = sys.argv[1:] +if mode not in ('old', 'native'): + sys.exit('usage: measure-session-helpers old|native') + +targets = [] +for path in Path('/proc').glob('[0-9]*'): + try: + args = [os.fsdecode(s) for s in (path/'cmdline').read_bytes().split(b'\0') if s] + if mode == 'native': + match = (path/'exe').resolve() == Path('/usr/libexec/omarchy-session-helper') + else: + match = any(Path(s).name in ('arch-ipad-auto-brightness', 'arch-ipad-rotate-output') + or (Path(s).name == 'omarchy-keyboard' and args[i+1:i+2] == ['listen']) + for i, s in enumerate(args)) + if match: + targets.append(path) + except (OSError, ValueError): + continue +if len(targets) != (3 if mode == 'old' else 1): + sys.exit(f'{mode}: unexpected policy PIDs {[p.name for p in targets]}; check the session') + +def ticks(path): + stat = (path/'stat').read_text().rsplit(')', 1)[1].split() + return int(stat[19]), int(stat[11]) + int(stat[12]) + +start = {p: ticks(p) for p in targets} +then = time.monotonic() +time.sleep(60) +elapsed = time.monotonic() - then +rss = pss = cpu = 0 +for p, (birth, before) in start.items(): + current, after = ticks(p) + if current != birth: + sys.exit(f'PID {p.name} changed during sample') + memory = {s.split(':')[0]: int(s.split()[1]) for s in (p/'smaps_rollup').read_text().splitlines() + if s.startswith(('Rss:', 'Pss:'))} + print(f'pid={p.name} rss={memory["Rss"]} KiB pss={memory["Pss"]} KiB') + rss += memory['Rss'] + pss += memory['Pss'] + cpu += after - before +print(f'{mode} sum RSS={rss} KiB PSS={pss} KiB CPU={100*cpu/os.sysconf("SC_CLK_TCK")/elapsed:.3f}% ' + f'of one core over {elapsed:.1f} s')