diff --git a/bin/omarchy-battery-plugged b/bin/omarchy-battery-plugged new file mode 100755 index 000000000000..d040c7bb5ffa --- /dev/null +++ b/bin/omarchy-battery-plugged @@ -0,0 +1,16 @@ +#!/bin/bash + +# omarchy:summary=Announce that the charger was just connected. +# omarchy:hidden=true + +set -euo pipefail + +# Nerd Font power plug. The icon theme is tried first; this is the fallback. +glyph=$'\U000f06a5' +status=$(omarchy-battery-status || true) + +if [[ -n $status ]]; then + omarchy-notification-send -g "$glyph" -u normal "$(omarchy-i18n battery.chargerConnectedTitle)" "$status" -i ac-adapter --transient +else + omarchy-notification-send -g "$glyph" -u normal "$(omarchy-i18n battery.chargerConnectedTitle)" "$(omarchy-i18n battery.chargerConnectedBody)" -i ac-adapter --transient +fi diff --git a/bin/omarchy-battery-status b/bin/omarchy-battery-status index 320a08fbd8e2..651bb131f9ff 100755 --- a/bin/omarchy-battery-status +++ b/bin/omarchy-battery-status @@ -5,6 +5,7 @@ shell_output=false power_supply_path="${OMARCHY_POWER_SUPPLY_PATH:-/sys/class/power_supply}" +hwmon_path="${OMARCHY_HWMON_PATH:-/sys/class/hwmon}" sleep_run_dir="${OMARCHY_SLEEP_RUN_DIR:-/run/omarchy}" battery_state_dir="${OMARCHY_BATTERY_STATE_DIR:-${XDG_STATE_HOME:-$HOME/.local/state}/omarchy/battery}" @@ -229,6 +230,41 @@ if [[ $shell_output == "true" ]]; then fi fi + # The connected charger: what it can give, and what is drawn from it now. A + # small charger under load leaves little for the battery, and the panel shows + # that split instead of a charge rate that looks like a fault. Apple Silicon + # reports the rating as input_power_limit on its Mains supply; USB-PD supplies + # elsewhere (UCSI) report the negotiated voltage_max and current_max. Below + # 5W is a plain USB port, not a charger rating. + charger_uw=0 + for supply in "$power_supply_path"/*; do + [[ -r $supply/type && $(<"$supply/type") =~ ^(Mains|USB) ]] || continue + [[ $(read_sysfs_number "$supply/online" || true) == "1" ]] || continue + if supply_uw=$(read_sysfs_number "$supply/input_power_limit"); then + : + elif microvolts=$(read_sysfs_number "$supply/voltage_max") && microamps=$(read_sysfs_number "$supply/current_max"); then + supply_uw=$(( microvolts * microamps / 1000000 )) + else + continue + fi + if (( supply_uw > charger_uw )); then + charger_uw=$supply_uw + fi + done + + if (( charger_uw >= 5000000 )); then + printf 'charger\t%sW\n' "$(( (charger_uw + 500000) / 1000000 ))" + + # Only a sensor gives the draw itself (the Apple SMC's "AC Input Power"); + # without one the panel shows the rating alone. + for label in "$hwmon_path"/*/power*_label; do + [[ -r $label && $(<"$label") == "AC Input Power" ]] || continue + microwatts=$(read_sysfs_number "${label%_label}_input") || continue + printf 'charger_draw\t%sW\n' "$(awk -v microwatts="$microwatts" 'BEGIN { rounded = sprintf("%.1f", microwatts / 1000000); sub(/\.0$/, "", rounded); print rounded }')" + break + done + fi + # Charge limit control metadata for the power panel. limit_supported=0 if [[ $upower_threshold_supported == "yes" || -r $battery_path/charge_control_end_threshold ]]; then diff --git a/bin/omarchy-powerprofiles-set b/bin/omarchy-powerprofiles-set index 836ce8271b42..a3c799cd3515 100755 --- a/bin/omarchy-powerprofiles-set +++ b/bin/omarchy-powerprofiles-set @@ -15,10 +15,18 @@ usage() { case "$action" in autodetect) - # Use the same signal as the shell (UPower.onBattery) so every entry point - # saves and restores the profile under the same ac/battery key. - if [[ $(busctl get-property org.freedesktop.UPower /org/freedesktop/UPower org.freedesktop.UPower OnBattery 2>/dev/null) == "b true" ]]; then + # Follow the battery's own state, like the shell's power panel, so every + # entry point saves and restores the profile under the same ac/battery key. + state=$(busctl get-property org.freedesktop.UPower /org/freedesktop/UPower/devices/DisplayDevice org.freedesktop.UPower.Device State 2>/dev/null) + if [[ $state == "u 2" ]]; then action=battery + elif [[ -z $state || $state == "u 0" ]]; then + # Unknown state: fall back to OnBattery, as the shell's power panel does. + if [[ $(busctl get-property org.freedesktop.UPower /org/freedesktop/UPower org.freedesktop.UPower OnBattery 2>/dev/null) == "b true" ]]; then + action=battery + else + action=ac + fi else action=ac fi diff --git a/default/i18n/en/cli.json b/default/i18n/en/cli.json index 7d74f4f70d89..79762b4f9a2a 100644 --- a/default/i18n/en/cli.json +++ b/default/i18n/en/cli.json @@ -63,6 +63,8 @@ "audio.micOn": "Microphone on", "audio.noDevices": "No audio devices found", "audio.noMicrophone": "No microphone found", + "battery.chargerConnectedBody": "Now charging", + "battery.chargerConnectedTitle": "Charger connected", "battery.durationHours": "%1h", "battery.durationHoursMinutes": "%1h %2m", "battery.durationMinutes": "%1m", diff --git a/default/i18n/en/shell.json b/default/i18n/en/shell.json index 8b90053643df..fd27148b9983 100644 --- a/default/i18n/en/shell.json +++ b/default/i18n/en/shell.json @@ -600,6 +600,13 @@ "power.chargeLimit": "Charge limit", "power.chargeLimitFailed": "Could not update charge limit", "power.chargeLimitTo": "Charge to only %1", + "power.charger": "CHARGER", + "power.chargerFromBattery": "From battery", + "power.chargerMaxed": "The charger is at its limit: a stronger one would charge faster", + "power.chargerShort": "The charger can't keep up: the battery covers the rest", + "power.chargerToBattery": "To battery", + "power.chargerToSystem": "To system", + "power.chargerUse": "%1 of %2", "power.charging": "Charging", "power.chargingPhrase1": "Pumping power", "power.chargingPhrase2": "Injecting electrons", diff --git a/docs/notifications.md b/docs/notifications.md index 4bf98141c056..ec961e881fd7 100644 --- a/docs/notifications.md +++ b/docs/notifications.md @@ -207,6 +207,7 @@ The `notifications` IPC target also answers `ping` (used by `omarchy-notificatio Everything goes through the same sender contract, so the pieces are small: - **Low battery** — `omarchy-battery-low` sends a normal toast that expires after 30 seconds (paused, like any card, while the deck is open) and runs the `battery-low` hook. Not critical: a critical toast never expires and comes back on every shell start, so the warning would outlive the charger going in. As an `omarchy-action` toast it still gets through Do Not Disturb. +- **Charger connected** — when line power arrives after the machine has been on battery, `omarchy-battery-plugged` sends a normal transient toast. A flip shorter than two seconds is ignored, so a USB-C renegotiation or a UPower reading that settles at startup does not announce a charger that was not just plugged in. A confirmation already earned survives a reconnect inside that window, and is dropped only if the machine stays on battery through it. - **Crash capture** — `omarchy-crash-watch` follows the systemd-coredump journal stream and announces each crashed program (deduped per minute) as a critical toast whose click runs `omarchy-agent-crash` (via `--exec`, so a diff --git a/shell/plugins/panels/power/Model.js b/shell/plugins/panels/power/Model.js index 2a621f28006d..98387fdb59e6 100644 --- a/shell/plugins/panels/power/Model.js +++ b/shell/plugins/panels/power/Model.js @@ -49,6 +49,23 @@ function batteryFraction(device) { return device && device.isPresent ? Math.max(0, Math.min(1, device.percentage)) : 0 } +// Read the battery's state; OnBattery can stay stale when an AC unplug is missed. +function isDischarging(device, onBattery, states) { + var d = device || {} + var s = states || {} + if (!d.isPresent) return false + if (d.state === undefined || d.state === s.Unknown) return !!onBattery + return d.state === s.Discharging +} + +function isCharging(device, onBattery, states) { + var d = device || {} + var s = states || {} + if (!d.isPresent) return false + if (d.state === undefined || d.state === s.Unknown) return !onBattery + return d.state === s.Charging +} + // rateFresh is false while the charge rate still dates from before external // power arrived. A battery that reports its rate every half minute reads // "charging at 0 W" until then, which is not a threshold holding it. @@ -222,6 +239,52 @@ function usageChart(hours, nowSeconds) { return { columns: columns, screen: screen, used: used } } +// How the charger's power is shared out. Battery status reports the charger's +// rating ("140W") and, where a sensor gives it, the power drawn from it now +// ("136.9W"), with the battery's state and rate. The battery's state, not the +// plug, gives the direction: a charger too weak for the load leaves the battery +// draining while plugged in. Charging, the rate flows into the battery and the +// rest of the draw is what the system takes; draining, the whole draw goes to +// the system and the battery covers the rest (drain). Fractions are of the +// rating. maxed: the charger gives all it has while the battery gets a small +// share of it or none. Null without a charger rating. +function chargerFlow(batteryInfo) { + var info = batteryInfo || {} + var limit = parseFloat(info.charger) + if (!(limit > 0)) return null + + var rate = Math.max(0, parseFloat(info.rate) || 0) + var charging = info.state === "charging" + var draining = info.state === "discharging" + var draw = parseFloat(info.charger_draw) + var hasDraw = draw >= 0 + var battery = charging ? rate : 0 + if (hasDraw) battery = Math.min(battery, draw) + var system = hasDraw ? Math.max(0, draw - battery) : -1 + + function fraction(watts) { return Math.max(0, Math.min(1, watts / limit)) } + + return { + limit: limit, + draw: hasDraw ? draw : -1, + battery: battery, + drain: draining ? rate : 0, + system: system, + batteryFraction: fraction(battery), + systemFraction: hasDraw ? fraction(system) : 0, + maxed: hasDraw && (charging || draining) && draw >= limit * 0.93 && battery < limit * 0.3 + } +} + +// A wattage in the shape battery status writes one, for localizeReading: +// whole watts from 10W up, one decimal below that. +function wattsReading(watts) { + var value = Math.max(0, Number(watts) || 0) + if (value >= 10) return Math.round(value) + "W" + var rounded = String(Math.round(value * 10) / 10) + return rounded + "W" +} + if (typeof module !== "undefined") { module.exports = { clampIndex: clampIndex, @@ -230,6 +293,8 @@ if (typeof module !== "undefined") { parseProfiles: parseProfiles, profileIcon: profileIcon, batteryFraction: batteryFraction, + isDischarging: isDischarging, + isCharging: isCharging, chargeThresholdActive: chargeThresholdActive, batteryIcon: batteryIcon, modeLabel: modeLabel, @@ -241,6 +306,8 @@ if (typeof module !== "undefined") { formatSleepTooltip: formatSleepTooltip, isLowS0ix: isLowS0ix, moveFocus: moveFocus, - usageChart: usageChart + usageChart: usageChart, + chargerFlow: chargerFlow, + wattsReading: wattsReading } } diff --git a/shell/plugins/panels/power/Panel.qml b/shell/plugins/panels/power/Panel.qml index 3d1c07fddf02..23115ce928bd 100644 --- a/shell/plugins/panels/power/Panel.qml +++ b/shell/plugins/panels/power/Panel.qml @@ -44,6 +44,7 @@ Panel { function upowerStates() { return { + Unknown: UPowerDeviceState.Unknown, Charging: UPowerDeviceState.Charging, Discharging: UPowerDeviceState.Discharging, FullyCharged: UPowerDeviceState.FullyCharged, @@ -96,10 +97,8 @@ Panel { var device = UPower.displayDevice return device && device.isPresent && device.state === UPowerDeviceState.FullyCharged && !root.chargeThresholdActive } - readonly property bool discharging: { - var device = UPower.displayDevice - return !!(device && device.isPresent && UPower.onBattery) - } + // The battery's own state; OnBattery can stay stale when an AC unplug is missed. + readonly property bool discharging: Model.isDischarging(UPower.displayDevice, UPower.onBattery, upowerStates()) // False from the moment external power arrives until the battery has had // time to report a charge rate measured with it. Some batteries refresh // the rate only every half minute, and until then it reads 0 W. @@ -108,6 +107,7 @@ Panel { chargeRateFresh = discharging if (discharging) chargeRateSettle.stop() else chargeRateSettle.restart() + if (opened) refreshBatteryInfo() } Timer { id: chargeRateSettle @@ -119,6 +119,8 @@ Panel { return Model.chargeThresholdActive(device, root.discharging, upowerStates(), root.chargeRateFresh, root.activeChargeLimit) } readonly property bool batteryFull: fullyCharged || (!root.discharging && batteryFraction >= 1) + // The charger's rating and how its power is shared between battery and system. + readonly property var chargerFlow: Model.chargerFlow(root.batteryInfo) readonly property bool batteryFlowIdle: batteryFull || chargeThresholdActive // 0..1 charge level, used by the visual progress bar. @@ -238,9 +240,12 @@ Panel { } function refresh() { - if (!batteryPresent) return - refreshBatteryInfo() + refreshPanelData() + } + + function refreshPanelData() { + if (!batteryPresent) return usage = Model.usageChart(batteryService ? batteryService.usage : null, Math.floor(Date.now() / 1000)) if (profiles.length === 0 && !profilesProc.running) profilesProc.running = true } @@ -347,6 +352,11 @@ Panel { implicitWidth: batteryPresent ? button.implicitWidth : 0 implicitHeight: batteryPresent ? button.implicitHeight : 0 + Connections { + target: UPower + function onOnBatteryChanged() { root.refreshBatteryInfo() } + } + Connections { target: PowerProfiles function onProfileChanged() { root.syncActiveProfile(root.profileName(PowerProfiles.profile)) } @@ -407,7 +417,10 @@ Panel { } } - Timer { interval: 5000; running: root.opened; repeat: true; onTriggered: root.refresh() } + Timer { interval: 5000; running: root.opened; repeat: true; onTriggered: root.refreshPanelData() } + // The helper also reads values without change signals, such as sleep drain. + // Read those periodically only while open; power and charge-limit events refresh immediately. + Timer { interval: 30000; running: root.opened; repeat: true; onTriggered: root.refreshBatteryInfo() } // Rotate the status phrase while the panel is open and we're in a // rotating state (charging or on battery). The text swap is wrapped in a @@ -708,6 +721,141 @@ Panel { } } + // ---------- Charger: its rating, and how its power is shared ---------- + // One bar is the charger's whole rating: the solid part flows into the + // battery, the softer part is what the system takes, the track is what + // is left. Without a sensor for the draw only the battery's part shows. + PanelSeparator { + visible: chargerSection.visible + foreground: root.bar.foreground + } + + Column { + id: chargerSection + readonly property var flow: root.chargerFlow + readonly property bool maxed: flow !== null && flow.maxed + visible: flow !== null + width: parent.width + spacing: Style.space(10) + + Item { + width: parent.width + implicitHeight: Math.max(chargerHeader.implicitHeight, chargerRating.implicitHeight) + + PanelSectionHeader { + id: chargerHeader + text: Commons.I18n.t("power.charger") + foreground: root.bar.foreground + fontFamily: root.bar.fontFamily + anchors.left: parent.left + anchors.verticalCenter: parent.verticalCenter + } + + InfoValue { + id: chargerRating + anchors.right: parent.right + anchors.verticalCenter: parent.verticalCenter + color: chargerSection.maxed ? Commons.Color.warning : root.bar.foreground + text: { + var flow = chargerSection.flow + if (!flow) return "" + if (flow.draw < 0) return root.reading(root.batteryInfo.charger) + return Commons.I18n.t("power.chargerUse").arg(root.reading(Model.wattsReading(flow.draw))).arg(root.reading(root.batteryInfo.charger)) + } + + Behavior on color { ColorAnimation { duration: Style.duration(220) } } + } + } + + Item { + width: parent.width + implicitHeight: Style.space(6) + + Rectangle { + id: chargerTrack + anchors.fill: parent + radius: height / 2 + color: Qt.rgba(root.bar.foreground.r, root.bar.foreground.g, root.bar.foreground.b, 0.12) + } + + // The system's part spans both shares and the battery's covers its + // start, so the two meet without a seam. + Rectangle { + readonly property real fraction: chargerSection.flow ? Math.min(1, chargerSection.flow.batteryFraction + chargerSection.flow.systemFraction) : 0 + visible: chargerSection.flow !== null && chargerSection.flow.systemFraction > 0 + anchors.left: chargerTrack.left + anchors.verticalCenter: chargerTrack.verticalCenter + height: chargerTrack.height + radius: chargerTrack.radius + width: Math.max(chargerTrack.height, chargerTrack.width * fraction) + color: chargerSection.maxed + ? Qt.rgba(Commons.Color.warning.r, Commons.Color.warning.g, Commons.Color.warning.b, 0.75) + : Qt.rgba(root.bar.foreground.r, root.bar.foreground.g, root.bar.foreground.b, 0.38) + + Behavior on width { NumberAnimation { duration: Style.duration(250); easing.type: Easing.Bezier; easing.bezierCurve: Style.easeOut } } + Behavior on color { ColorAnimation { duration: Style.duration(220) } } + } + + Rectangle { + visible: chargerSection.flow !== null && chargerSection.flow.batteryFraction > 0 + anchors.left: chargerTrack.left + anchors.verticalCenter: chargerTrack.verticalCenter + height: chargerTrack.height + radius: chargerTrack.radius + width: chargerSection.flow ? Math.max(chargerTrack.height, chargerTrack.width * chargerSection.flow.batteryFraction) : 0 + color: root.batteryFillColor + + Behavior on width { NumberAnimation { duration: Style.duration(250); easing.type: Easing.Bezier; easing.bezierCurve: Style.easeOut } } + } + } + + Row { + width: parent.width + spacing: Style.space(20) + + InfoPair { + width: (parent.width - parent.spacing) / 2 + readonly property bool draining: chargerSection.flow !== null && chargerSection.flow.drain > 0 + label: draining ? Commons.I18n.t("power.chargerFromBattery") : Commons.I18n.t("power.chargerToBattery") + value: draining ? root.reading(Model.wattsReading(chargerSection.flow.drain)) + : chargerSection.flow && chargerSection.flow.battery > 0 ? root.reading(Model.wattsReading(chargerSection.flow.battery)) : "-" + } + + InfoPair { + width: (parent.width - parent.spacing) / 2 + label: Commons.I18n.t("power.chargerToSystem") + value: chargerSection.flow && chargerSection.flow.system >= 0 ? root.reading(Model.wattsReading(chargerSection.flow.system)) : "—" + } + } + + Row { + visible: chargerSection.maxed + width: parent.width + spacing: Style.space(6) + + Text { + id: chargerWarnIcon + text: "󰀦" + textFormat: Text.PlainText + color: Commons.Color.warning + font.family: root.bar.fontFamily + font.pixelSize: Style.font.caption + anchors.verticalCenter: parent.verticalCenter + } + + Text { + text: chargerSection.flow && chargerSection.flow.drain > 0 ? Commons.I18n.t("power.chargerShort") : Commons.I18n.t("power.chargerMaxed") + textFormat: Text.PlainText + color: Commons.Color.warning + font.family: root.bar.fontFamily + font.pixelSize: Style.font.caption + wrapMode: Text.WordWrap + width: parent.width - chargerWarnIcon.implicitWidth - parent.spacing + anchors.verticalCenter: parent.verticalCenter + } + } + } + // ---------- Last 24 hours: level, external power, screen-on time ---------- PanelSeparator { foreground: root.bar.foreground diff --git a/shell/plugins/services/battery/BatteryModel.js b/shell/plugins/services/battery/BatteryModel.js index b326be129a07..93f54099d6fd 100644 --- a/shell/plugins/services/battery/BatteryModel.js +++ b/shell/plugins/services/battery/BatteryModel.js @@ -99,6 +99,48 @@ function recordUsage(hours, held, now, maxGap) { return next } +// Line power just arrived. Ignore a flap shorter than this: USB-C PD +// renegotiation and the first UPower reading at startup both look like a +// plug-in if the machine was only "on battery" for a moment. +var chargerAnnounceMinMs = 2000 + +function shouldAnnounceChargerConnected(wasOnBattery, onBattery, batteryPresent, onBatteryForMs) { + if (!batteryPresent) return false + if (wasOnBattery !== true || onBattery !== false) return false + return onBatteryForMs >= chargerAnnounceMinMs +} + +// A qualified plug stays pending across a power blip shorter than +// chargerAnnounceMinMs. Returning to AC while it is still pending announces +// again. Staying on battery through that window drops it: the charger is out. +function stepChargerAnnounce(state, onBattery, batteryPresent, nowMs) { + var sinceMs = state && state.sinceMs != null ? state.sinceMs : -1 + var pending = !!(state && state.pending) + var wasOnBattery = !!(state && state.onBattery) + var announce = false + + if (!batteryPresent) { + return { onBattery: !!onBattery, sinceMs: -1, pending: false, announce: false } + } + + if (wasOnBattery && !onBattery) { + var elapsed = sinceMs < 0 ? -1 : nowMs - sinceMs + if (pending || elapsed >= chargerAnnounceMinMs) { + pending = true + announce = true + } + sinceMs = -1 + } else if (!wasOnBattery && onBattery) { + if (sinceMs < 0) sinceMs = nowMs + } else if (onBattery && pending && sinceMs >= 0 && nowMs - sinceMs >= chargerAnnounceMinMs) { + pending = false + } else if (onBattery && sinceMs < 0) { + sinceMs = nowMs + } + + return { onBattery: !!onBattery, sinceMs: sinceMs, pending: pending, announce: announce } +} + if (typeof module !== "undefined") { module.exports = { batteryPercentage: batteryPercentage, @@ -108,6 +150,9 @@ if (typeof module !== "undefined") { profileAfterRead: profileAfterRead, shouldRearmChargeLimit: shouldRearmChargeLimit, parseUsage: parseUsage, - recordUsage: recordUsage + recordUsage: recordUsage, + chargerAnnounceMinMs: chargerAnnounceMinMs, + shouldAnnounceChargerConnected: shouldAnnounceChargerConnected, + stepChargerAnnounce: stepChargerAnnounce } } diff --git a/shell/plugins/services/battery/Service.qml b/shell/plugins/services/battery/Service.qml index 0e37fe646d3c..7041c13a6f5d 100644 --- a/shell/plugins/services/battery/Service.qml +++ b/shell/plugins/services/battery/Service.qml @@ -13,6 +13,13 @@ Item { readonly property int batteryThreshold: 10 property string pendingPowerSource: "" + readonly property string powerSource: { + var device = UPower.displayDevice + var known = device && device.isPresent && device.state !== undefined && device.state !== UPowerDeviceState.Unknown + return (known ? device.state === UPowerDeviceState.Discharging : UPower.onBattery) ? "battery" : "ac" + } + property bool powerSourceReady: false + onPowerSourceChanged: if (powerSourceReady) root.applyPowerProfile() // Follows power-profiles-daemon's change signals, so nothing polls it. // Quickshell never attaches that listener if the daemon failed when the // shell started, so a one-off read on startup, on a power source change and @@ -23,6 +30,9 @@ Item { property int powerProfileReadSignals: 0 property int chargeLimitSignals: 0 property bool lastOnBattery: UPower.onBattery + property bool chargerAnnounceOnBattery: UPower.onBattery + property double chargerOnBatterySinceMs: -1 + property bool chargerAnnouncePending: false readonly property string stateDir: { var stateHome = Quickshell.env("XDG_STATE_HOME") @@ -103,7 +113,7 @@ Item { } function applyPowerProfile() { - pendingPowerSource = UPower.onBattery ? "battery" : "ac" + pendingPowerSource = powerSource if (!powerProfileProcess.running) runPendingPowerProfile() } @@ -125,9 +135,13 @@ Item { powerProfileReadProcess.running = true } - function refreshChargeLimit() { + function refreshChargeLimitState() { topUpOnceFile.reread() chargeLimitSignals++ + } + + function refreshChargeLimit() { + refreshChargeLimitState() checkTopUpOnceRearm() } @@ -151,11 +165,61 @@ Item { } } + function applyChargerAnnounce(nowMs) { + var present = !!(UPower.displayDevice && UPower.displayDevice.isPresent) + var next = BatteryModel.stepChargerAnnounce({ + onBattery: root.chargerAnnounceOnBattery, + sinceMs: root.chargerOnBatterySinceMs, + pending: root.chargerAnnouncePending + }, UPower.onBattery, present, nowMs) + root.chargerAnnounceOnBattery = next.onBattery + root.chargerOnBatterySinceMs = next.sinceMs + root.chargerAnnouncePending = next.pending + if (next.announce) chargerAnnounceDebounce.restart() + else if (UPower.onBattery) chargerAnnounceDebounce.stop() + if (next.pending && UPower.onBattery) chargerAnnounceExpire.restart() + else chargerAnnounceExpire.stop() + } + + function sendChargerConnected() { + root.chargerAnnouncePending = false + if (chargerAnnounceProcess.running) return + chargerAnnounceProcess.command = ["omarchy-battery-plugged"] + chargerAnnounceProcess.running = true + } + Process { id: warningProcess } + Process { id: chargerAnnounceProcess } + + // Confirm the plug survived a moment, so a double signal does not toast twice. + // A blip back to battery during this wait must not drop the confirmation: + // applyChargerAnnounce keeps it pending and restarts this timer if AC returns. + Timer { + id: chargerAnnounceDebounce + interval: 500 + onTriggered: { + if (UPower.onBattery) return + if (!UPower.displayDevice || !UPower.displayDevice.isPresent) return + root.sendChargerConnected() + } + } + + // A pending confirmation dies only if the machine stays on battery this long. + Timer { + id: chargerAnnounceExpire + interval: BatteryModel.chargerAnnounceMinMs + onTriggered: { + if (!UPower.onBattery) return + root.applyChargerAnnounce(Date.now()) + } + } + Process { id: chargeLimitProcess - onExited: root.refreshChargeLimit() + // A failed write leaves the marker in place. Refresh the readout, but + // wait for another battery event or explicit refresh before trying again. + onExited: root.refreshChargeLimitState() } // Wait briefly on unplug before re-arming a one-time top-up so USB-C PD @@ -228,7 +292,6 @@ Item { root.lastOnBattery = UPower.onBattery root.recordUsage(true) root.checkBattery() - root.applyPowerProfile() root.refreshPowerProfile() if (root.topUpOnce) { if (!wasOnBattery && UPower.onBattery) topUpRearmDebounce.restart() @@ -237,6 +300,7 @@ Item { root.checkTopUpOnceRearm() } } + root.applyChargerAnnounce(Date.now()) } } @@ -250,6 +314,9 @@ Item { } Component.onCompleted: { + root.powerSourceReady = true + root.applyPowerProfile() + if (UPower.onBattery) root.chargerOnBatterySinceMs = Date.now() root.refreshPowerProfile() root.checkTopUpOnceRearm() } diff --git a/test/shell.d/battery-status-test.sh b/test/shell.d/battery-status-test.sh index a409fdcbff37..b188a694c6be 100644 --- a/test/shell.d/battery-status-test.sh +++ b/test/shell.d/battery-status-test.sh @@ -139,6 +139,36 @@ charging_output=$(OMARCHY_POWER_SUPPLY_PATH="$hold_dir/power" PATH="$hold_dir/bi grep -Fx $'time\t1h' <<<"$charging_output" >/dev/null || fail "time to full counts up to the charge limit" "$charging_output" pass "battery status times charging to the charge limit" +# The charger: a Mains supply without a rating shows none, Apple Silicon's +# input_power_limit and SMC sensor give the rating and the draw, a USB-PD +# supply gives its negotiated rating, and a plain USB port is no charger. +mkdir -p "$hold_dir/hwmon/hwmon0" +charger_output=$(OMARCHY_POWER_SUPPLY_PATH="$hold_dir/power" OMARCHY_HWMON_PATH="$hold_dir/hwmon" PATH="$hold_dir/bin:$PATH" "$ROOT/bin/omarchy-battery-status" --shell) +! grep -q '^charger' <<<"$charger_output" || fail "a charger without a rating reports none" "$charger_output" + +printf '65200000\n' >"$hold_dir/power/ac/input_power_limit" +printf 'AC Input Power\n' >"$hold_dir/hwmon/hwmon0/power1_label" +printf '64120000\n' >"$hold_dir/hwmon/hwmon0/power1_input" +charger_output=$(OMARCHY_POWER_SUPPLY_PATH="$hold_dir/power" OMARCHY_HWMON_PATH="$hold_dir/hwmon" PATH="$hold_dir/bin:$PATH" "$ROOT/bin/omarchy-battery-status" --shell) +grep -Fx $'charger\t65W' <<<"$charger_output" >/dev/null || fail "battery status reports the charger's input power limit" "$charger_output" +grep -Fx $'charger_draw\t64.1W' <<<"$charger_output" >/dev/null || fail "battery status reports the power drawn from the charger" "$charger_output" + +rm "$hold_dir/power/ac/input_power_limit" "$hold_dir/hwmon/hwmon0/power1_label" +mkdir -p "$hold_dir/power/ucsi-source-psy-USBC000:001" +printf 'USB\n' >"$hold_dir/power/ucsi-source-psy-USBC000:001/type" +printf '1\n' >"$hold_dir/power/ucsi-source-psy-USBC000:001/online" +printf '20000000\n' >"$hold_dir/power/ucsi-source-psy-USBC000:001/voltage_max" +printf '5000000\n' >"$hold_dir/power/ucsi-source-psy-USBC000:001/current_max" +charger_output=$(OMARCHY_POWER_SUPPLY_PATH="$hold_dir/power" OMARCHY_HWMON_PATH="$hold_dir/hwmon" PATH="$hold_dir/bin:$PATH" "$ROOT/bin/omarchy-battery-status" --shell) +grep -Fx $'charger\t100W' <<<"$charger_output" >/dev/null || fail "battery status reports a USB-PD charger's negotiated rating" "$charger_output" +! grep -q '^charger_draw' <<<"$charger_output" || fail "battery status reports no draw without a sensor" "$charger_output" + +printf '5000000\n' >"$hold_dir/power/ucsi-source-psy-USBC000:001/voltage_max" +printf '500000\n' >"$hold_dir/power/ucsi-source-psy-USBC000:001/current_max" +charger_output=$(OMARCHY_POWER_SUPPLY_PATH="$hold_dir/power" OMARCHY_HWMON_PATH="$hold_dir/hwmon" PATH="$hold_dir/bin:$PATH" "$ROOT/bin/omarchy-battery-status" --shell) +! grep -q '^charger' <<<"$charger_output" || fail "a plain USB port is no charger" "$charger_output" +pass "battery status reports the charger's rating and draw where the hardware gives them" + # UPower's own estimate stands in when the draw is too small to divide by... printf '100000\n' >"$hold_dir/power/BAT0/power_now" idle_output=$(OMARCHY_POWER_SUPPLY_PATH="$hold_dir/power" PATH="$hold_dir/bin:$PATH" "$ROOT/bin/omarchy-battery-status" --shell) diff --git a/test/shell.d/battery-test.sh b/test/shell.d/battery-test.sh index 5f573a49aa19..9daf503ae800 100644 --- a/test/shell.d/battery-test.sh +++ b/test/shell.d/battery-test.sh @@ -6,6 +6,18 @@ source "$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)/base-test.sh" run_node_test <<'JS' const battery = requireFromRoot('shell/plugins/services/battery/BatteryModel.js') +const serviceQml = require('fs').readFileSync(path.join(root, 'shell/plugins/services/battery/Service.qml'), 'utf8') +const powerSourceBody = serviceQml.match(/readonly property string powerSource: \{([\s\S]*?)\n \}/)[1] +function source(state, onBattery, present = true) { + return require('vm').runInNewContext(`(function() {${powerSourceBody}})()`, { + UPower: { displayDevice: { isPresent: present, state }, onBattery }, + UPowerDeviceState: { Unknown: 0, Charging: 1, Discharging: 2 } + }) +} +assertEqual(source(2, false), 'battery', 'automatic profiles follow discharging with a weak charger or stale on-battery flag') +assertEqual(source(1, true), 'ac', 'automatic profiles follow charging over a stale on-battery flag') +assertEqual(source(0, true), 'battery', 'unknown battery state falls back to on-battery') + const discharging = 1 const charging = 2 @@ -120,4 +132,51 @@ assertDeepEqual(Object.keys(aged), [String(at(30, 0))], 'usage drops hours older assertEqual(battery.recordUsage(usage, { at: at(1, 30), plugged: false, screenOn: false, level: 79 }, { at: at(60, 0), plugged: false, screenOn: false, level: 20 }, 90)[at(60, 0)].used, 0, 'usage leaves out a drop that spans more than the day it keeps') assertDeepEqual(battery.parseUsage('not json'), {}, 'usage reads a broken file as empty') +assert( + battery.shouldAnnounceChargerConnected(true, false, true, battery.chargerAnnounceMinMs), + 'battery announces a charger connected after time on battery' +) +assert( + !battery.shouldAnnounceChargerConnected(true, false, true, battery.chargerAnnounceMinMs - 1), + 'battery ignores a power-source flap shorter than the announce window' +) +assert( + !battery.shouldAnnounceChargerConnected(true, false, false, 5000), + 'battery does not announce a charger when no battery is present' +) +assert( + !battery.shouldAnnounceChargerConnected(false, false, true, 5000), + 'battery does not announce when already on external power' +) +assert( + !battery.shouldAnnounceChargerConnected(true, true, true, 5000), + 'battery does not announce while still on battery' +) +assert( + !battery.shouldAnnounceChargerConnected(false, true, true, 5000), + 'battery does not announce when the charger is removed' +) + +const minMs = battery.chargerAnnounceMinMs +let plugged = battery.stepChargerAnnounce({ onBattery: true, sinceMs: 0, pending: false }, false, true, minMs) +assert(plugged.announce && plugged.pending, 'a long battery stretch qualifies the charger toast') +let blip = battery.stepChargerAnnounce(plugged, true, true, minMs + 200) +assert(!blip.announce && blip.pending, 'a power blip keeps the charger confirmation pending') +let back = battery.stepChargerAnnounce(blip, false, true, minMs + 400) +assert(back.announce, 'reconnecting inside the window still announces the charger') +let stayed = battery.stepChargerAnnounce(blip, true, true, minMs + 200 + minMs) +assert(!stayed.pending && !stayed.announce, 'staying on battery through the window drops the confirmation') +let flap = battery.stepChargerAnnounce({ onBattery: false, sinceMs: -1, pending: false }, true, true, 0) +flap = battery.stepChargerAnnounce(flap, false, true, minMs - 1) +assert(!flap.announce, 'a flap that never qualified does not announce a charger') JS + +if command -v quickshell >/dev/null && command -v dbus-run-session >/dev/null; then + if ! output=$(timeout 15 dbus-run-session -- /usr/bin/python3 \ + "$SHELL_TEST_DIR/fixtures/battery-charge-limit.py" "$ROOT" 2>&1); then + fail "charge-limit failure waits for a new battery event before retrying" "$output" + fi + pass "charge-limit failure waits for a new battery event before retrying" +else + skip "Quickshell and dbus-run-session are needed for the charge-limit retry fixture" +fi diff --git a/test/shell.d/fixtures/battery-charge-limit.py b/test/shell.d/fixtures/battery-charge-limit.py new file mode 100644 index 000000000000..33da54d68226 --- /dev/null +++ b/test/shell.d/fixtures/battery-charge-limit.py @@ -0,0 +1,147 @@ +import os +from pathlib import Path +import subprocess +import sys +from tempfile import TemporaryDirectory + +from gi.repository import Gio, GLib + +UPOWER = "org.freedesktop.UPower" +DEVICE = UPOWER + ".Device" +ROOT = "/org/freedesktop/UPower" +BATTERY = ROOT + "/devices/battery_BAT0" +bus = Gio.bus_get_sync(Gio.BusType.SESSION) +loop = GLib.MainLoop() +props = { + "IsPresent": GLib.Variant("b", True), + "PowerSupply": GLib.Variant("b", True), + "ChargeThresholdSupported": GLib.Variant("b", True), + "ChargeThresholdEnabled": GLib.Variant("b", False), + "Percentage": GLib.Variant("d", 100.0), + "State": GLib.Variant("u", 1), # Charging; 100% also finishes a top-up. +} +attempts = 0 +accept_threshold = False + + +def method_call(connection, sender, path, interface, method, params, invocation): + global attempts + if method == "EnumerateDevices": + invocation.return_value(GLib.Variant("(ao)", ([BATTERY],))) + elif method == "GetDisplayDevice": + invocation.return_value(GLib.Variant("(o)", (BATTERY,))) + elif method == "EnableChargeThreshold": + attempts += 1 + assert params.unpack() == (True,) + if accept_threshold: + props["ChargeThresholdEnabled"] = GLib.Variant("b", True) + invocation.return_value(None) + else: + invocation.return_dbus_error("org.freedesktop.UPower.GeneralError", "test threshold write rejected") + + +def get_property(connection, sender, path, interface, name): + return GLib.Variant("b", False) if name == "OnBattery" else props[name] + + +def register(path, interface, methods, properties): + xml = f'{methods}' + "".join( + f'' + for name, value in properties.items() + ) + "" + bus.register_object(path, Gio.DBusNodeInfo.new_for_xml(xml).interfaces[0], method_call, get_property) + + +register(ROOT, UPOWER, """ + + +""", {"OnBattery": GLib.Variant("b", False)}) +register(BATTERY, DEVICE, """ + +""", props) +bus.call_sync("org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus", + "RequestName", GLib.Variant("(su)", (UPOWER, 0)), None, 0, 5000, None) + + +def update_percentage(percentage): + changed = {"Percentage": GLib.Variant("d", percentage)} + props.update(changed) + bus.emit_signal(None, BATTERY, "org.freedesktop.DBus.Properties", "PropertiesChanged", + GLib.Variant("(sa{sv}as)", (DEVICE, changed, []))) + + +def wait_until(predicate, timeout_ms=4000): + deadline = GLib.get_monotonic_time() + timeout_ms * 1000 + + def check(): + if predicate() or GLib.get_monotonic_time() >= deadline: + loop.quit() + return GLib.SOURCE_REMOVE + return GLib.SOURCE_CONTINUE + + GLib.timeout_add(10, check) + loop.run() + return predicate() + + +with TemporaryDirectory() as tmp: + home = Path(tmp) + state = home / "state" + marker = state / "omarchy" / "battery" / "top-up-once" + marker.parent.mkdir(parents=True) + marker.write_text("1\n") + repo = Path(sys.argv[1]) + config = home / "config" + config.mkdir() + (config / "battery").symlink_to(repo / "shell/plugins/services/battery", target_is_directory=True) + (config / "Commons").symlink_to(repo / "shell/Commons", target_is_directory=True) + (config / "shell.qml").write_text(""" +import Quickshell +import "battery" as Battery + +ShellRoot { + Battery.Service { + readonly property int observedPercentage: batteryPercentage() + onObservedPercentageChanged: console.info("fixture percentage " + observedPercentage) + // A rejected CLI write cannot send a refresh over IPC. The service only + // emits this signal for that attempt once it has handled the child's exit. + onChargeLimitSignalsChanged: console.info("fixture charge limit refreshed") + } +} +""") + (home / "run").mkdir(mode=0o700) + env = {**os.environ, "DBUS_SYSTEM_BUS_ADDRESS": os.environ["DBUS_SESSION_BUS_ADDRESS"], + "HOME": tmp, "XDG_RUNTIME_DIR": str(home / "run"), "XDG_CONFIG_HOME": str(home / ".config"), + "XDG_CACHE_HOME": str(home / ".cache"), "XDG_STATE_HOME": str(state), + "OMARCHY_BATTERY_STATE_DIR": str(marker.parent), "OMARCHY_POWER_SUPPLY_PATH": str(home / "sys"), + "QT_QPA_PLATFORM": "offscreen", "QML_IMPORT_PATH": str(repo / "shell"), + "QS_DISABLE_CRASH_HANDLER": "1", "PATH": f"{repo}/bin:{os.environ['PATH']}"} + log_path = home / "quickshell.log" + + def logged(message): + return message.encode() in log_path.read_bytes() + + with log_path.open("w") as log: + shell = subprocess.Popen(["quickshell", "-p", str(config), "--no-color"], stdout=log, stderr=log, env=env) + try: + # Dispatch the real Quickshell battery service and its real CLI on a + # private bus. The fixture only supplies the battery and write outcome. + assert wait_until(lambda: attempts > 0 and logged("fixture charge limit refreshed")), \ + "the first charge-limit failure did not complete" + assert marker.exists(), "a failed write must keep the request pending" + assert not wait_until(lambda: attempts > 1, 300), "the failed charge-limit write retried without a new battery event" + + update_percentage(95.0) + assert wait_until(lambda: logged("fixture percentage 95")), "Quickshell did not see the below-full reading" + assert not wait_until(lambda: attempts > 1, 200), "charging below the limit must not retry" + + accept_threshold = True + update_percentage(100.0) + assert wait_until(lambda: attempts >= 2 and not marker.exists()), "the successful retry did not clear the request" + assert attempts == 2, f"a new full-charge event must retry exactly once, saw {attempts}" + except Exception: + print(log_path.read_text(errors="replace")[-5000:], file=sys.stderr) + raise + finally: + shell.terminate() + shell.wait(timeout=5) diff --git a/test/shell.d/power-test.sh b/test/shell.d/power-test.sh index 96aafb4acc13..5635dad6accf 100644 --- a/test/shell.d/power-test.sh +++ b/test/shell.d/power-test.sh @@ -137,4 +137,18 @@ assertEqual(chart.screen, 1920, 'power totals screen-on time within the window') assertEqual(chart.columns[23].change, 10, 'power reports the change against the hour before') assertEqual(power.usageChart({ [499 * hour]: { level: 60, used: 5 }, [500 * hour]: { level: 60, used: 15 }, [470 * hour]: { used: 9 } }, now).used, 20, 'power totals the battery used within the window') +// A small charger under load: most of it goes to the system, so it reads as maxed. +const small = power.chargerFlow({ charger: '65W', charger_draw: '64.1W', rate: '10.7W', state: 'charging' }) +assertEqual(small.system, 64.1 - 10.7, 'power takes the battery\'s share out of the charger draw') +assert(small.maxed, 'power flags a charger that is maxed while the battery gets little of it') +assert(!power.chargerFlow({ charger: '140W', charger_draw: '136.9W', rate: '67.1W', state: 'charging' }).maxed, 'power does not flag a charger that is maxed by fast charging') +// A charger too weak for the load: plugged in, yet the battery drains. +const short = power.chargerFlow({ charger: '65W', charger_draw: '64.1W', rate: '10W', state: 'discharging' }) +assert(short.battery === 0 && short.drain === 10 && short.system === 64.1 && short.maxed, 'power counts a battery draining on a weak charger as covering the system, not as charging') +assertEqual(power.chargerFlow({ charger: '140W', charger_draw: '40W', rate: '0W', state: 'fully-charged' }).batteryFraction, 0, 'power gives a full battery no share') +const unsensed = power.chargerFlow({ charger: '65W', rate: '30W', state: 'charging' }) +assert(unsensed.system < 0 && !unsensed.maxed, 'power leaves the system share unknown without a draw sensor') +assertEqual(power.chargerFlow({ rate: '12W' }), null, 'power shows no charger without a rating') +assertEqual(power.wattsReading(7.25) + ' ' + power.wattsReading(136.9), '7.3W 137W', 'power rounds wattages like battery status') + JS diff --git a/test/shell.d/powerprofiles-set-test.sh b/test/shell.d/powerprofiles-set-test.sh index d1fcc99698e8..876115bec042 100755 --- a/test/shell.d/powerprofiles-set-test.sh +++ b/test/shell.d/powerprofiles-set-test.sh @@ -28,11 +28,12 @@ chmod +x "$tmp_dir/bin/powerprofilesctl" cat >"$tmp_dir/bin/busctl" <<'EOF' #!/bin/bash -if [[ ${ON_BATTERY:-0} == "1" ]]; then - echo "b true" -else - echo "b false" -fi +# Autodetect reads the battery's state; OnBattery is answered separately so a +# test can leave it stale while the battery reports discharging. +case "${!#}" in + State) printf 'u %s\n' "${BATTERY_STATE:-1}" ;; + OnBattery) printf 'b %s\n' "${ON_BATTERY:-false}" ;; +esac EOF chmod +x "$tmp_dir/bin/busctl" @@ -63,12 +64,18 @@ pass "power profile stores battery preference separately" [[ $(tail -n 1 "$tmp_dir/calls") == "balanced" ]] || fail "battery preference does not replace AC preference" pass "power profile keeps AC and battery preferences separate" -ON_BATTERY=1 "$ROOT/bin/omarchy-powerprofiles-set" +BATTERY_STATE=2 "$ROOT/bin/omarchy-powerprofiles-set" [[ $(tail -n 1 "$tmp_dir/calls") == "performance" ]] || fail "autodetect restores battery preference" pass "power profile autodetect restores battery preference" +# upowerd can keep OnBattery false after unplug while the battery reports +# discharging; autodetect must follow the battery. +BATTERY_STATE=2 ON_BATTERY=false "$ROOT/bin/omarchy-powerprofiles-set" +[[ $(tail -n 1 "$tmp_dir/calls") == "performance" ]] || fail "autodetect follows the battery over a stale OnBattery" +pass "power profile autodetect follows the battery over a stale OnBattery" + rm "$tmp_dir/state/ac" -ON_BATTERY=0 "$ROOT/bin/omarchy-powerprofiles-set" +BATTERY_STATE=1 "$ROOT/bin/omarchy-powerprofiles-set" [[ $(tail -n 1 "$tmp_dir/calls") == "performance" ]] || fail "power profile uses performance as AC default" pass "power profile retains performance as AC default"