Skip to content

CLI for SidePulse

Python

Keep the internal display off with lid closed

Peter Kuharf939c4ac710b
diff --git a/README.md b/README.md
index 13b4475..91bb708 100644
--- a/README.md
+++ b/README.md
@@ -201,12 +201,15 @@ sidepulse battery leds --device /Volumes/SidePulsePro --full-watts 140
SidePulse Pro uses all eight LEDs as a battery bar. At 50%, LEDs 0-3 are filled;
when charging, LED 4 is the pulsing frontier LED. Live updates ease the whole
-strip into its new base state, then trigger one frontier pulse. The app owns
-the animation cadence by rewriting that one-shot pulse; the device does not run
-a repeated charging loop. Pulse length and rewrite frequency are based on
-charger wattage divided by the laptop's full-speed wattage baseline, so slow
-chargers produce occasional short blinks and full-speed chargers produce a
-steady pulse.
+strip into its new base state, then the device animation engine repeats the
+frontier pulse. Pulse length and the pause between pulses are based on charger
+wattage divided by the laptop's full-speed wattage baseline, so slow chargers
+produce occasional short blinks and full-speed chargers produce a steady pulse.
+The app only rewrites the program when the battery level, charging state,
+charger power, brightness, or selected device changes.
+Power-source changes arrive through the macOS IOKit notification run loop, so
+plug/unplug previews and charging-state changes do not wait for the general
+status refresh. A low-frequency poll remains as a fallback.
Save the status-bar LED display preference:
@@ -640,6 +643,13 @@ and shows the path from provider hook event to interpreted SidePulse status.
The `Keep Awake With Lid Closed` menu section controls the stronger sleep
prevention policy:
+On supported Apple Silicon Macs, SidePulse requests built-in panel power off
+when the lid closes and restores it on opening. This targets the internal
+framebuffer only; external display power, brightness, and layout are untouched.
+The panel control uses the private macOS IOMobileFramebuffer API and logs an
+error if unavailable, without falling back to sleeping all displays. Pending
+panel restoration survives a SidePulse restart.
+
| Choice | Behavior |
| --- | --- |
| Never | Do not use the closed-lid sleep override. |
diff --git a/src/sidepulse/battery.py b/src/sidepulse/battery.py
index 1663423..f5c24d5 100644
--- a/src/sidepulse/battery.py
+++ b/src/sidepulse/battery.py
@@ -295,7 +295,12 @@ def program_for_battery(
pulse_index = min(fill.full, count - 1)
transition = max(0, int(transition_ms))
- if not snapshot.is_plugged or snapshot.is_charged:
+ if (
+ not snapshot.is_plugged
+ or not snapshot.is_charging
+ or snapshot.is_charged
+ or percent >= 100
+ ):
color = battery_color(percent)
if snapshot.is_charged or percent >= 100:
return apply_brightness(
@@ -316,6 +321,9 @@ def program_for_battery(
color = BATTERY_CHARGING_MINT
ratio = snapshot.charge_speed_ratio(full_charge_watts)
pulse_ms = charging_pulse_length_ms(ratio)
+ cycle_ms = round(charging_cycle_seconds(ratio) * 1000)
+ hold_ms = max(0, cycle_ms - transition - pulse_ms)
+ frontier_color = battery_fill_color(pulse_index, fill, color)
lines = [
";".join(
battery_segment(
@@ -326,11 +334,10 @@ def program_for_battery(
for index in range(count)
)
]
- lines.extend(
- [
- f"{pulse_index}:{color} {pulse_ms}ms pulse",
- ]
- )
+ lines.append(f"{pulse_index}:{color} {pulse_ms}ms pulse")
+ if hold_ms > 0:
+ lines.append(f"{pulse_index}:{frontier_color} {hold_ms}ms none")
+ lines.append("repeat")
return apply_brightness("\n".join(lines), brightness)
@@ -423,14 +430,12 @@ class BatteryLedController:
self.last_error: str | None = None
self.last_target: Path | None = None
self.last_attempt_monotonic = 0.0
- self.last_write_monotonic = 0.0
def reset(self) -> None:
self.last_program = None
self.last_error = None
self.last_target = None
self.last_attempt_monotonic = 0.0
- self.last_write_monotonic = 0.0
def sync_snapshot(self, snapshot: BatterySnapshot) -> BatteryLedWrite:
now = time.monotonic()
@@ -450,11 +455,7 @@ class BatteryLedController:
error=self.last_error,
)
- if (
- program == self.last_program
- and self.last_error is None
- and not should_rewrite_battery_program(snapshot, now - self.last_write_monotonic)
- ):
+ if program == self.last_program and self.last_error is None:
return BatteryLedWrite(
target=self.last_target,
program="",
@@ -493,7 +494,6 @@ class BatteryLedController:
self.last_program = program
self.last_error = None
self.last_target = written_target
- self.last_write_monotonic = now
return BatteryLedWrite(
target=written_target,
program=program,
@@ -549,17 +549,11 @@ def charging_pulse_length_ms(ratio: float) -> int:
return round(180 + (1220 * speed))
-def charging_update_interval_seconds(ratio: float) -> float:
+def charging_cycle_seconds(ratio: float) -> float:
speed = clamp(ratio)
return max(0.9, 3.0 - (2.1 * speed))
-def should_rewrite_battery_program(snapshot: BatterySnapshot, elapsed_seconds: float) -> bool:
- if not snapshot.is_plugged or snapshot.is_charged:
- return False
- return elapsed_seconds >= charging_update_interval_seconds(snapshot.charge_speed_ratio())
-
-
def parse_full_watts(value: str | float | int | None) -> float | None:
if value is None:
return None
diff --git a/src/sidepulse/internal_display.py b/src/sidepulse/internal_display.py
new file mode 100644
index 0000000..bad1c57
--- /dev/null
+++ b/src/sidepulse/internal_display.py
@@ -0,0 +1,128 @@
+"""Lid-controlled panel power, without changing brightness or external displays."""
+from __future__ import annotations
+
+import ctypes
+import plistlib
+import subprocess
+from collections.abc import Callable
+from pathlib import Path
+
+from .providers import default_state_dir
+
+
+def builtin_framebuffer_id(entries: list[dict]) -> int:
+ # External framebuffers are named dispext*, even with no monitor attached.
+ matches = [
+ entry["IORegistryEntryID"]
+ for entry in entries
+ if str(entry.get("IONameMatched", "")).split(",")[0] == "disp0"
+ and isinstance(entry.get("IORegistryEntryID"), int)
+ ]
+ if len(matches) != 1:
+ raise RuntimeError("Could not uniquely identify the built-in framebuffer")
+ return matches[0]
+
+
+class BuiltinPanelPower:
+ """Lazy, process-lifetime connection to the Apple Silicon internal panel.
+
+ IOMobileFramebuffer is a private macOS API. Unsupported hardware fails
+ closed: never fall back to a command that sleeps every display.
+ """
+
+ def __init__(self) -> None:
+ self._framebuffer = None
+ self._unavailable_error: RuntimeError | None = None
+
+ def _connect(self) -> None:
+ result = subprocess.run(
+ ["/usr/sbin/ioreg", "-a", "-r", "-c", "IOMobileFramebuffer", "-d", "1"],
+ check=True, capture_output=True, timeout=3,
+ )
+ registry_id = builtin_framebuffer_id(plistlib.loads(result.stdout))
+ iokit = ctypes.CDLL("/System/Library/Frameworks/IOKit.framework/IOKit")
+ panel = ctypes.CDLL(
+ "/System/Library/PrivateFrameworks/IOMobileFramebuffer.framework/IOMobileFramebuffer"
+ )
+ system = ctypes.CDLL("/usr/lib/libSystem.B.dylib")
+ iokit.IORegistryEntryIDMatching.argtypes = [ctypes.c_uint64]
+ iokit.IORegistryEntryIDMatching.restype = ctypes.c_void_p
+ iokit.IOServiceGetMatchingService.argtypes = [ctypes.c_uint32, ctypes.c_void_p]
+ iokit.IOServiceGetMatchingService.restype = ctypes.c_uint32
+ iokit.IOObjectRelease.argtypes = [ctypes.c_uint32]
+ panel.IOMobileFramebufferOpen.argtypes = [
+ ctypes.c_uint32, ctypes.c_uint32, ctypes.c_uint32,
+ ctypes.POINTER(ctypes.c_void_p),
+ ]
+ panel.IOMobileFramebufferOpen.restype = ctypes.c_int32
+ panel.IOMobileFramebufferRequestPowerChange.argtypes = [ctypes.c_void_p, ctypes.c_uint32]
+ panel.IOMobileFramebufferRequestPowerChange.restype = ctypes.c_int32
+ service = iokit.IOServiceGetMatchingService(0, iokit.IORegistryEntryIDMatching(registry_id))
+ if not service:
+ raise RuntimeError("Built-in framebuffer service disappeared")
+ framebuffer = ctypes.c_void_p()
+ try:
+ task = ctypes.c_uint32.in_dll(system, "mach_task_self_").value
+ status = panel.IOMobileFramebufferOpen(service, task, 0, ctypes.byref(framebuffer))
+ if status or not framebuffer.value:
+ raise RuntimeError(f"Opening built-in framebuffer failed: {status}")
+ finally:
+ iokit.IOObjectRelease(service)
+ self._panel = panel
+ self._framebuffer = framebuffer
+
+ def __call__(self, on: bool) -> None:
+ if self._unavailable_error is not None:
+ raise self._unavailable_error
+ if self._framebuffer is None:
+ try:
+ self._connect()
+ except Exception as exc:
+ # There is no useful retry for a missing private framework or
+ # a Mac without the Apple Silicon internal framebuffer. Cache
+ # that result so lid polling never blocks the app repeatedly.
+ self._unavailable_error = RuntimeError(str(exc))
+ raise self._unavailable_error from exc
+ status = self._panel.IOMobileFramebufferRequestPowerChange(self._framebuffer, int(on))
+ if status:
+ raise RuntimeError(f"Built-in panel power request failed: {status}")
+
+
+class InternalDisplayController:
+ def __init__(
+ self, set_power: Callable[[bool], None] | None = None,
+ *, recovery_path: Path | None = None,
+ ) -> None:
+ self.set_power = set_power or BuiltinPanelPower()
+ self.recovery_path = recovery_path or default_state_dir() / "internal-panel-off"
+ self.powered_off = self.recovery_path.exists()
+ self._applied = False
+ self.last_error: str | None = None
+
+ def update(self, lid_closed: bool | None) -> bool:
+ if lid_closed is None:
+ return False
+ # On launch with an open lid, leave the user's display state alone.
+ if lid_closed == self.powered_off and (self._applied or not lid_closed):
+ return False
+ self._applied = False
+ try:
+ if lid_closed:
+ # Record intent before the native call, so a crash or uncertain
+ # API result can still be recovered after the lid opens.
+ self.recovery_path.parent.mkdir(parents=True, exist_ok=True)
+ self.recovery_path.touch()
+ self.powered_off = True
+ self.set_power(not lid_closed)
+ if not lid_closed:
+ self.recovery_path.unlink(missing_ok=True)
+ except Exception as exc:
+ self.last_error = str(exc)
+ return False
+ self.powered_off = lid_closed
+ self._applied = True
+ self.last_error = None
+ return True
+
+ def release(self) -> None:
+ self.update(False)
diff --git a/src/sidepulse/keep_awake.py b/src/sidepulse/keep_awake.py
index cc972da..74cd3c6 100644
--- a/src/sidepulse/keep_awake.py
+++ b/src/sidepulse/keep_awake.py
@@ -15,7 +15,7 @@ AWAKE_GRACE_SECONDS = 300.0
SD_STATUS_READ_SECONDS = 60.0
KEEPALIVE_FILE_NAME = "keepalive"
STATUS_FILE_NAME = KEEPALIVE_FILE_NAME
-CAFFEINATE_COMMAND = ("/usr/bin/caffeinate", "-imsu")
+CAFFEINATE_COMMAND = ("/usr/bin/caffeinate", "-ims")
class KeepAwakeController:
diff --git a/src/sidepulse/lid_sleep.py b/src/sidepulse/lid_sleep.py
index b341d47..8ae08af 100644
--- a/src/sidepulse/lid_sleep.py
+++ b/src/sidepulse/lid_sleep.py
@@ -17,7 +17,7 @@ from .settings import (
)
-CAFFEINATE_CLOSED_LID_COMMAND = ("/usr/bin/caffeinate", "-imsu")
+CAFFEINATE_CLOSED_LID_COMMAND = ("/usr/bin/caffeinate", "-ims")
IOREG_CLAMSHELL_COMMAND = ("/usr/sbin/ioreg", "-r", "-k", "AppleClamshellState", "-d", "4")
IOREG_SLEEP_DISABLED_COMMAND = ("/usr/sbin/ioreg", "-r", "-k", "SleepDisabled", "-d", "4")
PMSET_ASSERTIONS_COMMAND = ("/usr/bin/pmset", "-g", "assertions")
diff --git a/src/sidepulse/power_source_notifications.py b/src/sidepulse/power_source_notifications.py
new file mode 100644
index 0000000..28a5f2b
--- /dev/null
+++ b/src/sidepulse/power_source_notifications.py
@@ -0,0 +1,107 @@
+from __future__ import annotations
+
+import ctypes
+import sys
+from collections.abc import Callable
+
+
+IOKIT_FRAMEWORK = "/System/Library/Frameworks/IOKit.framework/IOKit"
+CORE_FOUNDATION_FRAMEWORK = (
+ "/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation"
+)
+PowerSourceCallback = ctypes.CFUNCTYPE(None, ctypes.c_void_p)
+
+
+class PowerSourceNotifier:
+ """Deliver macOS power-source changes on the application's main run loop."""
+
+ def __init__(self, callback: Callable[[], None]) -> None:
+ self.callback = callback
+ self.last_error: str | None = None
+ self._iokit = None
+ self._core_foundation = None
+ self._callback_ref = None
+ self._source = None
+ self._run_loop = None
+ self._modes = None
+
+ def start(self) -> bool:
+ if self._source is not None:
+ return True
+ if sys.platform != "darwin":
+ self.last_error = "power-source notifications require macOS"
+ return False
+
+ try:
+ from AppKit import NSEventTrackingRunLoopMode
+
+ iokit = ctypes.CDLL(IOKIT_FRAMEWORK)
+ core_foundation = ctypes.CDLL(CORE_FOUNDATION_FRAMEWORK)
+
+ create_source = iokit.IOPSNotificationCreateRunLoopSource
+ create_source.argtypes = [PowerSourceCallback, ctypes.c_void_p]
+ create_source.restype = ctypes.c_void_p
+ core_foundation.CFRunLoopGetMain.restype = ctypes.c_void_p
+ core_foundation.CFRunLoopAddSource.argtypes = [
+ ctypes.c_void_p,
+ ctypes.c_void_p,
+ ctypes.c_void_p,
+ ]
+ core_foundation.CFRunLoopRemoveSource.argtypes = [
+ ctypes.c_void_p,
+ ctypes.c_void_p,
+ ctypes.c_void_p,
+ ]
+ core_foundation.CFRelease.argtypes = [ctypes.c_void_p]
+
+ callback_ref = PowerSourceCallback(self._notify)
+ source = create_source(callback_ref, None)
+ if not source:
+ raise RuntimeError("IOKit did not create a notification source")
+ run_loop = core_foundation.CFRunLoopGetMain()
+ common_mode = ctypes.c_void_p.in_dll(
+ core_foundation,
+ "kCFRunLoopCommonModes",
+ ).value
+ event_tracking_mode = NSEventTrackingRunLoopMode.__c_void_p__().value
+ if not run_loop or not common_mode or not event_tracking_mode:
+ core_foundation.CFRelease(source)
+ raise RuntimeError("Core Foundation main run loop is unavailable")
+
+ for mode in (common_mode, event_tracking_mode):
+ core_foundation.CFRunLoopAddSource(run_loop, source, mode)
+ except Exception as exc:
+ self.last_error = str(exc)
+ return False
+
+ self._iokit = iokit
+ self._core_foundation = core_foundation
+ self._callback_ref = callback_ref
+ self._source = source
+ self._run_loop = run_loop
+ self._modes = (common_mode, event_tracking_mode)
+ self.last_error = None
+ return True
+
+ def stop(self) -> None:
+ if self._source is None or self._core_foundation is None:
+ return
+ for mode in self._modes or ():
+ self._core_foundation.CFRunLoopRemoveSource(
+ self._run_loop,
+ self._source,
+ mode,
+ )
+ self._core_foundation.CFRelease(self._source)
+ self._source = None
+ self._run_loop = None
+ self._modes = None
+ self._callback_ref = None
+ self._core_foundation = None
+ self._iokit = None
+
+ def _notify(self, _context) -> None:
+ try:
+ self.callback()
+ except Exception as exc:
+ self.last_error = str(exc)
diff --git a/src/sidepulse/status_bar.py b/src/sidepulse/status_bar.py
index 32d7b9c..c629490 100644
--- a/src/sidepulse/status_bar.py
+++ b/src/sidepulse/status_bar.py
@@ -9,6 +9,7 @@ import threading
import time
from dataclasses import dataclass
from datetime import datetime, timezone
+from functools import lru_cache
from pathlib import Path
try:
@@ -17,8 +18,11 @@ try:
NSApp,
NSApplication,
NSApplicationActivationPolicyAccessory,
+ NSAppearanceNameAqua,
+ NSAppearanceNameDarkAqua,
NSAlert,
NSAlertFirstButtonReturn,
+ NSAffineTransform,
NSBackingStoreBuffered,
NSBezierPath,
NSBezelStyleRounded,
@@ -26,11 +30,13 @@ try:
NSButtonTypeSwitch,
NSColor,
NSCompositingOperationSourceOver,
+ NSCompositingOperationSourceIn,
NSEventTrackingRunLoopMode,
NSFont,
NSFontAttributeName,
NSFontWeightBold,
NSForegroundColorAttributeName,
+ NSGraphicsContext,
NSImage,
NSMenu,
NSMenuItem,
@@ -39,6 +45,7 @@ try:
NSOnState,
NSOpenPanel,
NSPopUpButton,
+ NSRectFillUsingOperation,
NSScrollView,
NSSavePanel,
NSSlider,
@@ -76,6 +83,7 @@ from .battery import (
program_for_battery,
read_battery_snapshot,
)
+from .power_source_notifications import PowerSourceNotifier
from .audit import (
append_status_history_record,
default_status_audit_log_path,
@@ -129,6 +137,7 @@ from .virtual_device import (
VirtualLedView,
VirtualStatusDevice,
)
+from .internal_display import InternalDisplayController
from .lid_sleep import (
LID_POLL_SECONDS,
ClosedLidAwakeController,
@@ -350,6 +359,8 @@ STATE_IDLE = StatusBarState("Idle", "circle", 4)
STATE_WORKING = StatusBarState("Working", "arrow.triangle.2.circlepath", 2)
STATE_DONE = StatusBarState("Done", "checkmark.circle", 3)
STATE_ASK = StatusBarState("Ask", "questionmark.circle", 1)
+STATUS_ICON_FRAME_SECONDS = 1.0 / 30.0
+STATUS_ICON_FRAME_COUNT = 48
STATUS_BAR_DEVICE_PRIORITY = ("sidepulsepro", "sidepulsedot", "pulsedot")
STATUS_BAR_KEEPALIVE_VOLUME_NAMES = (
"SidePulsePro",
@@ -357,6 +368,7 @@ STATUS_BAR_KEEPALIVE_VOLUME_NAMES = (
"PulseDot",
)
STATUS_BAR_REFRESH_SECONDS = 15.0
+STATUS_BAR_BATTERY_FALLBACK_POLL_SECONDS = 30.0
STATUS_BAR_DEVICE_POLL_SECONDS = 2.0
STATUS_BAR_SESSION_HISTORY_LIMIT = 10
SIDEPULSE_NOTCH_FEATURE_ENABLED = True
@@ -524,6 +536,17 @@ def format_percent_value(value: float | int) -> str:
return f"{number:.1f}%"
+def schedule_status_bar_timer(interval: float, target, selector: str):
+ """Schedule periodic work while menus and other tracking UI are active."""
+ timer = NSTimer.scheduledTimerWithTimeInterval_target_selector_userInfo_repeats_(
+ interval, target, selector, None, True,
+ )
+ run_loop = NSRunLoop.mainRunLoop()
+ for mode in (NSRunLoopCommonModes, NSEventTrackingRunLoopMode):
+ run_loop.addTimer_forMode_(timer, mode)
+ return timer
+
+
class StatusBarController(NSObject):
def init(self):
self = objc.super(StatusBarController, self).init()
@@ -535,7 +558,11 @@ class StatusBarController(NSObject):
self.monitor = self.build_monitor()
self.event_server = None
self.status_item = None
+ self.status_icon_timer = None
+ self.tracking_status_menu = None
self.timer = None
+ self.battery_timer = None
+ self.power_source_notifier = PowerSourceNotifier(self.power_source_did_change)
self.lid_timer = None
self.device_timer = None
self.agent_animation_preview_timer = None
@@ -561,6 +588,10 @@ class StatusBarController(NSObject):
self.last_snapshot = None
self.last_battery_snapshot = None
self.last_battery_error = None
+ self.battery_poll_in_flight = False
+ self.battery_poll_pending = False
+ self.pending_battery_snapshot = None
+ self.pending_battery_error = None
self.last_power_connected = None
self.battery_preview_until = 0.0
self.current_state = STATE_IDLE
@@ -577,6 +608,7 @@ class StatusBarController(NSObject):
self.last_led_display_kind = LED_DISPLAY_AGENT
self.last_connected_device_signature = None
self.keep_awake = KeepAwakeController()
+ self.internal_display = InternalDisplayController()
self.closed_lid_awake = ClosedLidAwakeController(
use_system_disable=sleep_helper_installed(),
)
@@ -602,6 +634,8 @@ class StatusBarController(NSObject):
self.lid_poll_backoff_until_monotonic = 0.0
self.pending_lid_closed = None
self.pending_lid_error = None
+ self.pending_lid_panel_error = None
+ self.pending_lid_panel_state = None
self.lid_closed_led_hold_active = False
self.led_animation_until_monotonic = 0.0
self.led_animation_token = 0
@@ -626,26 +660,30 @@ class StatusBarController(NSObject):
log_status_bar("status item created")
self.refresh_(None)
- self.timer = NSTimer.scheduledTimerWithTimeInterval_target_selector_userInfo_repeats_(
+ self.timer = schedule_status_bar_timer(
STATUS_BAR_REFRESH_SECONDS,
self,
"refresh:",
- None,
- True,
)
- self.lid_timer = NSTimer.scheduledTimerWithTimeInterval_target_selector_userInfo_repeats_(
+ if not self.power_source_notifier.start():
+ log_status_bar(
+ "power notification unavailable: "
+ f"{self.power_source_notifier.last_error or 'unknown error'}"
+ )
+ self.battery_timer = schedule_status_bar_timer(
+ STATUS_BAR_BATTERY_FALLBACK_POLL_SECONDS,
+ self,
+ "pollBattery:",
+ )
+ self.lid_timer = schedule_status_bar_timer(
LID_POLL_SECONDS,
self,
"pollLid:",
- None,
- True,
)
- self.device_timer = NSTimer.scheduledTimerWithTimeInterval_target_selector_userInfo_repeats_(
+ self.device_timer = schedule_status_bar_timer(
STATUS_BAR_DEVICE_POLL_SECONDS,
self,
"pollDevices:",
- None,
- True,
)
self.show_setup_window_if_needed()
if SIDEPULSE_NOTCH_FEATURE_ENABLED and self.settings.virtual_status_device_enabled:
@@ -857,6 +895,7 @@ class StatusBarController(NSObject):
self.settings = settings
if self.status_item is not None:
self.status_item.setVisible_(settings.show_menu_bar_icon)
+ self.update_status_icon_animation()
self.refresh_settings_window()
@objc.IBAction
@@ -1084,11 +1123,18 @@ class StatusBarController(NSObject):
@objc.IBAction
def quit_(self, _sender):
+ self.internal_display.release()
self.closed_lid_awake.release()
self.keep_awake.release()
NSApp.terminate_(self)
def applicationWillTerminate_(self, _notification):
+ self.stop_status_icon_animation()
+ self.internal_display.release()
+ self.power_source_notifier.stop()
+ if self.battery_timer is not None:
+ self.battery_timer.invalidate()
+ self.battery_timer = None
self.stop_agent_animation_preview_timer()
self.stop_event_server()
self.closed_lid_awake.release()
@@ -1106,9 +1152,68 @@ class StatusBarController(NSObject):
button.setImage_(image_for_symbol(state.symbol, state.label))
button.setToolTip_(f"SidePulse Agent Monitor: {state.label}")
button.setAccessibilityLabel_(f"SidePulse Agent Monitor: {state.label}")
+ self.update_status_icon_animation()
if previous != state:
log_status_bar(f"state={state.label}")
+ def menuWillOpen_(self, menu):
+ self.tracking_status_menu = menu
+ self.update_status_icon_animation()
+
+ def menuDidClose_(self, menu):
+ if self.tracking_status_menu == menu:
+ self.tracking_status_menu = None
+ self.update_status_icon_animation()
+
+ def stop_status_icon_animation(self) -> None:
+ if self.status_icon_timer is not None:
+ self.status_icon_timer.invalidate()
+ self.status_icon_timer = None
+
+ @objc.IBAction
+ def animateStatusIcons_(self, _timer):
+ self.update_status_icon_animation()
+
+ def update_status_icon_animation(self) -> None:
+ visible = self.status_item is not None and self.status_item.isVisible()
+ rows = []
+ if self.tracking_status_menu is not None:
+ for item in self.tracking_status_menu.itemArray():
+ status = item.representedObject()
+ if isinstance(status, AgentStatus):
+ rows.append((item, status))
+ motion = not NSWorkspace.sharedWorkspace().accessibilityDisplayShouldReduceMotion()
+ animated = motion and (
+ (visible and self.current_state in (STATE_WORKING, STATE_ASK))
+ or any(state_for_mode(status.mode) in (STATE_WORKING, STATE_ASK) for _, status in rows)
+ )
+ if animated and self.status_icon_timer is None:
+ self.status_icon_timer = NSTimer.timerWithTimeInterval_target_selector_userInfo_repeats_(
+ STATUS_ICON_FRAME_SECONDS, self, "animateStatusIcons:", None, True,
+ )
+ self.status_icon_timer.setTolerance_(0.005)
+ run_loop = NSRunLoop.mainRunLoop()
+ run_loop.addTimer_forMode_(self.status_icon_timer, NSRunLoopCommonModes)
+ run_loop.addTimer_forMode_(self.status_icon_timer, NSEventTrackingRunLoopMode)
+ elif not animated:
+ self.stop_status_icon_animation()
+
+ frame = int(time.monotonic() / STATUS_ICON_FRAME_SECONDS) % STATUS_ICON_FRAME_COUNT
+ if visible:
+ state = self.current_state
+ icon = (
+ animated_status_icon(state, frame)
+ if animated and state in (STATE_WORKING, STATE_ASK)
+ else image_for_symbol(state.symbol, state.label)
+ )
+ self.status_item.button().setImage_(icon)
+ if rows:
+ dark_mode = is_dark_appearance(self.tracking_status_menu.effectiveAppearance())
+ for item, status in rows:
+ item.setImage_(session_row_icon_for_status(
+ status, frame if animated else None, dark_mode=dark_mode,
+ ))
+
def build_monitor(self) -> LiveAgentMonitor:
socket_path = default_event_socket_path()
return LiveAgentMonitor(
@@ -2518,11 +2623,78 @@ class StatusBarController(NSObject):
self.last_battery_error = error
return None
+ return self.accept_battery_snapshot(snapshot)
+
+ def accept_battery_snapshot(self, snapshot: BatterySnapshot) -> BatterySnapshot:
self.last_battery_error = None
self.last_battery_snapshot = snapshot
self.update_battery_power_preview(snapshot)
return snapshot
+ @objc.IBAction
+ def pollBattery_(self, _sender):
+ self.poll_battery_once()
+
+ def poll_battery_once(self) -> None:
+ if self.battery_poll_in_flight:
+ self.battery_poll_pending = True
+ return
+ self.battery_poll_in_flight = True
+ threading.Thread(target=self._read_battery_snapshot_async, daemon=True).start()
+
+ def power_source_did_change(self) -> None:
+ self.poll_battery_once()
+
+ def _read_battery_snapshot_async(self) -> None:
+ try:
+ self.pending_battery_snapshot = read_battery_snapshot(
+ full_charge_watts=self.settings.battery_full_charge_watts,
+ )
+ self.pending_battery_error = None
+ except Exception as exc:
+ self.pending_battery_snapshot = None
+ self.pending_battery_error = str(exc)
+ self.performSelectorOnMainThread_withObject_waitUntilDone_(
+ "handleBatterySnapshot:",
+ None,
+ False,
+ )
+
+ def handleBatterySnapshot_(self, _payload) -> None:
+ self.handle_battery_snapshot()
+
+ def handle_battery_snapshot(self) -> None:
+ snapshot = self.pending_battery_snapshot
+ error = self.pending_battery_error
+ self.pending_battery_snapshot = None
+ self.pending_battery_error = None
+ poll_again = self.battery_poll_pending
+ self.battery_poll_pending = False
+ self.battery_poll_in_flight = False
+
+ if snapshot is None:
+ if error and error != self.last_battery_error:
+ log_status_bar(f"battery error: {error}")
+ self.last_battery_error = error
+ if poll_again:
+ self.poll_battery_once()
+ return
+
+ battery_snapshot = self.accept_battery_snapshot(snapshot)
+ mode = (
+ self.last_snapshot.aggregate.mode
+ if self.last_snapshot is not None
+ else AgentMode.IDLE_READY
+ )
+ self.sync_keep_awake(mode, battery_snapshot)
+ self.sync_leds(
+ mode,
+ battery_snapshot,
+ self.active_led_display_kind(battery_snapshot),
+ )
+ if poll_again:
+ self.poll_battery_once()
+
def update_battery_power_preview(self, snapshot: BatterySnapshot) -> None:
plugged = snapshot.is_plugged
if self.last_power_connected is not None and self.last_power_connected != plugged:
@@ -3215,9 +3387,27 @@ class StatusBarController(NSObject):
threading.Thread(target=self._read_lid_closed_async, daemon=True).start()
def _read_lid_closed_async(self) -> None:
+ self.pending_lid_panel_error = None
+ self.pending_lid_panel_state = None
try:
- self.pending_lid_closed = read_lid_closed()
+ closed = read_lid_closed()
+ self.pending_lid_closed = closed
self.pending_lid_error = None
+ panel = getattr(self, "internal_display", None)
+ if panel is not None:
+ previous_error = panel.last_error
+ was_off = panel.powered_off
+ panel.update(closed)
+ self.pending_lid_panel_error = (
+ panel.last_error
+ if panel.last_error != previous_error
+ else None
+ )
+ self.pending_lid_panel_state = (
+ panel.powered_off
+ if panel.last_error is None and (was_off != panel.powered_off or previous_error)
+ else None
+ )
except Exception as exc:
self.pending_lid_closed = None
self.pending_lid_error = str(exc)
@@ -3245,6 +3435,12 @@ class StatusBarController(NSObject):
if closed is None:
return
closed = bool(closed)
+ panel_error = getattr(self, "pending_lid_panel_error", None)
+ panel_state = getattr(self, "pending_lid_panel_state", None)
+ if panel_error:
+ log_status_bar(f"internal_display error: {panel_error}")
+ elif panel_state is not None:
+ log_status_bar(f"internal_display={'off' if panel_state else 'on'}")
self.last_lid_error = None
self.lid_poll_backoff_until_monotonic = 0.0
if self.last_lid_closed is None:
@@ -3403,6 +3599,7 @@ class StatusBarController(NSObject):
def build_menu(snapshot, state: StatusBarState, target: StatusBarController) -> NSMenu:
menu = NSMenu.alloc().init()
+ menu.setDelegate_(target)
menu.addItem_(disabled_menu_item("SidePulse"))
menu.addItem_(NSMenuItem.separatorItem())
@@ -5754,11 +5951,21 @@ def session_open_action_title(status: AgentStatus, action: str, settings=None) -
return session_open_action_label(status, action)
-def session_row_icon_for_status(status: AgentStatus):
+def session_row_icon_for_status(
+ status: AgentStatus, animation_frame: int | None = None, *, dark_mode: bool | None = None,
+):
+ if dark_mode is None:
+ dark_mode = is_dark_appearance()
+ state = state_for_mode(status.mode)
+ if animation_frame is not None and state in (STATE_WORKING, STATE_ASK):
+ return animated_session_row_icon(
+ state, animation_frame, session_origin_icon_for_status(status), dark_mode,
+ )
cache_key = (
status.mode.value,
status.provider.lower(),
normalized_origin_text(status.origin),
+ dark_mode,
)
if cache_key in _session_row_icon_cache:
return _session_row_icon_cache[cache_key]
@@ -5770,7 +5977,7 @@ def session_row_icon_for_status(status: AgentStatus):
elif status_icon is None:
image = origin_icon
else:
- image = horizontal_icon_pair(status_icon, origin_icon)
+ image = horizontal_icon_pair(status_icon, origin_icon, dark_mode=dark_mode)
_session_row_icon_cache[cache_key] = image
return image
@@ -5780,6 +5987,47 @@ def status_icon_for_status(status: AgentStatus):
return image_for_symbol(state.symbol, state.label)
+@lru_cache(maxsize=STATUS_ICON_FRAME_COUNT * 2)
+def animated_status_icon(state: StatusBarState, frame: int):
+ source = image_for_symbol(state.symbol, state.label)
+ if source is None:
+ return None
+ phase = frame / STATUS_ICON_FRAME_COUNT
+ pulse = (1.0 + math.cos(2.0 * math.pi * phase)) / 2.0
+ scale = 1.0 if state == STATE_WORKING else 0.82 + 0.18 * pulse
+ opacity = 1.0 if state == STATE_WORKING else 0.45 + 0.55 * pulse
+ image = NSImage.alloc().initWithSize_((18.0, 18.0))
+ image.lockFocus()
+ NSGraphicsContext.saveGraphicsState()
+ try:
+ transform = NSAffineTransform.transform()
+ transform.translateXBy_yBy_(9.0, 9.0)
+ if state == STATE_WORKING:
+ transform.rotateByDegrees_(-360.0 * phase)
+ transform.scaleBy_(scale)
+ transform.concat()
+ source.drawInRect_fromRect_operation_fraction_(
+ ((-7.5, -7.5), (15.0, 15.0)), image_source_rect(source),
+ NSCompositingOperationSourceOver, opacity,
+ )
+ finally:
+ NSGraphicsContext.restoreGraphicsState()
+ image.unlockFocus()
+ image.setTemplate_(True)
+ return image
+
+
+@lru_cache(maxsize=512)
+def animated_session_row_icon(state: StatusBarState, frame: int, origin_icon, dark_mode: bool = False):
+ # Only the status glyph moves; the provider/host badge remains stationary.
+ icon = animated_status_icon(state, frame)
+ if origin_icon is None:
+ return icon
+ if icon is None:
+ return origin_icon
+ return horizontal_icon_pair(icon, origin_icon, dark_mode=dark_mode)
+
+
def session_origin_icon_for_status(status: AgentStatus):
provider_icon = provider_icon_for_status(status)
host_icon = host_icon_for_origin(status.origin)
@@ -5896,7 +6144,16 @@ def composite_app_icons(host_icon, provider_icon):
return image
-def horizontal_icon_pair(left_icon, right_icon):
+def is_dark_appearance(appearance=None) -> bool:
+ appearance = appearance or NSApplication.sharedApplication().effectiveAppearance()
+ return appearance.bestMatchFromAppearancesWithNames_(
+ [NSAppearanceNameAqua, NSAppearanceNameDarkAqua],
+ ) == NSAppearanceNameDarkAqua
+
+
+def horizontal_icon_pair(left_icon, right_icon, *, dark_mode: bool | None = None):
+ if dark_mode is None:
+ dark_mode = is_dark_appearance()
left_width = 15.5
right_width = float(right_icon.size().width)
width = left_width + 3.0 + right_width
@@ -5910,6 +6167,12 @@ def horizontal_icon_pair(left_icon, right_icon):
NSCompositingOperationSourceOver,
1.0,
)
+ # The combined image contains a full-color app badge and cannot be a
+ # template. Tint only the status glyph, preserving its animated alpha.
+ (NSColor.whiteColor() if dark_mode else NSColor.blackColor()).set()
+ NSRectFillUsingOperation(
+ ((0.0, 0.0), (left_width, height)), NSCompositingOperationSourceIn,
+ )
right_icon.drawInRect_fromRect_operation_fraction_(
((left_width + 3.0, 0.0), (right_width, height)),
image_source_rect(right_icon),
diff --git a/tests/test_internal_display.py b/tests/test_internal_display.py
new file mode 100644
index 0000000..0b721d4
--- /dev/null
+++ b/tests/test_internal_display.py
@@ -0,0 +1,90 @@
+from unittest.mock import Mock
+
+import pytest
+
+from sidepulse.internal_display import InternalDisplayController, builtin_framebuffer_id
+
+
+def test_selects_only_internal_framebuffer():
+ entries = [
+ {"IONameMatched": "dispext0,t604x", "IORegistryEntryID": 1},
+ {"IONameMatched": "disp0,t604x", "IORegistryEntryID": 2},
+ {"IONameMatched": "dispext1,t604x", "IORegistryEntryID": 3},
+ ]
+ assert builtin_framebuffer_id(entries) == 2
+ with pytest.raises(RuntimeError):
+ builtin_framebuffer_id(entries[:1])
+ with pytest.raises(RuntimeError):
+ builtin_framebuffer_id([entries[1], entries[1]])
+
+
+def test_lid_cycle_and_repeated_polls(tmp_path):
+ power = Mock()
+ panel = InternalDisplayController(power, recovery_path=tmp_path / "recovery")
+ panel.update(False)
+ panel.update(None)
+ power.assert_not_called()
+ panel.update(True)
+ panel.update(True)
+ power.assert_called_once_with(False)
+ panel.update(False)
+ panel.release()
+ assert [call.args for call in power.call_args_list] == [(False,), (True,)]
+ assert not panel.recovery_path.exists()
+
+
+def test_retries_failed_off_and_restores_after_uncertain_result(tmp_path):
+ power = Mock(side_effect=[RuntimeError("failed"), None, RuntimeError("wake"), None])
+ panel = InternalDisplayController(power, recovery_path=tmp_path / "recovery")
+ panel.update(True)
+ assert panel.last_error == "failed"
+ assert panel.recovery_path.exists()
+ panel.update(True)
+ assert panel.last_error is None
+ panel.update(False)
+ assert panel.powered_off
+ panel.update(False)
+ assert not panel.powered_off
+ assert [call.args for call in power.call_args_list] == [(False,), (False,), (True,), (True,)]
+
+
[email protected]("closed", [False, True])
+def test_restart_recovers_recorded_panel_state(tmp_path, closed):
+ path = tmp_path / "recovery"
+ path.touch()
+ power = Mock()
+ panel = InternalDisplayController(power, recovery_path=path)
+ panel.update(closed)
+ power.assert_called_once_with(not closed)
+ panel.release()
+ assert not path.exists()
+
+
+def test_open_after_failed_off_still_restores(tmp_path):
+ power = Mock(side_effect=[RuntimeError("uncertain"), None])
+ panel = InternalDisplayController(power, recovery_path=tmp_path / "recovery")
+ panel.update(True)
+ panel.update(False)
+ assert [call.args for call in power.call_args_list] == [(False,), (True,)]
+ assert not panel.powered_off
+
+
+def test_failed_second_close_retries(tmp_path):
+ power = Mock(side_effect=[None, None, RuntimeError("off"), None])
+ panel = InternalDisplayController(power, recovery_path=tmp_path / "recovery")
+ for closed in [True, False, True, True]:
+ panel.update(closed)
+ assert power.call_count == 4
+ assert panel.last_error is None
+
+
+def test_backend_initialization_error_is_cached():
+ from sidepulse.internal_display import BuiltinPanelPower
+
+ backend = BuiltinPanelPower()
+ backend._connect = Mock(side_effect=RuntimeError("unsupported"))
+ with pytest.raises(RuntimeError, match="unsupported"):
+ backend(False)
+ with pytest.raises(RuntimeError, match="unsupported"):
+ backend(False)
+ backend._connect.assert_called_once()
diff --git a/tests/test_sidepulse.py b/tests/test_sidepulse.py
index 4d1b069..b50205f 100644
--- a/tests/test_sidepulse.py
+++ b/tests/test_sidepulse.py
@@ -1805,6 +1805,67 @@ class AgentMonitorTests(unittest.TestCase):
self.assertEqual(calls, [None])
+ def test_status_bar_battery_poll_does_not_overlap_reads(self) -> None:
+ try:
+ from sidepulse import status_bar
+ except SystemExit as exc:
+ self.skipTest(str(exc))
+
+ target = SimpleNamespace(
+ battery_poll_in_flight=False,
+ battery_poll_pending=False,
+ _read_battery_snapshot_async=lambda: None,
+ )
+
+ with patch("sidepulse.status_bar.threading.Thread") as thread:
+ status_bar.StatusBarController.poll_battery_once(target)
+ status_bar.StatusBarController.poll_battery_once(target)
+
+ self.assertTrue(target.battery_poll_in_flight)
+ self.assertTrue(target.battery_poll_pending)
+ thread.assert_called_once_with(
+ target=target._read_battery_snapshot_async,
+ daemon=True,
+ )
+ thread.return_value.start.assert_called_once_with()
+
+ def test_status_bar_battery_poll_result_syncs_leds_immediately(self) -> None:
+ try:
+ from sidepulse import status_bar
+ except SystemExit as exc:
+ self.skipTest(str(exc))
+
+ snapshot = BatterySnapshot(percent=55, is_plugged=True, is_charging=True)
+ calls: list[tuple[str, object]] = []
+ target = SimpleNamespace(
+ pending_battery_snapshot=snapshot,
+ pending_battery_error=None,
+ battery_poll_in_flight=True,
+ battery_poll_pending=False,
+ last_battery_error=None,
+ last_snapshot=SimpleNamespace(
+ aggregate=SimpleNamespace(mode=AgentMode.WORKING),
+ ),
+ accept_battery_snapshot=lambda value: value,
+ sync_keep_awake=lambda mode, value: calls.append(
+ ("awake", (mode, value))
+ ),
+ active_led_display_kind=lambda value: "battery",
+ sync_leds=lambda mode, value, display: calls.append(
+ ("leds", (mode, value, display))
+ ),
+ )
+
+ status_bar.StatusBarController.handle_battery_snapshot(target)
+
+ self.assertFalse(target.battery_poll_in_flight)
+ self.assertIsNone(target.pending_battery_snapshot)
+ self.assertEqual(calls[0], ("awake", (AgentMode.WORKING, snapshot)))
+ self.assertEqual(
+ calls[1],
+ ("leds", (AgentMode.WORKING, snapshot, "battery")),
+ )
+
def test_status_bar_syncs_agent_status_to_linked_phone_once(self) -> None:
try:
from sidepulse import status_bar
@@ -2264,6 +2325,46 @@ class AgentMonitorTests(unittest.TestCase):
],
)
+ def test_status_bar_timers_run_while_menu_tracks_input(self) -> None:
+ try:
+ from sidepulse import status_bar
+ except SystemExit as exc:
+ self.skipTest(str(exc))
+
+ timer = object()
+ modes = []
+ run_loop = SimpleNamespace(
+ addTimer_forMode_=lambda added_timer, mode: modes.append(
+ (added_timer, mode)
+ )
+ )
+ with (
+ patch(
+ "sidepulse.status_bar.NSTimer",
+ SimpleNamespace(
+ scheduledTimerWithTimeInterval_target_selector_userInfo_repeats_=(
+ lambda *args: timer
+ )
+ ),
+ ),
+ patch(
+ "sidepulse.status_bar.NSRunLoop",
+ SimpleNamespace(mainRunLoop=lambda: run_loop),
+ ),
+ ):
+ self.assertIs(
+ status_bar.schedule_status_bar_timer(1, object(), "pollLid:"),
+ timer,
+ )
+
+ self.assertEqual(
+ modes,
+ [
+ (timer, status_bar.NSRunLoopCommonModes),
+ (timer, status_bar.NSEventTrackingRunLoopMode),
+ ],
+ )
+
def test_status_bar_show_agent_animation_on_device_writes_and_restores(self) -> None:
try:
from sidepulse import status_bar
@@ -4726,8 +4827,9 @@ class AgentMonitorTests(unittest.TestCase):
self.assertIn(f"3:{BATTERY_CHARGING_MINT} 360ms ease", lines[0])
self.assertIn("4:#000000 360ms ease", lines[0])
self.assertEqual(lines[1], f"4:{BATTERY_CHARGING_MINT} 790ms pulse")
- self.assertEqual(len(lines), 2)
- self.assertNotIn("repeat", program)
+ self.assertEqual(lines[2], "4:#000000 800ms none")
+ self.assertEqual(lines[3], "repeat")
+ self.assertEqual(len(lines), 4)
self.assertNotIn("\noff", program)
def test_unplugged_battery_program_eases_to_static_level(self) -> None:
@@ -4775,10 +4877,26 @@ class AgentMonitorTests(unittest.TestCase):
validate_led_text(program)
self.assertIn(f"6:{BATTERY_CHARGING_MINT} 1400ms pulse", program)
- self.assertNotIn("repeat", program)
+ self.assertTrue(program.endswith("repeat"))
self.assertNotIn("none", program)
- def test_battery_led_controller_animates_charging_on_cadence(self) -> None:
+ def test_plugged_but_not_charging_uses_static_battery_display(self) -> None:
+ snapshot = BatterySnapshot(
+ percent=80,
+ is_plugged=True,
+ is_charging=False,
+ adapter_watts=140,
+ full_charge_watts=140,
+ )
+
+ program = program_for_battery(snapshot, led_count=8)
+
+ validate_led_text(program)
+ self.assertNotIn("pulse", program)
+ self.assertNotIn("repeat", program)
+ self.assertIn("0:#00FF66 360ms ease", program)
+
+ def test_battery_led_controller_only_rewrites_when_program_changes(self) -> None:
with tempfile.TemporaryDirectory() as tmp:
device = Path(tmp) / "SidePulsePro"
device.mkdir()
@@ -4790,6 +4908,13 @@ class AgentMonitorTests(unittest.TestCase):
adapter_watts=70,
full_charge_watts=140,
)
+ faster_snapshot = BatterySnapshot(
+ percent=50,
+ is_plugged=True,
+ is_charging=True,
+ adapter_watts=96,
+ full_charge_watts=140,
+ )
with patch(
"sidepulse.battery.time.monotonic",
@@ -4797,7 +4922,7 @@ class AgentMonitorTests(unittest.TestCase):
):
first = controller.sync_snapshot(snapshot)
second = controller.sync_snapshot(snapshot)
- third = controller.sync_snapshot(snapshot)
+ third = controller.sync_snapshot(faster_snapshot)
self.assertTrue(first.changed)
self.assertFalse(second.changed)
diff --git a/tests/test_status_bar_ui.py b/tests/test_status_bar_ui.py
index c94f1af..b61bc46 100644
--- a/tests/test_status_bar_ui.py
+++ b/tests/test_status_bar_ui.py
@@ -57,6 +57,7 @@ def tearDownModule():
from AppKit import ( # noqa: E402
NSApplication,
+ NSBitmapImageRep,
NSControl,
NSEvent,
NSEventModifierFlagCommand,
@@ -193,6 +194,7 @@ class StatusBarTestCase(unittest.TestCase):
class MenuBarVisibilityTests(StatusBarTestCase):
def test_status_updates_keep_only_icon_with_accessible_state(self):
controller = sb.StatusBarController.alloc().init()
+ self.addCleanup(controller.stop_status_icon_animation)
controller.status_item = Mock()
button = controller.status_item.button.return_value
for state in (sb.STATE_IDLE, sb.STATE_WORKING, sb.STATE_DONE, sb.STATE_ASK):
@@ -1000,6 +1002,83 @@ class WindowBuildTests(StatusBarTestCase):
self.controller.settings_window.orderOut_(None)
+class StatusIconAnimationTests(StatusBarTestCase):
+ def setUp(self):
+ self.target = sb.StatusBarController.alloc().init()
+ self.addCleanup(self.target.stop_status_icon_animation)
+ self.target.status_item = Mock()
+ self.target.status_item.isVisible.return_value = True
+ self.workspace = Mock()
+ self.workspace.accessibilityDisplayShouldReduceMotion.return_value = False
+ self.workspace.fullPathForApplication_.return_value = None
+ context = patch.object(sb, "NSWorkspace")
+ context.start().sharedWorkspace.return_value = self.workspace
+ self.addCleanup(context.stop)
+
+ def test_working_and_ask_frames_change_but_keep_template_and_size(self):
+ for state in (sb.STATE_WORKING, sb.STATE_ASK):
+ first = sb.animated_status_icon(state, 0)
+ later = sb.animated_status_icon(state, 12)
+ self.assertNotEqual(bytes(first.TIFFRepresentation()), bytes(later.TIFFRepresentation()))
+ self.assertTrue(first.isTemplate())
+ self.assertEqual(first.size(), later.size())
+ self.assertIs(first, sb.animated_status_icon(state, 0))
+
+ def test_provider_badge_pixels_stay_stationary(self):
+ # Supply a real provider image independent of installed applications.
+ origin = sb.image_for_symbol("terminal", "Terminal")
+ frames = [sb.animated_session_row_icon(sb.STATE_WORKING, frame, origin) for frame in (0, 12)]
+ bitmaps = [NSBitmapImageRep.imageRepWithData_(frame.TIFFRepresentation()) for frame in frames]
+ start_x = int(19 * bitmaps[0].pixelsWide() / frames[0].size().width)
+ for y in range(bitmaps[0].pixelsHigh()):
+ for x in range(start_x, bitmaps[0].pixelsWide()):
+ self.assertEqual(bitmaps[0].colorAtX_y_(x, y), bitmaps[1].colorAtX_y_(x, y))
+
+ def test_timer_stops_for_idle_done_and_hidden_icon(self):
+ for state in (sb.STATE_WORKING, sb.STATE_ASK):
+ self.target.status_item.isVisible.return_value = True
+ self.target.set_status(state)
+ timer = self.target.status_icon_timer
+ self.assertIsNotNone(timer)
+ self.target.status_item.isVisible.return_value = False
+ self.target.update_status_icon_animation()
+ self.assertIsNone(self.target.status_icon_timer)
+ self.assertFalse(timer.isValid())
+ self.target.status_item.isVisible.return_value = True
+ for state in (sb.STATE_IDLE, sb.STATE_DONE):
+ self.target.set_status(state)
+ self.assertIsNone(self.target.status_icon_timer)
+
+ def test_open_menu_animates_rows_and_closing_stops_row_animation(self):
+ self.target.current_state = sb.STATE_IDLE
+ menu = NSMenu.alloc().init()
+ for mode in (AgentMode.WORKING, AgentMode.WAITING_FOR_INPUT, AgentMode.COMPLETED):
+ status = make_status(mode=mode, provider="nonsense")
+ menu.addItem_(sb.build_session_menu_item(status, datetime.now(timezone.utc), self.target))
+ with patch.object(sb.time, "monotonic", return_value=0):
+ self.target.menuWillOpen_(menu)
+ first = [bytes(item.image().TIFFRepresentation()) for item in menu.itemArray()]
+ with patch.object(sb.time, "monotonic", return_value=0.4):
+ self.target.animateStatusIcons_(None)
+ later = [bytes(item.image().TIFFRepresentation()) for item in menu.itemArray()]
+ self.assertNotEqual(first[0], later[0])
+ self.assertNotEqual(first[1], later[1])
+ self.assertEqual(first[2], later[2])
+ self.assertIsNotNone(self.target.status_icon_timer)
+ self.target.menuDidClose_(menu)
+ self.assertIsNone(self.target.status_icon_timer)
+ self.assertIsNone(self.target.tracking_status_menu)
+
+ def test_reduce_motion_keeps_static_icons(self):
+ self.target.set_status(sb.STATE_WORKING)
+ self.workspace.accessibilityDisplayShouldReduceMotion.return_value = True
+ self.target.animateStatusIcons_(None)
+ self.assertIsNone(self.target.status_icon_timer)
+ self.target.status_item.button().setImage_.assert_called_with(
+ sb.image_for_symbol(sb.STATE_WORKING.symbol, sb.STATE_WORKING.label),
+ )
+
+
class IconTests(StatusBarTestCase):
"""Icon builders return real images rather than None."""