CLI for SidePulse
Python
Remove unsafe internal panel power control
Peter Kuharfedc0adaccdf
diff --git a/README.md b/README.mdindex 91bb708..0832d70 100644--- a/README.md+++ b/README.md@@ -643,13 +643,6 @@ and shows the path from provider hook event to interpreted SidePulse status.The `Keep Awake With Lid Closed` menu section controls the stronger sleepprevention 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/internal_display.py b/src/sidepulse/internal_display.pydeleted file mode 100644index bad1c57..0000000--- a/src/sidepulse/internal_display.py+++ /dev/null@@ -1,128 +0,0 @@-"""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/status_bar.py b/src/sidepulse/status_bar.pyindex c629490..adc2652 100644--- a/src/sidepulse/status_bar.py+++ b/src/sidepulse/status_bar.py@@ -137,7 +137,6 @@ from .virtual_device import (VirtualLedView,VirtualStatusDevice,)-from .internal_display import InternalDisplayControllerfrom .lid_sleep import (LID_POLL_SECONDS,ClosedLidAwakeController,@@ -608,7 +607,6 @@ class StatusBarController(NSObject):self.last_led_display_kind = LED_DISPLAY_AGENTself.last_connected_device_signature = Noneself.keep_awake = KeepAwakeController()- self.internal_display = InternalDisplayController()self.closed_lid_awake = ClosedLidAwakeController(use_system_disable=sleep_helper_installed(),)@@ -634,8 +632,6 @@ class StatusBarController(NSObject):self.lid_poll_backoff_until_monotonic = 0.0self.pending_lid_closed = Noneself.pending_lid_error = None- self.pending_lid_panel_error = None- self.pending_lid_panel_state = Noneself.lid_closed_led_hold_active = Falseself.led_animation_until_monotonic = 0.0self.led_animation_token = 0@@ -1123,14 +1119,12 @@ class StatusBarController(NSObject):@objc.IBActiondef 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()@@ -3387,27 +3381,10 @@ 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 = Nonetry:closed = read_lid_closed()self.pending_lid_closed = closedself.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 = Noneself.pending_lid_error = str(exc)@@ -3435,12 +3412,6 @@ class StatusBarController(NSObject):if closed is None:returnclosed = 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 = Noneself.lid_poll_backoff_until_monotonic = 0.0if self.last_lid_closed is None:diff --git a/tests/test_internal_display.py b/tests/test_internal_display.pydeleted file mode 100644index 0b721d4..0000000--- a/tests/test_internal_display.py+++ /dev/null@@ -1,90 +0,0 @@-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()