diff --git a/CHANGELOG.md b/CHANGELOG.md index b6b710f1..78ed2788 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -66,6 +66,9 @@ release is checked here and released on by hand. - The on-screen keyboard releases its shared-memory drawing buffers while hidden, freeing about 9 MiB of RAM at idle (tcballard). +- The shell stops waking the tablet several times a second to check the + battery and the rotation lock: both now update when they change (grierj). + ## [0.4.10] - 2026-12-05 Built on orchard 0.3.24. diff --git a/desktop/shell/bin/omarchy-battery-status b/desktop/shell/bin/omarchy-battery-status index 11c90a16..dcc83eab 100644 --- a/desktop/shell/bin/omarchy-battery-status +++ b/desktop/shell/bin/omarchy-battery-status @@ -14,9 +14,9 @@ for candidate in "$base"/*; do 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" +read -r percentage < "$battery/capacity" || exit 0 +[[ $percentage =~ ^[0-9]{1,3}$ && 10#$percentage -le 100 ]] || exit 0 +printf 'percentage\t%d%%\n' $(( 10#$percentage )) external=unknown for candidate in "$base"/*; do @@ -31,24 +31,30 @@ done 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]{1,15}$ && 10#$full -gt 0 ]]; then + tenths=$(( (10#$full + 50000) / 100000 )) + printf 'size\t%d.%dWh\n' $(( tenths / 10 )) $(( tenths % 10 )) elif [[ -r $battery/charge_full ]] && read -r full < "$battery/charge_full" && - [[ $full =~ ^[0-9]+$ && $full -gt 0 ]]; then + [[ $full =~ ^[0-9]{1,15}$ && 10#$full -gt 0 ]]; then # Charge-reporting gauges (the phones' bq27545) have no energy_full. Show the # measured mAh; converting to Wh would need a nominal voltage we do not measure. - awk -v uah="$full" 'BEGIN { printf "size\t%.0fmAh\n", uah / 1000 }' + printf 'size\t%dmAh\n' $(( (10#$full + 500) / 1000 )) 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 }' -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 }' +if [[ -r $battery/power_now ]] && read -r microwatts < "$battery/power_now"; then + if [[ $microwatts =~ ^-?[0-9]{1,15}$ ]]; then + abs_u=${microwatts#-} + tenths=$(( (10#$abs_u + 50000) / 100000 )) + printf 'rate\t%d.%dW\n' $(( tenths / 10 )) $(( tenths % 10 )) + fi +elif [[ -r $battery/current_now && -r $battery/voltage_now ]] && + read -r microamps < "$battery/current_now" && + read -r microvolts < "$battery/voltage_now"; then + if [[ $microamps =~ ^-?[0-9]{1,9}$ && $microvolts =~ ^[0-9]{1,9}$ ]]; then + abs_i=${microamps#-} + tenths=$(( (10#$abs_i * 10#$microvolts + 50000000000) / 100000000000 )) + printf 'rate\t%d.%dW\n' $(( tenths / 10 )) $(( tenths % 10 )) fi fi diff --git a/desktop/shell/shell/Commons/BatteryStatus.qml b/desktop/shell/shell/Commons/BatteryStatus.qml new file mode 100644 index 00000000..65b843f3 --- /dev/null +++ b/desktop/shell/shell/Commons/BatteryStatus.qml @@ -0,0 +1,67 @@ +pragma Singleton +import QtQuick +import Quickshell +import Quickshell.Io +import Quickshell.Services.UPower +import "../plugins/panels/power/Model.js" as Model + +// One shared omarchy-battery-status reader for the bar, the lock screen, the +// control center and the power panel. Refreshes immediately on UPower source +// or battery changes and on demand when a panel opens; a slow fallback timer +// keeps discovery independent of UPower without polling every second at idle. +Singleton { + id: root + + property var batteryInfo: ({}) + property bool refreshPending: false + + function refresh() { + // A read already running may have sampled before the event this refresh is + // for, so coalesce one follow-up run once it exits. + if (batteryProc.running) { + refreshPending = true + return + } + refreshPending = false + batteryProc.running = true + } + + function updateKeyValue(raw) { + var next = Model.parseKeyValue(raw) + // Keep last known good data if a refresh briefly returns nothing — happens + // around AC plug/unplug events. Avoids the section collapsing mid-transition. + if (Object.keys(next).length > 0) batteryInfo = next + else batteryInfo = Object.assign({}, batteryInfo, { external_power: "unknown" }) + } + + Process { + id: batteryProc + command: ["omarchy-battery-status", "--shell"] + stdout: StdioCollector { waitForEnd: true; onStreamFinished: root.updateKeyValue(text) } + onExited: { + // Deferred: the process still reports running while signalling exit. + if (root.refreshPending) Qt.callLater(root.refresh) + } + } + + Connections { + target: UPower + function onOnBatteryChanged() { root.refresh() } + } + + Connections { + target: UPower.displayDevice + ignoreUnknownSignals: true + function onPercentageChanged() { root.refresh() } + function onStateChanged() { root.refresh() } + function onIsPresentChanged() { root.refresh() } + } + + Timer { + interval: 30000 + running: true + repeat: true + triggeredOnStart: true + onTriggered: root.refresh() + } +} diff --git a/desktop/shell/shell/Commons/RotationLockState.qml b/desktop/shell/shell/Commons/RotationLockState.qml new file mode 100644 index 00000000..4dbff531 --- /dev/null +++ b/desktop/shell/shell/Commons/RotationLockState.qml @@ -0,0 +1,102 @@ +pragma Singleton +import QtQuick +import Quickshell +import Quickshell.Io + +// One shared rotation-lock and accelerometer probe for the bar, lock screen, +// control center and Display settings. Watches the config directory (and its +// parent so a moved or recreated directory re-arms the watch) so creating or +// removing the lock file updates immediately with no polling timer. +Singleton { + id: root + + readonly property string configHome: Quickshell.env("XDG_CONFIG_HOME") || (Quickshell.env("HOME") + "/.config") + readonly property string configDir: configHome + "/omarchy" + readonly property string lockPath: configDir + "/rotation-lock" + + property bool locked: false + // Until the proxy has answered, assume a sensor: nothing greys out at start. + property bool sensor: true + property bool activeTarget: false + property bool hasPendingToggle: false + property bool pendingTarget: false + + function reload() { + parentDirWatcher.reload() + dirWatcher.reload() + file.reload() + } + + function toggle() { + var base = toggleProc.running ? (hasPendingToggle ? pendingTarget : activeTarget) : locked + setLocked(!base) + } + + function setLocked(want) { + var next = !!want + if (toggleProc.running) { + hasPendingToggle = true + pendingTarget = next + return + } + activeTarget = next + toggleProc.command = ["omarchy-rotation-lock", next ? "on" : "off"] + toggleProc.running = true + } + + Process { + id: toggleProc + onExited: { + if (root.hasPendingToggle) { + var next = root.pendingTarget + root.hasPendingToggle = false + Qt.callLater(function() { root.setLocked(next) }) + return + } + root.reload() + } + } + + Process { + id: probe + command: ["busctl", "get-property", "net.hadess.SensorProxy", "/net/hadess/SensorProxy", + "net.hadess.SensorProxy", "HasAccelerometer"] + stdout: StdioCollector { id: probeOut } + onExited: function(exitCode) { + root.sensor = exitCode === 0 && probeOut.text.trim() === "b true" + } + } + + Component.onCompleted: probe.running = true + + // The proxy may still be starting when the shell does: ask once more. + Timer { + interval: 10000 + running: true + onTriggered: if (!root.sensor) probe.running = true + } + + FileView { + id: parentDirWatcher + path: root.configHome + watchChanges: true + printErrors: false + onFileChanged: root.reload() + } + + FileView { + id: dirWatcher + path: root.configDir + watchChanges: true + printErrors: false + onFileChanged: root.reload() + } + + FileView { + id: file + path: root.lockPath + printErrors: false + onLoaded: root.locked = true + onLoadFailed: root.locked = false + } +} diff --git a/desktop/shell/shell/Commons/qmldir b/desktop/shell/shell/Commons/qmldir index 24f4db12..b4fe4713 100644 --- a/desktop/shell/shell/Commons/qmldir +++ b/desktop/shell/shell/Commons/qmldir @@ -1,11 +1,13 @@ 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 singleton InputDevices 1.0 InputDevices.qml singleton IpcRegistry 1.0 IpcRegistry.qml singleton InputMethodState 1.0 InputMethodState.qml +singleton RotationLockState 1.0 RotationLockState.qml singleton Style 1.0 Style.qml singleton TimeZone 1.0 TimeZone.qml singleton TimeFormat 1.0 TimeFormat.qml diff --git a/desktop/shell/shell/controlcenter/ControlCenter.qml b/desktop/shell/shell/controlcenter/ControlCenter.qml index 07cd097e..edbc1e08 100644 --- a/desktop/shell/shell/controlcenter/ControlCenter.qml +++ b/desktop/shell/shell/controlcenter/ControlCenter.qml @@ -258,7 +258,7 @@ Item { if (UntypedInput.active) { if (UntypedInput.known) UntypedInput.setMuted(!UntypedInput.muted) } else if (source && source.audio) source.audio.muted = !source.audio.muted } - function toggleRotation() { run([omarchy("omarchy-rotation-lock"), rotation.locked ? "off" : "on"]); rotation.locked = !rotation.locked } + function toggleRotation() { rotation.toggle() } function toggleAwake() { if (idleService) idleService.setIdleEnabled(root.stayAwake) } function showKeyboard() { root.close(); run([omarchy("omarchy-keyboard"), "toggle"]) } function setVolume(value) { @@ -385,6 +385,7 @@ Item { // ----------------------------------------------------------- lifecycle function prepare() { + battery.refresh() if (!brightnessRead.running) brightnessRead.running = true if (!autoRead.running) autoRead.running = true root.focusKey = "" diff --git a/desktop/shell/shell/plugins/panels/power/Status.qml b/desktop/shell/shell/plugins/panels/power/Status.qml index d668d8d8..6a0f0273 100644 --- a/desktop/shell/shell/plugins/panels/power/Status.qml +++ b/desktop/shell/shell/plugins/panels/power/Status.qml @@ -1,19 +1,16 @@ import QtQuick -import Quickshell -import Quickshell.Io import Quickshell.Services.UPower +import qs.Commons import "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. +// Backed by the shared BatteryStatus singleton so every view reuses one reader. Item { id: root 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. - property var batteryInfo: ({}) + readonly property var batteryInfo: BatteryStatus.batteryInfo readonly property bool externalPower: batteryInfo.external_power === "connected" readonly property var batteryDevice: { var device = UPower.displayDevice @@ -40,28 +37,6 @@ Item { } function refresh() { - if (!batteryProc.running) batteryProc.running = true - } - - function updateKeyValue(raw) { - var next = Model.parseKeyValue(raw) - // Keep last known good data if a refresh briefly returns nothing — happens - // around AC plug/unplug events. Avoids the section collapsing mid-transition. - if (Object.keys(next).length > 0) batteryInfo = next - else batteryInfo = Object.assign({}, batteryInfo, { external_power: "unknown" }) - } - - Process { - id: batteryProc - command: ["omarchy-battery-status", "--shell"] - stdout: StdioCollector { waitForEnd: true; onStreamFinished: root.updateKeyValue(text) } - } - - Timer { - interval: 1000 - running: true - repeat: true - triggeredOnStart: true - onTriggered: root.refresh() + BatteryStatus.refresh() } } diff --git a/desktop/shell/shell/plugins/status/RotationLock.qml b/desktop/shell/shell/plugins/status/RotationLock.qml index 776eaf75..01cf2037 100644 --- a/desktop/shell/shell/plugins/status/RotationLock.qml +++ b/desktop/shell/shell/plugins/status/RotationLock.qml @@ -1,46 +1,14 @@ import QtQuick -import Quickshell -import Quickshell.Io +import qs.Commons -// Whether rotation is locked: omarchy-rotation-lock's file, which only exists -// while it is. Read every two seconds, as a missing file cannot be watched. -// And whether there is anything to lock: iio-sensor-proxy's accelerometer, -// which the rotation daemon follows. Without one the lock is unavailable. +// Whether rotation is locked and whether an accelerometer is present. +// Backed by the shared RotationLockState singleton so every view reuses one +// directory watcher and one SensorProxy probe with no polling timer. Item { id: root visible: false - property bool locked: false - // Until the proxy has answered, assume a sensor: nothing greys out at start. - property bool sensor: true - - Process { - id: probe - command: ["busctl", "get-property", "net.hadess.SensorProxy", "/net/hadess/SensorProxy", - "net.hadess.SensorProxy", "HasAccelerometer"] - stdout: StdioCollector { id: probeOut } - onExited: function(exitCode) { - root.sensor = exitCode === 0 && probeOut.text.trim() === "b true" - } - } - Component.onCompleted: probe.running = true - // The proxy may still be starting when the shell does: ask once more. - Timer { - interval: 10000 - running: true - onTriggered: if (!root.sensor) probe.running = true - } - - FileView { - id: file - path: (Quickshell.env("XDG_CONFIG_HOME") || (Quickshell.env("HOME") + "/.config")) + "/omarchy/rotation-lock" - printErrors: false - onLoaded: root.locked = true - onLoadFailed: root.locked = false - } - Timer { - interval: 2000 - running: true - repeat: true - onTriggered: file.reload() - } + readonly property bool locked: RotationLockState.locked + readonly property bool sensor: RotationLockState.sensor + function setLocked(want) { RotationLockState.setLocked(want) } + function toggle() { RotationLockState.toggle() } } diff --git a/desktop/shell/shell/settings/DisplayPage.qml b/desktop/shell/shell/settings/DisplayPage.qml index 235642d2..95fcc59e 100644 --- a/desktop/shell/shell/settings/DisplayPage.qml +++ b/desktop/shell/shell/settings/DisplayPage.qml @@ -110,10 +110,7 @@ Item { usable: rotation.sensor isSwitch: true switchOn: rotation.locked - onActivated: { - Quickshell.execDetached(["omarchy-rotation-lock", rotation.locked ? "off" : "on"]) - rotation.locked = !rotation.locked - } + onActivated: rotation.toggle() } } } diff --git a/tests/test_idle_wakeups.py b/tests/test_idle_wakeups.py new file mode 100644 index 00000000..6fa300d9 --- /dev/null +++ b/tests/test_idle_wakeups.py @@ -0,0 +1,171 @@ +"""Idle-power and wakeup discipline for the shell's battery and rotation-lock status.""" + +from pathlib import Path +import subprocess +import tempfile +import unittest + +PROJECT = Path(__file__).resolve().parents[1] + + +class BatteryStatusScriptTests(unittest.TestCase): + SCRIPT = PROJECT / 'desktop/shell/bin/omarchy-battery-status' + + def run_script(self, supplies): + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + for name, files in supplies.items(): + d = base / name + d.mkdir() + for key, value in files.items(): + (d / key).write_text(value) + # Run with an empty PATH so any external fork (awk, etc.) fails. + env = {'PATH': '', 'OMARCHY_POWER_SUPPLY_PATH': str(base)} + res = subprocess.run(['/bin/bash', str(self.SCRIPT), '--shell'], + capture_output=True, text=True, env=env, check=True) + return dict(line.split('\t', 1) for line in res.stdout.splitlines() if '\t' in line) + + def test_pure_bash_computes_size_and_rate_from_current_and_voltage(self): + out = self.run_script({ + 'battery': { + 'type': 'Battery\n', + 'present': '1\n', + 'capacity': '36\n', + 'energy_full': '30450000\n', + 'cycle_count': '1110\n', + 'current_now': '-195000\n', + 'voltage_now': '3769000\n', + }, + 'lightning': { + 'type': 'USB\n', + 'online': '1\n', + }, + }) + self.assertEqual(out['percentage'], '36%') + self.assertEqual(out['external_power'], 'connected') + self.assertEqual(out['size'], '30.5Wh') + self.assertEqual(out['cycles'], '1110') + # 195000 * 3769000 / 1e12 = 0.734955 -> 0.7W + self.assertEqual(out['rate'], '0.7W') + + def test_handles_leading_zeros_empty_optional_files_and_overflow_guards(self): + out = self.run_script({ + 'BAT0': { + 'type': 'Battery\n', + 'capacity': '08\n', + 'energy_full': '99999999999999999999\n', # out-of-range: ignored + 'power_now': '', # empty optional file: must not abort under set -e + }, + 'AC': { + 'type': 'Mains\n', + 'online': '0\n', + }, + }) + self.assertEqual(out['percentage'], '8%') + self.assertEqual(out['external_power'], 'disconnected') + self.assertNotIn('size', out) + self.assertNotIn('rate', out) + + out2 = self.run_script({ + 'BAT0': { + 'type': 'Battery\n', + 'capacity': '80\n', + 'power_now': '-00150000\n', + }, + }) + self.assertEqual(out2['rate'], '0.2W') + + def test_charge_full_fallback_in_pure_bash(self): + # Charge-reporting gauges (no energy_full) report size in mAh without awk. + out = self.run_script({ + 'battery': { + 'type': 'Battery\n', + 'capacity': '50\n', + 'charge_full': '1960000\n', + }, + }) + self.assertEqual(out['size'], '1960mAh') + + # Rounding and leading zeros (avoiding octal interpretation). + out_round = self.run_script({ + 'battery': { + 'type': 'Battery\n', + 'capacity': '50\n', + 'charge_full': '01406500\n', + }, + }) + self.assertEqual(out_round['size'], '1407mAh') + + # Valid energy_full wins over charge_full. + out_both = self.run_script({ + 'battery': { + 'type': 'Battery\n', + 'capacity': '50\n', + 'energy_full': '10000000\n', + 'charge_full': '1960000\n', + }, + }) + self.assertEqual(out_both['size'], '10.0Wh') + + # Unusable energy_full falls back to charge_full. + for bad_energy in ('0\n', 'garbage\n', '-5\n', '\n', '', '99999999999999999999\n'): + with self.subTest(bad_energy=bad_energy): + out_fb = self.run_script({ + 'battery': { + 'type': 'Battery\n', + 'capacity': '50\n', + 'energy_full': bad_energy, + 'charge_full': '1960000\n', + }, + }) + self.assertEqual(out_fb['size'], '1960mAh') + + # Unusable charge_full omits size without aborting under set -e. + for bad_charge in ('0\n', 'garbage\n', '-5\n', '\n', '', '99999999999999999999\n'): + with self.subTest(bad_charge=bad_charge): + out_bad = self.run_script({ + 'battery': { + 'type': 'Battery\n', + 'capacity': '50\n', + 'charge_full': bad_charge, + }, + }) + self.assertNotIn('size', out_bad) + + +class ShellSingletonTests(unittest.TestCase): + def test_battery_and_rotation_status_are_thin_singleton_proxies(self): + qmldir = (PROJECT / 'desktop/shell/shell/Commons/qmldir').read_text() + self.assertIn('singleton BatteryStatus 1.0 BatteryStatus.qml', qmldir) + self.assertIn('singleton RotationLockState 1.0 RotationLockState.qml', qmldir) + + power_status = (PROJECT / 'desktop/shell/shell/plugins/panels/power/Status.qml').read_text() + self.assertNotIn('Timer {', power_status) + self.assertNotIn('Process {', power_status) + self.assertIn('BatteryStatus.batteryInfo', power_status) + + battery_singleton = (PROJECT / 'desktop/shell/shell/Commons/BatteryStatus.qml').read_text() + self.assertIn('refreshPending', battery_singleton) + + rotation_lock = (PROJECT / 'desktop/shell/shell/plugins/status/RotationLock.qml').read_text() + self.assertNotIn('Timer {', rotation_lock) + self.assertNotIn('Process {', rotation_lock) + self.assertIn('RotationLockState.locked', rotation_lock) + self.assertIn('function setLocked(', rotation_lock) + + rotation_singleton = (PROJECT / 'desktop/shell/shell/Commons/RotationLockState.qml').read_text() + self.assertIn('watchChanges: true', rotation_singleton) + self.assertIn('parentDirWatcher', rotation_singleton) + self.assertNotIn('repeat: true', rotation_singleton) + + # Both callers route through rotation.toggle() rather than writing read-only locked. + display_page = (PROJECT / 'desktop/shell/shell/settings/DisplayPage.qml').read_text() + self.assertIn('rotation.toggle()', display_page) + self.assertNotIn('rotation.locked =', display_page) + control_center = (PROJECT / 'desktop/shell/shell/controlcenter/ControlCenter.qml').read_text() + self.assertIn('rotation.toggle()', control_center) + self.assertNotIn('rotation.locked =', control_center) + + +if __name__ == '__main__': + unittest.main()