Skip to content
Open
Show file tree
Hide file tree
Changes from 4 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
130 changes: 130 additions & 0 deletions bin/omarchy-battery-charge-limit
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
#!/bin/bash

# omarchy:summary=Read or change battery charge limits through UPower
# omarchy:args=[status|on|off|toggle] [--shell]

set -euo pipefail

action=status
action_seen=false
shell_output=false
for argument in "$@"; do
case $argument in
--shell) shell_output=true ;;
status | on | off | toggle)
if [[ $action_seen == "true" ]]; then
echo "Specify only one charge-limit action." >&2
exit 2
fi
action=$argument
action_seen=true
;;
*)
echo "Usage: omarchy-battery-charge-limit [status|on|off|toggle] [--shell]" >&2
exit 2
;;
esac
done

service=org.freedesktop.UPower
interface=org.freedesktop.UPower.Device

# Read the capability and state together. UPower owns the hardware-specific
# thresholds, charging modes, authorization and persistence.
read_battery() {
# Settings mask: 1 = start threshold, 2 = end threshold, 4 = firmware policy.
# A numeric property alone is not evidence that the hardware uses it.
busctl --system --json=short call "$service" "$1" org.freedesktop.DBus.Properties GetAll s "$interface" |
jq -r '
def percent: type == "number" and . > 0 and . < 100 and floor == .;
.data[0] | select(.Type.data == 2 and .PowerSupply.data == true and .IsPresent.data == true and .ChargeThresholdSupported.data == true)
| (if .ChargeThresholdEnabled.data == true then "on"
elif .ChargeThresholdEnabled.data == false then "off"
else error("Missing charge-limit state") end) as $state
| (.ChargeThresholdSettingsSupported.data // 0) as $raw_settings
| (if ($raw_settings | type) == "number" and $raw_settings >= 0 then $raw_settings else 0 end) as $settings
| (.ChargeStartThreshold.data // 0) as $start
| (.ChargeEndThreshold.data // 0) as $end
| (if (($settings / 2 | floor) % 2 == 1) and ($end | percent) then
if ($settings % 2 == 1) and ($start | percent) and $start < $end then "range" else "end" end
elif ($settings / 4 | floor) % 2 == 1 then "firmware"
else "unknown" end) as $policy
| [$state, $policy, (if $policy == "range" then $start else 0 end),
(if $policy == "end" or $policy == "range" then $end else 0 end)] | @tsv'
}

devices=$(busctl --system --json=short call "$service" /org/freedesktop/UPower "$service" EnumerateDevices |
jq -r '.data[0][]')

batteries=()
states=()
policies=()
while IFS= read -r device; do
[[ -n $device ]] || continue
reading=$(read_battery "$device")
[[ -n $reading ]] || continue
read -r state policy start end <<<"$reading"
batteries+=("$device")
states+=("$state")
policies+=("$policy $start $end")
done <<<"$devices"

state=unsupported
policy=unknown
start=0
end=0
if (( ${#batteries[@]} == 0 )); then
if [[ $action != "status" ]]; then
echo "Battery charge limits are unavailable." >&2
exit 1
fi
else
state=${states[0]}
for value in "${states[@]}"; do
[[ $value == "$state" ]] || state=mixed
done
if [[ $action == "toggle" ]]; then
if [[ $state == "on" ]]; then
action=off
else
action=on
fi
fi

if [[ $action != "status" ]]; then
if [[ $action == "on" ]]; then
enabled=true
else
enabled=false
fi

for index in "${!batteries[@]}"; do
[[ ${states[index]} != "$action" ]] || continue
busctl --system call "$service" "${batteries[index]}" "$interface" EnableChargeThreshold b "$enabled"
reading=$(read_battery "${batteries[index]}")
read -r actual policy start end <<<"$reading"
if [[ $actual != "$action" ]]; then
echo "Could not confirm the battery charge limit." >&2
exit 1
fi
policies[index]="$policy $start $end"
done
state=$action
fi

read -r policy start end <<<"${policies[0]}"
for value in "${policies[@]}"; do
if [[ $value != "${policies[0]}" ]]; then
policy=different
start=0
end=0
break
fi
done
fi

if [[ $shell_output == "true" ]]; then
printf 'state\t%s\npolicy\t%s\nstart\t%s\nend\t%s\n' "$state" "$policy" "$start" "$end"
else
echo "$state"
fi
8 changes: 8 additions & 0 deletions default/i18n/en/shell.json
Original file line number Diff line number Diff line change
Expand Up @@ -469,6 +469,14 @@
"power.fullyCharged": "Fully charged",
"power.holding": "Holding",
"power.onBattery": "On battery",
"power.chargeLimitRange": "Start below %1% · stop at %2%",
"power.chargeLimitEnd": "Maximum %1%",
"power.chargeLimitDefault": "Device default",
"power.chargeLimitDifferent": "Separate limits per battery",
"power.chargeLimitMixed": "Enabled on some batteries",
"power.chargeLimitReadFailed": "Couldn't read charging settings. Reopen to retry.",
"power.chargeLimitLastKnown": "Unavailable · last known state",
"power.chargeLimitFailed": "Couldn't apply the setting. Try again.",
"power.powerProfile": "POWER PROFILE",
"power.profileBalanced": "Balanced",
"power.profilePerformance": "Performance",
Expand Down
2 changes: 1 addition & 1 deletion manual/05-the-top-bar.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ 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, switches power profiles (it remembers a separate choice for battery and AC), and prints some system info. On supported machines, **Charge limit** limits charging using the laptop’s battery protection settings; turning it off allows a full charge. It applies to every supported system battery. The panel shows the stopping percentage or start/stop range when the hardware reports it; firmware-controlled limits are shown without a guessed percentage. Batteries can have different limits. If settings cannot be read, the control is disabled until a successful refresh or reopening the panel. Use Up/Down to move between power profiles and the charge limit, Left/Right to select off/on, or Enter/Space to toggle it. The command `omarchy battery charge-limit toggle` also switches the protection on or off.
- **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.
- **World clock** keeps a row per city, with its weather and how its day is going. Search finds towns as well as time zones, so Fort Lauderdale is Fort Lauderdale and not New York. If the line at the top names the wrong city, click it and say where you are; pick somewhere on another time zone and the system clock moves there too, which is handy when you travel. Hover a city and click the person button to say who lives there — plain names, or `@` GitHub handles to bring their faces along.
Expand Down
63 changes: 63 additions & 0 deletions shell/plugins/panels/power/Model.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,64 @@ function parseProfiles(raw, previousIndex) {
}
}

function parseChargeLimit(raw) {
var info = parseKeyValue(raw)
var state = info.state
if (state !== "on" && state !== "off" && state !== "mixed" && state !== "unsupported") return null

var policy = info.policy
var start = Number(info.start) || 0
var end = Number(info.end) || 0
var percentage = function(value) { return Number.isInteger(value) && value > 0 && value < 100 }
if (state === "unsupported") policy = "unknown"
if (policy === "range" && !(percentage(start) && percentage(end) && start < end)) policy = "unknown"
if (policy === "end" && !percentage(end)) policy = "unknown"
if (policy !== "range" && policy !== "end" && policy !== "firmware" && policy !== "different") policy = "unknown"
return { state: state, policy: policy, start: policy === "range" ? start : 0, end: policy === "range" || policy === "end" ? end : 0 }
}

// stdout completion and process exit can arrive in either order. An empty
// failed read must not replace the last good state with "unsupported".
function chargeLimitReadResult(raw, exitCode) {
if (raw === null || exitCode === null) return null
var info = exitCode === 0 ? parseChargeLimit(raw) : null
return { failed: info === null, info: info }
}

function chargeLimitDescription(info, tr, fmt) {
var t = typeof tr === "function" ? tr : function(key, english) { return english }
var number = typeof fmt === "function" ? fmt : String
var limit = info || {}
if (limit.state === "unsupported") return ""
if (limit.state === "mixed") return t("power.chargeLimitMixed", "Enabled on some batteries")
if (limit.policy === "range") {
var range = t("power.chargeLimitRange", "Start below %1% · stop at %2%")
return range.replace("%1", number(limit.start)).replace("%2", number(limit.end))
}
if (limit.policy === "end") {
var end = t("power.chargeLimitEnd", "Maximum %1%")
return end.replace("%1", number(limit.end))
}
if (limit.policy === "different") {
return t("power.chargeLimitDifferent", "Separate limits per battery")
}
return t("power.chargeLimitDefault", "Device default")
}

function movePowerCursor(cursor, dx, dy, chargeLimitAvailable, profiles) {
var focused = chargeLimitAvailable && cursor.chargeFocused
var index = cursor.profileIndex
var action = ""
if (chargeLimitAvailable && dy !== 0) focused = dy > 0
else if (focused && dx !== 0) action = dx > 0 ? "on" : "off"
else if (!focused) index = selectProfileIndex(index, dx !== 0 ? dx : dy, profiles)
return { chargeFocused: !!focused, profileIndex: index, chargeAction: action }
}

function chargeLimitEvent(line) {
return /Charge(?:Start|End)?Threshold|\b(?:IsPresent|PowerSupply|Type)\b|\.Device(?:Added|Removed)\b|owned by/.test(String(line || ""))
}

function profileIcon(name) {
if (name === "power-saver") return "󰌪"
if (name === "balanced") return "󰊚"
Expand Down Expand Up @@ -116,6 +174,11 @@ if (typeof module !== "undefined") {
selectProfileIndex: selectProfileIndex,
parseKeyValue: parseKeyValue,
parseProfiles: parseProfiles,
parseChargeLimit: parseChargeLimit,
chargeLimitReadResult: chargeLimitReadResult,
chargeLimitDescription: chargeLimitDescription,
movePowerCursor: movePowerCursor,
chargeLimitEvent: chargeLimitEvent,
profileIcon: profileIcon,
batteryFraction: batteryFraction,
chargeThresholdActive: chargeThresholdActive,
Expand Down
Loading