macOS / Tests (AppleSilicon) (push) Canceled after 0s
macOS / Tests (Intel) (push) Canceled after 0s
macOS / Build (AppleSilicon) (push) Canceled after 0s
macOS / Build (Intel) (push) Canceled after 0s
macOS / Publish the GitHub Release (push) Canceled after 0s
150 lines
5.2 KiB
Python
150 lines
5.2 KiB
Python
"""Keep the machine awake while music plays or a device sync runs.
|
|
|
|
Uses the GNOME SessionManager D-Bus interface (the same session bus PyQt6's
|
|
QtDBus already talks to for MPRIS) to register an inhibitor. Playback holds a
|
|
*suspend* inhibitor; a device sync additionally holds *logout* (which covers
|
|
shutdown/reboot from the session — GNOME's power dialog names the holder and
|
|
its reason). GNOME's critical-battery action overrides these, so a near-dead
|
|
laptop still suspends as expected.
|
|
|
|
Instances are independent (one D-Bus cookie each), so playback and sync can
|
|
hold inhibitors simultaneously without stepping on each other. On non-GNOME
|
|
desktops the interface won't be available; every method then no-ops silently
|
|
rather than failing.
|
|
|
|
On macOS there is no session bus to ask: an inhibitor is a ``caffeinate``
|
|
child process held for as long as the inhibit lasts (``-i`` for suspend,
|
|
plus ``-s``/``-m`` keeping disks and the system up for logout-class
|
|
syncs). ``-w <our pid>`` makes it exit on its own if LinTunes dies, so a
|
|
crash can never leave the Mac unable to sleep.
|
|
"""
|
|
import atexit
|
|
import logging
|
|
import os
|
|
import shutil
|
|
import subprocess
|
|
import weakref
|
|
|
|
from PyQt6.QtCore import QMetaType
|
|
|
|
try:
|
|
from PyQt6.QtDBus import (QDBusArgument, QDBusConnection, QDBusInterface,
|
|
QDBusReply)
|
|
HAVE_DBUS = True
|
|
except ImportError: # no QtDBus in this Qt: every inhibitor no-ops
|
|
HAVE_DBUS = False
|
|
|
|
from lintunes import paths
|
|
|
|
log = logging.getLogger(__name__)
|
|
|
|
|
|
SERVICE = "org.gnome.SessionManager"
|
|
PATH = "/org/gnome/SessionManager"
|
|
INHIBIT_LOGOUT = 1 # GsmInhibitorFlag: inhibit logout/shutdown/reboot
|
|
INHIBIT_SUSPEND = 4 # GsmInhibitorFlag: inhibit suspending the session/computer
|
|
APP_ID = "org.lintunes.LinTunes"
|
|
REASON = "Playing music"
|
|
|
|
|
|
def _uint(value: int) -> QDBusArgument:
|
|
"""Marshal as D-Bus uint32. Inhibit's signature is (susu) — a plain
|
|
Python int marshals as *signed* int32 and GNOME rejects the whole call
|
|
with a type error (which QDBusReply reported merely as "invalid", so
|
|
the inhibitor silently never took effect)."""
|
|
return QDBusArgument(value, QMetaType.Type.UInt.value)
|
|
|
|
|
|
def caffeinate_command(flags: int, pid: int | None = None) -> list[str]:
|
|
"""The macOS ``caffeinate`` line for these GsmInhibitorFlags: ``-i``
|
|
stops idle sleep (what playback needs); a logout-class inhibit (a
|
|
sync, an export) also keeps the system (``-s``, on AC) and the disks
|
|
(``-m``) awake. ``-w`` ties it to our process."""
|
|
args = ["caffeinate", "-i"]
|
|
if flags & INHIBIT_LOGOUT:
|
|
args += ["-s", "-m"]
|
|
args += ["-w", str(os.getpid() if pid is None else pid)]
|
|
return args
|
|
|
|
|
|
# Every live caffeinate, so quitting kills them even if nothing released
|
|
# them (``-w`` would end them anyway once we exit; this is belt and braces).
|
|
_LIVE: "weakref.WeakSet[SleepInhibitor]" = weakref.WeakSet()
|
|
|
|
|
|
@atexit.register
|
|
def _release_all():
|
|
for inhibitor in list(_LIVE):
|
|
try:
|
|
inhibitor.release()
|
|
except Exception: # noqa: BLE001 — exiting; nothing to report to
|
|
pass
|
|
|
|
|
|
class SleepInhibitor:
|
|
def __init__(self, reason: str = REASON, flags: int = INHIBIT_SUSPEND):
|
|
self._cookie: int | None = None
|
|
self._reason = reason
|
|
self._flags = flags
|
|
self._proc = None # macOS: the caffeinate holding the inhibit
|
|
self._iface = None
|
|
if paths.IS_MAC or not HAVE_DBUS:
|
|
return
|
|
bus = QDBusConnection.sessionBus()
|
|
self._iface = QDBusInterface(SERVICE, PATH, SERVICE, bus)
|
|
|
|
def _available(self) -> bool:
|
|
return self._iface is not None and self._iface.isValid()
|
|
|
|
def _mac_inhibit(self):
|
|
if self._proc is not None and self._proc.poll() is None:
|
|
return
|
|
if shutil.which("caffeinate") is None:
|
|
return
|
|
try:
|
|
self._proc = subprocess.Popen(
|
|
caffeinate_command(self._flags),
|
|
stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
|
|
stderr=subprocess.DEVNULL)
|
|
except OSError as e:
|
|
log.info("inhibit: couldn't start caffeinate: %s", e)
|
|
self._proc = None
|
|
return
|
|
_LIVE.add(self)
|
|
|
|
def _mac_release(self):
|
|
proc, self._proc = self._proc, None
|
|
_LIVE.discard(self)
|
|
if proc is None:
|
|
return
|
|
try:
|
|
proc.terminate()
|
|
proc.wait(timeout=2)
|
|
except Exception: # noqa: BLE001
|
|
try:
|
|
proc.kill()
|
|
except Exception: # noqa: BLE001
|
|
pass
|
|
|
|
def inhibit(self):
|
|
"""Take the inhibitor. No-op if already inhibiting or unavailable."""
|
|
if paths.IS_MAC:
|
|
self._mac_inhibit()
|
|
return
|
|
if self._cookie is not None or not self._available():
|
|
return
|
|
reply = QDBusReply(self._iface.call(
|
|
"Inhibit", APP_ID, _uint(0), self._reason, _uint(self._flags)))
|
|
if reply.isValid():
|
|
self._cookie = int(reply.value())
|
|
|
|
def release(self):
|
|
"""Release a held inhibitor, if any."""
|
|
if self._proc is not None:
|
|
self._mac_release()
|
|
if self._cookie is None:
|
|
return
|
|
if self._available():
|
|
self._iface.call("Uninhibit", _uint(self._cookie))
|
|
self._cookie = None
|