Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
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
10 changes: 8 additions & 2 deletions shell/plugins/services/battery/Service.qml
Original file line number Diff line number Diff line change
Expand Up @@ -89,9 +89,13 @@ Item {
powerProfileReadProcess.running = true
}

function refreshChargeLimit() {
function refreshChargeLimitState() {
topUpOnceFile.reread()
chargeLimitSignals++
}

function refreshChargeLimit() {
refreshChargeLimitState()
checkTopUpOnceRearm()
}

Expand Down Expand Up @@ -119,7 +123,9 @@ Item {

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
Expand Down
10 changes: 10 additions & 0 deletions test/shell.d/battery-test.sh
Original file line number Diff line number Diff line change
Expand Up @@ -98,3 +98,13 @@ assert(
'battery does not re-arm charge limit when one-time top-up is not active'
)
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
120 changes: 120 additions & 0 deletions test/shell.d/fixtures/battery-charge-limit.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
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'<node><interface name="{interface}">{methods}' + "".join(
f'<property name="{name}" type="{value.get_type_string()}" access="read"/>'
for name, value in properties.items()
) + "</interface></node>"
bus.register_object(path, Gio.DBusNodeInfo.new_for_xml(xml).interfaces[0], method_call, get_property)


register(ROOT, UPOWER, """
<method name="EnumerateDevices"><arg type="ao" direction="out"/></method>
<method name="GetDisplayDevice"><arg type="o" direction="out"/></method>
""", {"OnBattery": GLib.Variant("b", False)})
register(BATTERY, DEVICE, """
<method name="EnableChargeThreshold"><arg type="b" direction="in"/></method>
""", 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, [])))


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\nimport "battery" as Battery\nShellRoot { Battery.Service {} }\n')
(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']}"}
with (home / "quickshell.log").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.
GLib.timeout_add(1200, loop.quit)
loop.run()
assert shell.poll() is None, "Quickshell exited before settling"
assert attempts == 1, f"expected one failed charge-limit write, saw {attempts}"
Comment thread
Cynnamoroll marked this conversation as resolved.
Resolved
assert marker.exists(), "a failed write must keep the request pending"

update_percentage(95.0)
GLib.timeout_add(200, loop.quit)
loop.run()
assert attempts == 1, "charging below the limit must not retry"

accept_threshold = True
update_percentage(100.0)
GLib.timeout_add(1000, loop.quit)
loop.run()
assert attempts == 2, f"a new full-charge event must retry exactly once, saw {attempts}"
assert not marker.exists(), "a successful retry must clear the pending request"
except Exception:
log.seek(0)
print(log.read()[-5000:], file=sys.stderr)
raise
finally:
shell.terminate()
shell.wait(timeout=5)