Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
88 changes: 81 additions & 7 deletions bin/omarchy-battery-status
Original file line number Diff line number Diff line change
Expand Up @@ -41,15 +41,23 @@ format_duration() {
# that BAT*: Apple Silicon reports battery_macsmc_battery. Match on the class,
# then take the first one that powers the machine: a wireless mouse or keyboard
# is a battery_ device too, and UPower marks it "power supply: no".
#
# A laptop can have more than one (ThinkPads with an internal and a removable
# battery). The first stays the one whose charge limit and cycle count are
# shown; the others join its totals further down.
battery=""
battery_info=""
other_battery_infos=()
while read -r candidate; do
[[ -n $candidate ]] || continue
candidate_info=$(upower -i "$candidate" 2>/dev/null) || continue
if grep -qE '^\s*power supply:\s+yes' <<<"$candidate_info"; then
battery=$candidate
battery_info=$candidate_info
break
if [[ -z $battery ]]; then
battery=$candidate
battery_info=$candidate_info
else
other_battery_infos+=("$candidate_info")
fi
fi
done < <(upower -e 2>/dev/null | grep '/battery_')
[[ -z $battery ]] && exit 0
Expand Down Expand Up @@ -78,10 +86,19 @@ read_sysfs_number() {
# UPower's energy-rate can lag the kernel telemetry by tens of seconds. Use
# the instantaneous sysfs reading when there is one so the open panel stays
# live; without one, UPower's rate, worked out from the falling charge, stands.
if microwatts=$(read_sysfs_number "$battery_path/power_now"); then
power_rate_raw=$(awk -v microwatts="$microwatts" 'BEGIN { print microwatts / 1000000 }')
elif microamps=$(read_sysfs_number "$battery_path/current_now") && microvolts=$(read_sysfs_number "$battery_path/voltage_now"); then
power_rate_raw=$(awk -v microamps="$microamps" -v microvolts="$microvolts" 'BEGIN { print microamps * microvolts / 1000000000000 }')
live_rate() {
local path=$1 microwatts microamps microvolts
if microwatts=$(read_sysfs_number "$path/power_now"); then
awk -v microwatts="$microwatts" 'BEGIN { print microwatts / 1000000 }'
elif microamps=$(read_sysfs_number "$path/current_now") && microvolts=$(read_sysfs_number "$path/voltage_now"); then
awk -v microamps="$microamps" -v microvolts="$microvolts" 'BEGIN { print microamps * microvolts / 1000000000000 }'
else
return 1
fi
}

if live_rate_raw=$(live_rate "$battery_path"); then
power_rate_raw=$live_rate_raw
fi

# Some kernels sign power_now by direction (negative while discharging on
Expand All @@ -93,6 +110,62 @@ power_rate=$(awk -v rate="${power_rate_raw:-0}" 'BEGIN {
print rounded
}')
state=$(awk '/state/ { print $2; exit }' <<<"$battery_info")

# With more than one battery the reading is the machine's, not the first
# battery's: energy, capacity and draw add up, the percentage is worked out
# from the totals as UPower's own display device does, and the machine is
# discharging or charging when any battery is. Each battery keeps a line of
# its own for the power panel.
battery_lines=()
if (( ${#other_battery_infos[@]} > 0 )); then
battery_line() {
awk -v name="$1" -v percentage="$2" -v state="$3" -v rate="${4:-0}" 'BEGIN {
if (rate < 0) rate = -rate
rounded = sprintf("%.1f", rate)
sub(/\.0$/, "", rounded)
printf "battery.%s\t%d%%;%s;%sW", name, percentage, state, rounded
}'
}

battery_lines+=("$(battery_line "$native_path" "$percentage" "$state" "$power_rate_raw")")
states=" $state "

for other_info in "${other_battery_infos[@]}"; do
other_path=$(awk '/native-path/ { print $2; exit }' <<<"$other_info")
other_state=$(awk '/state/ { print $2; exit }' <<<"$other_info")
other_rate=$(live_rate "$power_supply_path/$other_path") || other_rate=$(awk '/energy-rate/ { print $2; exit }' <<<"$other_info")
battery_lines+=("$(battery_line "$other_path" "$(awk '/percentage/ { print int($2); exit }' <<<"$other_info")" "$other_state" "$other_rate")")
states+="$other_state "

read -r energy energy_full energy_full_design power_rate_raw < <(awk \
-v energy="$energy" -v full="$energy_full" -v design="$energy_full_design" -v rate="${power_rate_raw:-0}" -v other_rate="${other_rate:-0}" '
/^ *energy:/ { energy += $2 }
/energy-full:/ { full += $2 }
/energy-full-design:/ { design += $2 }
Comment on lines +140 to +144

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Charging time uses wrong limit

The combined charging estimate still uses only the first battery's charge limit. If BAT0 holds 16Wh of 20Wh at an 80% limit and BAT1 charges from 30Wh toward 60Wh at 10W, the new totals produce 1h 48m instead of 3h. Add each battery's remaining energy up to its own limit rather than applying the first battery's limit to the combined capacity.

Prompt To Fix With AI
This is a comment left during a code review.
Path: bin/omarchy-battery-status
Line: 140-144

Comment:
**Charging time uses wrong limit**

The combined charging estimate still uses only the first battery's charge limit. If `BAT0` holds 16Wh of 20Wh at an 80% limit and `BAT1` charges from 30Wh toward 60Wh at 10W, the new totals produce 1h 48m instead of 3h. Add each battery's remaining energy up to its own limit rather than applying the first battery's limit to the combined capacity.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

END {
if (rate < 0) rate = -rate
if (other_rate < 0) other_rate = -other_rate
print energy + 0, full + 0, design + 0, rate + other_rate
}' <<<"$other_info")
done

if awk -v full="$energy_full" 'BEGIN { exit !(full > 0) }'; then
percentage=$(awk -v energy="$energy" -v full="$energy_full" 'BEGIN { print int(energy / full * 100) }')
Comment on lines +148 to +153

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Unknown charge becomes zero

The new sum turns a missing energy reading into zero. The script already supports missing energy by using UPower's time estimate. If two batteries provide capacity and percentage but omit energy, the combined percentage becomes 0%, and the time estimate disappears. Keep track of missing readings and avoid replacing them with a measured zero.

Prompt To Fix With AI
This is a comment left during a code review.
Path: bin/omarchy-battery-status
Line: 148-153

Comment:
**Unknown charge becomes zero**

The new sum turns a missing energy reading into zero. The script already supports missing energy by using UPower's time estimate. If two batteries provide capacity and percentage but omit energy, the combined percentage becomes 0%, and the time estimate disappears. Keep track of missing readings and avoid replacing them with a measured zero.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

capacity=$(awk -v full="$energy_full" 'BEGIN { printf "%d", full }')
fi

if [[ $states == *" discharging "* ]]; then
state="discharging"
elif [[ $states == *" charging "* ]]; then
state="charging"
fi

power_rate=$(awk -v rate="$power_rate_raw" 'BEGIN {
rounded = sprintf("%.1f", rate)
sub(/\.0$/, "", rounded)
print rounded
}')
fi
upower_threshold_start=$(awk '/charge-start-threshold:/ { gsub(/%/, "", $2); print int($2); exit }' <<<"$battery_info")
upower_threshold_end=$(awk '/charge-end-threshold:/ { gsub(/%/, "", $2); print int($2); exit }' <<<"$battery_info")
upower_threshold_enabled=$(awk '/charge-threshold-enabled:/ { print tolower($2); exit }' <<<"$battery_info")
Expand Down Expand Up @@ -206,6 +279,7 @@ if [[ $shell_output == "true" ]]; then
printf 'rate\t%s\n' "${power_rate}W"
printf 'size\t%s\n' "${capacity}Wh"
printf 'time\t%s\n' "$time_remaining"
(( ${#battery_lines[@]} == 0 )) || printf '%s\n' "${battery_lines[@]}"

health=$(compute_health "$energy_full" "$energy_full_design" "$upower_capacity")
if [[ -z $health ]]; then
Expand Down
24 changes: 24 additions & 0 deletions shell/plugins/panels/power/Model.js
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,28 @@ function localizeReading(raw, fmt) {
})
}

// A laptop with more than one battery gets a "battery.<name>" line for each
// from omarchy-battery-status --shell: "89%;discharging;14W". One battery has
// none, and so no rows of its own in the panel.
function parseBatteries(batteryInfo) {
var info = batteryInfo || {}
return Object.keys(info).filter(function(key) {
return key.indexOf("battery.") === 0
}).sort().map(function(key) {
var parts = String(info[key]).split(";")
return { name: key.substring(8), percentage: parts[0] || "", state: parts[1] || "", rate: parts[2] || "" }
})
}

// "89% ↓ 14W": the charge, then which way the power flows and how fast, for a
// battery that is charging or discharging.
function batteryReading(battery, fmt) {
var arrow = battery.state === "charging" ? "↑" : (battery.state === "discharging" ? "↓" : "")
var reading = battery.percentage
if (arrow !== "" && parseFloat(battery.rate) > 0) reading += " " + arrow + " " + battery.rate
return localizeReading(reading, fmt)
}

function profileLabel(name, tr) {
var t = typeof tr === "function" ? tr : function(key, english) { return english }
var value = String(name || "")
Expand Down Expand Up @@ -235,6 +257,8 @@ if (typeof module !== "undefined") {
modeLabel: modeLabel,
profileLabel: profileLabel,
localizeReading: localizeReading,
parseBatteries: parseBatteries,
batteryReading: batteryReading,
chargeLimitFraction: chargeLimitFraction,
chargeLimitLabel: chargeLimitLabel,
formatSleepShort: formatSleepShort,
Expand Down
28 changes: 28 additions & 0 deletions shell/plugins/panels/power/Panel.qml
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ Panel {
var device = UPower.displayDevice
return !!(device && device.isPresent)
}
readonly property var batteries: Model.parseBatteries(root.batteryInfo)
readonly property bool chargeLimitSupported: root.batteryInfo.limit_supported === "1"
readonly property bool chargeLimitEnabled: root.activeChargeLimit === "on" || root.activeChargeLimit === "once"
readonly property real chargeLimitFraction: Model.chargeLimitFraction(root.batteryInfo)
Expand Down Expand Up @@ -627,6 +628,33 @@ Panel {
width: parent.width
spacing: Style.space(8)

// Each battery of a laptop that has more than one, under the
// machine's combined reading above.
Grid {
visible: root.batteries.length > 1
width: parent.width
columns: 2
columnSpacing: Style.space(20)
rowSpacing: Style.spacing.labelGap

Repeater {
model: root.batteries

Item {
id: batteryRow
required property var modelData
width: (parent.width - parent.columnSpacing) / 2
implicitHeight: batteryPair.implicitHeight

InfoPair {
id: batteryPair
label: batteryRow.modelData.name
value: Model.batteryReading(batteryRow.modelData, Commons.I18n.formatNumber)
}
}
}
}

Row {
width: parent.width
spacing: Style.space(20)
Expand Down
61 changes: 61 additions & 0 deletions test/shell.d/battery-status-test.sh
Original file line number Diff line number Diff line change
Expand Up @@ -366,3 +366,64 @@ env "${limit_env[@]}" "$ROOT/bin/omarchy-battery-limit" toggle
env "${limit_env[@]}" "$ROOT/bin/omarchy-battery-limit" off
[[ $(env "${limit_env[@]}" "$ROOT/bin/omarchy-battery-limit" status) == "off" ]] || fail "battery-limit disables charge limit"
pass "omarchy-battery-limit handles status, on, off, once, and toggle"

# Two batteries (a ThinkPad's internal and removable pair): the reading is the
# machine's, and each battery keeps a line of its own.
dual_dir=$(mktemp -d)
trap 'rm -rf "$tmp_dir" "$hold_dir" "$dual_dir"' EXIT

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Test files remain

This replaces the earlier exit trap but drops hwdb_dir. Every successful run now leaves that temporary directory and its fixtures behind. Keep hwdb_dir in the cleanup list when adding dual_dir.

Suggested change
trap 'rm -rf "$tmp_dir" "$hold_dir" "$dual_dir"' EXIT
trap 'rm -rf "$tmp_dir" "$hold_dir" "$hwdb_dir" "$dual_dir"' EXIT
Prompt To Fix With AI
This is a comment left during a code review.
Path: test/shell.d/battery-status-test.sh
Line: 373

Comment:
**Test files remain**

This replaces the earlier exit trap but drops `hwdb_dir`. Every successful run now leaves that temporary directory and its fixtures behind. Keep `hwdb_dir` in the cleanup list when adding `dual_dir`.

```suggestion
trap 'rm -rf "$tmp_dir" "$hold_dir" "$hwdb_dir" "$dual_dir"' EXIT
```

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.


mkdir -p "$dual_dir/bin" "$dual_dir/power/BAT0" "$dual_dir/power/BAT1"
printf '0\n' >"$dual_dir/power/BAT0/power_now"
printf '8000000\n' >"$dual_dir/power/BAT1/power_now"
cat >"$dual_dir/bin/upower" <<'STUB'
#!/bin/bash
if [[ $1 == "-e" ]]; then
echo "/org/freedesktop/UPower/devices/battery_BAT0"
echo "/org/freedesktop/UPower/devices/battery_BAT1"
exit 0
fi
if [[ $1 == "-i" && $2 == */battery_BAT0 ]]; then
cat <<'INFO'
native-path: BAT0
power supply: yes
state: fully-charged
energy: 20 Wh
energy-full: 20 Wh
energy-full-design: 24 Wh
energy-rate: 0 W
percentage: 100%
INFO
exit 0
fi
if [[ $1 == "-i" ]]; then
cat <<'INFO'
native-path: BAT1
power supply: yes
state: discharging
energy: 30 Wh
energy-full: 60 Wh
energy-full-design: 72 Wh
energy-rate: 8 W
percentage: 50%
INFO
exit 0
fi
exit 1
STUB
chmod +x "$dual_dir/bin/upower"

dual_output=$(OMARCHY_POWER_SUPPLY_PATH="$dual_dir/power" PATH="$dual_dir/bin:$PATH" "$ROOT/bin/omarchy-battery-status" --shell)
grep -Fx $'percentage\t62%' <<<"$dual_output" >/dev/null || fail "two batteries report their combined charge" "$dual_output"
grep -Fx $'state\tdischarging' <<<"$dual_output" >/dev/null || fail "two batteries are discharging when either is" "$dual_output"
grep -Fx $'rate\t8W' <<<"$dual_output" >/dev/null || fail "two batteries report their combined draw" "$dual_output"
grep -Fx $'size\t80Wh' <<<"$dual_output" >/dev/null || fail "two batteries report their combined capacity" "$dual_output"
grep -Fx $'time\t6h 15m' <<<"$dual_output" >/dev/null || fail "two batteries count the time left from the combined energy" "$dual_output"
grep -Fx $'health\t83%' <<<"$dual_output" >/dev/null || fail "two batteries report their combined health" "$dual_output"
grep -Fx $'battery.BAT0\t100%;fully-charged;0W' <<<"$dual_output" >/dev/null || fail "the first battery keeps a line of its own" "$dual_output"
grep -Fx $'battery.BAT1\t50%;discharging;8W' <<<"$dual_output" >/dev/null || fail "the second battery keeps a line of its own" "$dual_output"
! grep -q $'^battery\\.' <<<"$shell_output" || fail "a single battery has no per-battery lines" "$shell_output"
pass "battery status adds up a laptop's batteries and lists each one"
8 changes: 8 additions & 0 deletions test/shell.d/power-test.sh
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,14 @@ assertEqual(power.modeLabel({ isPresent: true, percentage: 1, state: states.Full
assertEqual(power.localizeReading('13.1W'), '13.1W', 'power keeps battery readings in English digits by default')
assertEqual(power.localizeReading('75-80%', function(v, d) { return '<' + v + '>' }), '<75>-<80>%', 'power localizes every number in a battery reading')
assertEqual(power.localizeReading('13.10W', function(v, d) { return v.toFixed(d).replace('.', ',') }), '13,10W', 'power keeps a reading\'s decimals when localizing')
assertDeepEqual(
power.parseBatteries({ percentage: '25%', 'battery.BAT1': '5%;pending-charge;0W', 'battery.BAT0': '89%;discharging;14W' }),
[{ name: 'BAT0', percentage: '89%', state: 'discharging', rate: '14W' }, { name: 'BAT1', percentage: '5%', state: 'pending-charge', rate: '0W' }],
'power lists each battery of a laptop with more than one'
)
assertDeepEqual(power.parseBatteries({ percentage: '51%' }), [], 'power lists no batteries for a laptop with one')
assertEqual(power.batteryReading({ percentage: '89%', state: 'discharging', rate: '14W' }), '89% ↓ 14W', 'power shows a discharging battery with its draw')
assertEqual(power.batteryReading({ percentage: '5%', state: 'pending-charge', rate: '0W' }), '5%', 'power shows an idle battery with its charge alone')
assertEqual(power.localizeReading(undefined), '', 'power reads a missing battery field as empty')
assertEqual(power.modeLabel({ isPresent: true, percentage: 0.5, state: states.Discharging }, true, states), 'On battery', 'power labels battery mode')
assertEqual(power.modeLabel({ isPresent: true, percentage: 0.5, state: states.Discharging }, false, states), 'Charging', 'power treats external power as newer than stale discharging state')
Expand Down