diff --git a/bin/omarchy-battery-limit b/bin/omarchy-battery-limit new file mode 100755 index 000000000000..f95fb0fdb906 --- /dev/null +++ b/bin/omarchy-battery-limit @@ -0,0 +1,92 @@ +#!/bin/bash + +# omarchy:summary=Inspect and control UPower battery charge limits +# omarchy:args=[status|enable|disable] [--shell] +# omarchy:examples=omarchy battery limit | omarchy battery limit enable + +case "$*" in + "" | status) action=status; shell_output=false ;; + --shell | "status --shell") action=status; shell_output=true ;; + enable | disable) action="$1"; shell_output=false ;; + *) + echo "Usage: omarchy-battery-limit [status|enable|disable] [--shell]" >&2 + exit 2 + ;; +esac + +upower_property() { + local raw value + + raw=$(busctl get-property org.freedesktop.UPower "$1" org.freedesktop.UPower.Device "$2" 2>/dev/null) || return 1 + read -r _ value <<<"$raw" + value=${value#\"} + value=${value%\"} + printf '%s\n' "$value" +} + +declare -a batteries=() +enabled=true +policy=unknown + +while IFS= read -r device; do + [[ $device != */DisplayDevice ]] || continue + [[ $(upower_property "$device" ChargeThresholdSupported || true) == true ]] || continue + + batteries+=("$device") + [[ $(upower_property "$device" ChargeThresholdEnabled || true) == true ]] || enabled=false + + if [[ $policy == unknown ]]; then + settings=$(upower_property "$device" ChargeThresholdSettingsSupported || true) + start=$(upower_property "$device" ChargeStartThreshold || true) + end=$(upower_property "$device" ChargeEndThreshold || true) + + if [[ $settings =~ ^[0-9]+$ ]] && (( (settings & 2) != 0 )) && [[ $end =~ ^[0-9]+$ ]]; then + if (( (settings & 1) != 0 )) && [[ $start =~ ^[0-9]+$ ]] && (( start < end )); then + policy="$start-$end" + else + policy="$end" + fi + elif [[ $settings =~ ^[0-9]+$ ]] && (( (settings & 4) != 0 )); then + policy=firmware + fi + fi +done < <(upower -e 2>/dev/null) + +if (( ${#batteries[@]} == 0 )); then + state=unsupported +elif [[ $enabled == true ]]; then + state=enabled +else + state=disabled +fi + +if [[ $action == status ]]; then + if [[ $shell_output == true ]]; then + printf 'state\t%s\npolicy\t%s\n' "$state" "$policy" + else + case "$state" in + unsupported) echo "Battery protection is not supported" ;; + enabled) echo "Battery protection is enabled" ;; + disabled) echo "Battery protection is disabled" ;; + esac + fi + exit 0 +fi + +if [[ $state == unsupported ]]; then + echo "Battery charge limits are not supported by UPower on this system" >&2 + exit 1 +fi + +[[ $action == enable ]] && desired=true || desired=false +failed=false + +for device in "${batteries[@]}"; do + if ! busctl call org.freedesktop.UPower "$device" org.freedesktop.UPower.Device EnableChargeThreshold b "$desired" >/dev/null; then + echo "Failed to update charge limits for $device" >&2 + failed=true + fi +done + +[[ $failed == false ]] || exit 1 +echo "Battery protection ${action}d" diff --git a/manual/05-the-top-bar.md b/manual/05-the-top-bar.md index 09a028986f4d..e0fc756e6ab6 100644 --- a/manual/05-the-top-bar.md +++ b/manual/05-the-top-bar.md @@ -52,7 +52,9 @@ The panels aren't read-outs. They're where you actually do the thing: - **Audio** has a master volume slider, an output-device picker, and a per-app mixer, so you can turn down that one browser tab without touching everything else. - **Network** scans for Wi-Fi, shows signal strength, connects, and lets you pick a DNS provider. - **Bluetooth** lists your devices with connect/disconnect and battery levels. -- **Power** shows battery stats, switches power profiles (it remembers a separate choice for battery and AC), and prints some system info. +- **Power** shows battery stats, controls battery-health protection when UPower and the hardware support it, switches power profiles (it remembers a separate choice for battery and AC), and prints some system info. + +On compatible laptops, **Preserve battery health** applies the charging policy reported by UPower and keeps it across restarts. The policy commonly stops charging around 80%, but UPower and the hardware choose the actual values rather than Omarchy. The control stays hidden when charging limits are unsupported. - **Display** carries a brightness slider, text size, monitor scaling presets, and — when you have more than one screen — per-monitor controls. See [monitors](33-monitors.md) for the deeper story. - **Clock** opens a month grid with ISO week numbers and month stepping. diff --git a/shell/plugins/bar/README.md b/shell/plugins/bar/README.md index 5741c5f3114d..d1635feb188b 100644 --- a/shell/plugins/bar/README.md +++ b/shell/plugins/bar/README.md @@ -68,7 +68,7 @@ Example `shell.json` (bar subtree only shown): | `omarchy.network` | Wi-Fi/Ethernet icon + popup with Wi-Fi scan, signal, connect, DNS provider selection | left = popup | | `omarchy.tailscale` | Tailscale status, connection switcher, machine browser, and copy actions | left = popup · right = toggle · middle = refresh | | `omarchy.agents` | AI coding agent limits with pace, today, last week, and all-time model breakdown | left = panel · right = launch agent · middle = next subscription | -| `omarchy.power` | Battery/AC icon + popup with battery stats, power profiles, and system info | left = popup · right = toggle percentage | +| `omarchy.power` | Battery/AC icon + popup with battery stats, battery-health protection, power profiles, and system info | left = popup · right = toggle percentage | | `omarchy.bluetooth` | Bluetooth icon + popup with device list, connect/disconnect, battery | left = popup · right = toggle radio | | `omarchy.monitor` | Brightness and laptop display controls | left = popup | diff --git a/shell/plugins/panels/power/Model.js b/shell/plugins/panels/power/Model.js index 8a11dfe7ee57..c9fd25770409 100644 --- a/shell/plugins/panels/power/Model.js +++ b/shell/plugins/panels/power/Model.js @@ -38,6 +38,20 @@ function parseProfiles(raw, previousIndex) { } } +function limitDescription(state, policy) { + var active = state === "enabled" + if (policy === "firmware") return (active ? "Uses" : "Use") + " firmware optimized charging" + if (!policy || policy === "unknown") return (active ? "Uses" : "Use") + " the battery's health-preserving policy" + + var thresholds = policy.split("-") + if (thresholds.length === 2) { + return (active ? "Starts charging at " : "Start charging at ") + thresholds[0] + "% and " + + (active ? "stops" : "stop") + " at " + thresholds[1] + "%" + } + + return (active ? "Stops charging at " : "Limit charging to ") + policy + "%" +} + function profileIcon(name) { if (name === "power-saver") return "󰌪" if (name === "balanced") return "󰊚" @@ -95,6 +109,7 @@ if (typeof module !== "undefined") { selectProfileIndex: selectProfileIndex, parseKeyValue: parseKeyValue, parseProfiles: parseProfiles, + limitDescription: limitDescription, profileIcon: profileIcon, batteryFraction: batteryFraction, chargeThresholdActive: chargeThresholdActive, diff --git a/shell/plugins/panels/power/Panel.qml b/shell/plugins/panels/power/Panel.qml index 871ee2f6ef7d..c8a55cf1d53e 100644 --- a/shell/plugins/panels/power/Panel.qml +++ b/shell/plugins/panels/power/Panel.qml @@ -14,11 +14,16 @@ Panel { // permits — needed for the togglePercentage method below. manageIpc: false property var batteryInfo: ({}) + property var limitInfo: ({ state: "unsupported", policy: "unknown" }) property var systemInfo: ({}) property var profiles: [] property string activeProfile: "" property int profileIndex: 0 property bool cursorActive: false + property string cursorSection: "profiles" + property string limitError: "" + readonly property bool limitVisible: limitInfo.state !== "unsupported" + readonly property string limitDescription: Model.limitDescription(limitInfo.state, limitInfo.policy) readonly property bool showPercentage: setting("showPercentage", false) === true // With the percentage shown the button paints a text block wider than an // icon, so the open-panel mark takes the painted width instead of the @@ -61,6 +66,37 @@ Panel { return Model.profileIcon(name) } + function moveCursor(dx, dy) { + if (!cursorActive) { + cursorActive = true + return + } + + if (limitVisible && ((cursorSection === "limit" && dy > 0) || (cursorSection === "profiles" && dy < 0))) { + cursorSection = cursorSection === "limit" ? "profiles" : "limit" + return + } + + if (cursorSection === "profiles") selectProfileByDelta(dx !== 0 ? dx : dy) + } + + function activateCursor() { + if (!cursorActive) { + cursorActive = true + return + } + + if (cursorSection === "profiles") activateSelectedProfile() + else setLimit(limitInfo.state === "enabled" ? "disable" : "enable") + } + + function setLimit(action) { + if (!action || limitActionProc.running) return + limitError = "" + limitActionProc.command = ["omarchy-battery-limit", action] + limitActionProc.running = true + } + readonly property bool fullyCharged: { var device = UPower.displayDevice return device && device.isPresent && device.state === UPowerDeviceState.FullyCharged && !root.chargeThresholdActive @@ -136,16 +172,25 @@ Panel { if (!batteryPresent) return if (!batteryProc.running) batteryProc.running = true + refreshLimit() if (!profilesProc.running) profilesProc.running = true if (!systemProc.running) systemProc.running = true } + function refreshLimit() { + if (batteryPresent && !limitProc.running) limitProc.running = true + } + function updateKeyValue(raw, targetName) { 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) return if (targetName === "battery") batteryInfo = next + else if (targetName === "limit") { + limitInfo = next + if (!cursorActive) cursorSection = next.state !== "unsupported" ? "limit" : "profiles" + } else systemInfo = next } @@ -196,6 +241,7 @@ Panel { var idx = profiles.indexOf(activeProfile) profileIndex = idx >= 0 ? idx : 0 cursorActive = false + cursorSection = limitVisible ? "limit" : "profiles" } } @@ -211,6 +257,12 @@ Panel { stdout: StdioCollector { waitForEnd: true; onStreamFinished: root.updateKeyValue(text, "battery") } } + Process { + id: limitProc + command: ["omarchy-battery-limit", "status", "--shell"] + stdout: StdioCollector { waitForEnd: true; onStreamFinished: root.updateKeyValue(text, "limit") } + } + Process { id: profilesProc command: ["omarchy-powerprofiles-list", "--active-state"] @@ -228,6 +280,22 @@ Panel { onExited: root.refresh() } + Process { + id: limitActionProc + stderr: StdioCollector { + waitForEnd: true + onStreamFinished: { + var message = text.trim() + if (message !== "") root.limitError = message + } + } + onExited: function(exitCode) { + if (exitCode === 0) root.limitError = "" + else if (root.limitError === "") root.limitError = "Could not update battery protection" + root.refresh() + } + } + Timer { interval: 5000; running: root.opened; repeat: true; onTriggered: root.refresh() } // Rotate the status phrase while the panel is open and we're in a @@ -303,11 +371,9 @@ Panel { id: keyCatcher anchors.fill: parent onMoveRequested: function(dx, dy) { - if (!root.cursorActive) { root.cursorActive = true; return } - if (dx !== 0) root.selectProfileByDelta(dx) - else if (dy !== 0) root.selectProfileByDelta(dy) + root.moveCursor(dx, dy) } - onActivateRequested: if (root.cursorActive) root.activateSelectedProfile() + onActivateRequested: root.activateCursor() onCloseRequested: root.close() onTabRequested: function(direction) { root.switchPanel(direction) } @@ -448,6 +514,51 @@ Panel { } } + // ---------- Battery health ---------- + Column { + visible: root.limitVisible + width: parent.width + spacing: Style.space(10) + + PanelSeparator { + foreground: root.bar.foreground + } + + PanelSectionHeader { + text: "BATTERY HEALTH" + foreground: root.bar.foreground + fontFamily: root.bar.fontFamily + } + + Toggle { + width: parent.width + label: "Preserve battery health" + description: root.limitDescription + checked: root.limitInfo.state === "enabled" + enabled: !limitActionProc.running + hasCursor: root.cursorActive && root.cursorSection === "limit" + foreground: root.bar.foreground + fontFamily: root.bar.fontFamily + onClicked: root.setLimit(root.limitInfo.state === "enabled" ? "disable" : "enable") + onHovered: function(h) { + if (h) { + root.cursorActive = true + root.cursorSection = "limit" + } + } + } + + Text { + visible: root.limitError !== "" + width: parent.width + text: root.limitError + color: Color.urgent + font.family: root.bar.fontFamily + font.pixelSize: Style.font.caption + wrapMode: Text.WordWrap + } + } + // ---------- Power profile picker ---------- PanelSeparator { foreground: root.bar.foreground @@ -488,11 +599,12 @@ Panel { verticalPadding: Style.spacing.controlPaddingY + Style.space(2) bordered: true active: root.activeProfile === modelData - hasCursor: root.cursorActive && root.profileIndex === index + hasCursor: root.cursorActive && root.cursorSection === "profiles" && root.profileIndex === index onClicked: root.setProfile(modelData) onHovered: function(h) { if (h) { root.cursorActive = true + root.cursorSection = "profiles" root.profileIndex = index } } diff --git a/shell/plugins/panels/power/manifest.json b/shell/plugins/panels/power/manifest.json index 64a1eac40dfa..2fa70a8dc9c3 100644 --- a/shell/plugins/panels/power/manifest.json +++ b/shell/plugins/panels/power/manifest.json @@ -4,7 +4,7 @@ "name": "Power", "version": "1.0.0", "author": "Omarchy", - "description": "Battery, power profile, and system stats", + "description": "Battery health, power profiles, and system stats", "kinds": [ "bar-widget" ], @@ -13,7 +13,7 @@ }, "barWidget": { "displayName": "Power", - "description": "Battery, power profile, and system stats", + "description": "Battery health, power profiles, and system stats", "category": "System", "allowMultiple": false } diff --git a/test/shell.d/battery-limit-test.sh b/test/shell.d/battery-limit-test.sh new file mode 100755 index 000000000000..d121f456d18d --- /dev/null +++ b/test/shell.d/battery-limit-test.sh @@ -0,0 +1,90 @@ +#!/bin/bash + +set -euo pipefail + +source "$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)/base-test.sh" + +tmp_dir=$(mktemp -d) +trap 'rm -rf "$tmp_dir"' EXIT +mkdir -p "$tmp_dir/bin" "$tmp_dir/devices" + +cat >"$tmp_dir/bin/upower" <<'STUB' +#!/bin/bash +[[ $1 == "-e" ]] || exit 1 +cat "$UPOWER_DEVICES_FILE" +STUB + +cat >"$tmp_dir/bin/busctl" <<'STUB' +#!/bin/bash +if [[ $1 == "get-property" ]]; then + value=$(<"$BATTERY_FIXTURE_DIR/${3##*/}/$5") || exit 1 + case "$5" in + ChargeThresholdSupported | ChargeThresholdEnabled) printf 'b %s\n' "$value" ;; + *) printf 'u %s\n' "$value" ;; + esac +elif [[ $1 == "call" ]]; then + printf '%s\t%s\n' "$3" "$7" >>"$BATTERY_CALL_LOG" +else + exit 1 +fi +STUB + +chmod +x "$tmp_dir/bin/upower" "$tmp_dir/bin/busctl" +export PATH="$tmp_dir/bin:$ROOT/bin:$PATH" +export UPOWER_DEVICES_FILE="$tmp_dir/upower-devices" +export BATTERY_FIXTURE_DIR="$tmp_dir/devices" +export BATTERY_CALL_LOG="$tmp_dir/calls" + +reset_fixture() { + rm -rf "$BATTERY_FIXTURE_DIR" + mkdir -p "$BATTERY_FIXTURE_DIR" + : >"$UPOWER_DEVICES_FILE" + : >"$BATTERY_CALL_LOG" +} + +add_battery() { + local name="$1" supported="$2" enabled="$3" settings="$4" start="$5" end="$6" + local fixture="$BATTERY_FIXTURE_DIR/$name" + + mkdir -p "$fixture" + printf '/org/freedesktop/UPower/devices/%s\n' "$name" >>"$UPOWER_DEVICES_FILE" + printf '%s\n' "$supported" >"$fixture/ChargeThresholdSupported" + printf '%s\n' "$enabled" >"$fixture/ChargeThresholdEnabled" + printf '%s\n' "$settings" >"$fixture/ChargeThresholdSettingsSupported" + printf '%s\n' "$start" >"$fixture/ChargeStartThreshold" + printf '%s\n' "$end" >"$fixture/ChargeEndThreshold" +} + +field() { + awk -F '\t' -v key="$2" '$1 == key { print $2; exit }' <<<"$1" +} + +reset_fixture +output=$(omarchy-battery-limit status --shell) +[[ $(field "$output" state) == unsupported ]] || fail "battery limit hides unsupported hardware" +pass "battery limit hides unsupported hardware" + +reset_fixture +add_battery battery_BAT0 true false 2 75 80 +output=$(omarchy-battery-limit status --shell) +[[ $(field "$output" state) == disabled ]] || fail "battery limit reports disabled state" +[[ $(field "$output" policy) == 80 ]] || fail "battery limit reports the UPower policy" +omarchy-battery-limit enable >/dev/null +grep -Fx $'/org/freedesktop/UPower/devices/battery_BAT0\ttrue' "$BATTERY_CALL_LOG" >/dev/null || + fail "battery limit enables through UPower" +pass "battery limit enables through UPower" + +reset_fixture +add_battery battery_BAT0 true true 3 75 80 +add_battery battery_BAT1 true false 2 75 85 +output=$(omarchy-battery-limit status --shell) +[[ $(field "$output" state) == disabled ]] || fail "battery limit leaves a partial set unchecked" +omarchy-battery-limit disable >/dev/null +[[ $(wc -l <"$BATTERY_CALL_LOG") == 2 ]] || fail "battery limit updates every supported battery" +grep -F $'\tfalse' "$BATTERY_CALL_LOG" >/dev/null || fail "battery limit disables through UPower" +pass "battery limit updates every supported battery" + +if rg -i 'asus|asusctl|pkexec|systemctl|charge_control_' "$ROOT/bin/omarchy-battery-limit" >/dev/null; then + fail "battery limit remains vendor-neutral and delegates privileges to UPower" +fi +pass "battery limit uses only the vendor-neutral UPower primitive" diff --git a/test/shell.d/power-test.sh b/test/shell.d/power-test.sh index c367e782d201..b6d9d040282f 100644 --- a/test/shell.d/power-test.sh +++ b/test/shell.d/power-test.sh @@ -19,7 +19,9 @@ assertDeepEqual( { profiles: ['power-saver', 'balanced', 'performance'], activeProfile: 'balanced', profileIndex: 2 }, 'power parses profile output and clamps selection' ) - +assertEqual(power.limitDescription('enabled', '75-80'), 'Starts charging at 75% and stops at 80%', 'power explains active threshold ranges') +assertEqual(power.limitDescription('disabled', '75-80'), 'Start charging at 75% and stop at 80%', 'power makes inactive threshold ranges actionable') +assertEqual(power.limitDescription('disabled', 'firmware'), 'Use firmware optimized charging', 'power makes inactive firmware policy actionable') assert(power.profileIcon('performance').length > 0, 'power maps profile icons') assertEqual(power.batteryFraction({ isPresent: true, percentage: 1.5 }), 1, 'power clamps battery fraction') @@ -48,4 +50,11 @@ assert(/Math\.round\(root\.batteryFraction \* 100\) \+ "% " \+ root\.batteryIcon assert(/openPanelIndicatorWidth:.*showPercentage.*button\.glyphPaintedWidth : 0/.test(panelSource), 'power spans the open-panel mark across the painted percentage block') assert(/IpcHandler[\s\S]*?function togglePercentage\(\) \{ root\.togglePercentage\(\) \}/.test(panelSource), 'power exposes togglePercentage over IPC') assert(/manageIpc: false/.test(panelSource), 'power owns its IPC handler so it can extend the target methods') +assert(/command: \["omarchy-battery-limit", "status", "--shell"\]/.test(panelSource), 'power reads charge-limit state through the Omarchy command') +assert(/if \(!cursorActive\) cursorSection = next\.state !== "unsupported" \? "limit" : "profiles"/.test(panelSource), 'power initializes keyboard focus after limit status loads') +assert(/if \(message !== ""\) root\.limitError = message/.test(panelSource), 'power keeps fallback errors when stderr is empty') +assert(/text: "BATTERY HEALTH"/.test(panelSource), 'power includes a battery health section') +assert(/Toggle \{[\s\S]*label: "Preserve battery health"/.test(panelSource), 'power uses the shared toggle control') +assert(!/takeover|ConfirmDialog/.test(panelSource), 'power keeps battery health to one toggle') +assert(!/pkexec|charge_control_end_threshold/.test(panelSource), 'power panel does not perform privileged or vendor-specific writes') JS