okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-142b-serve into f-1426e1085c1d

main
3.1 KiB94 linesraw
1"""Opt-in "prevent_sleep" (#1727): while at least one request is running or queued, the PC is kept awake.
2
3Windows only.  SetThreadExecutionState(ES_CONTINUOUS | ES_SYSTEM_REQUIRED) keeps the system from idling into sleep
4(not the display: no ES_DISPLAY_REQUIRED); ES_CONTINUOUS alone puts the normal behaviour back.  The state belongs
5to the thread that set it, so one daemon thread sets and clears it; it is cleared when idle and on exit.
6Elsewhere this does nothing.
7"""
8from __future__ import annotations
9
10import atexit
11import sys
12import threading
13
14ES_CONTINUOUS = 0x80000000
15ES_SYSTEM_REQUIRED = 0x00000001
16
17
18def _windows_call():
19    import ctypes
20    fn = ctypes.windll.kernel32.SetThreadExecutionState
21    fn.argtypes = [ctypes.c_uint32]
22    fn.restype = ctypes.c_uint32
23    return fn
24
25
26class KeepAwake:
27    def __init__(self, call=None):
28        self._call = call
29        self._count = 0
30        self._cond = threading.Condition()
31        self._closed = False
32        self._thread = None
33
34    @classmethod
35    def create(cls, enabled: bool, say=print):
36        """None when off.  On a system without SetThreadExecutionState: one line, and None."""
37        if not enabled:
38            return None
39        if not sys.platform.startswith("win"):
40            say('[strata] "prevent_sleep" is for Windows only: ignored here', flush=True)
41            return None
42        try:
43            ka = cls(_windows_call())
44        except (ImportError, AttributeError, OSError) as e:
45            say(f'[strata] "prevent_sleep" could not be set up: {e}', flush=True)
46            return None
47        atexit.register(ka.close)
48        say('[strata] prevent_sleep: Windows stays awake while a request is running or queued', flush=True)
49        return ka
50
51    def _loop(self):
52        held = False
53        while True:
54            with self._cond:
55                while not self._closed and (self._count > 0) == held:
56                    self._cond.wait()
57                if self._closed:
58                    break
59                want = self._count > 0
60            try:
61                self._call(ES_CONTINUOUS | ES_SYSTEM_REQUIRED if want else ES_CONTINUOUS)
62                held = want
63            except Exception:         # noqa: BLE001  never fail a request over this
64                held = want
65        try:
66            self._call(ES_CONTINUOUS)
67        except Exception:             # noqa: BLE001
68            pass
69
70    def _start(self):
71        if self._thread is None:
72            self._thread = threading.Thread(target=self._loop, daemon=True, name="keep-awake")
73            self._thread.start()
74
75    def acquire(self):
76        with self._cond:
77            if self._closed:
78                return
79            self._count += 1
80            self._start()
81            self._cond.notify_all()
82
83    def release(self):
84        with self._cond:
85            self._count = max(0, self._count - 1)
86            self._cond.notify_all()
87
88    def close(self):
89        with self._cond:
90            self._closed = True
91            self._cond.notify_all()
92        t = self._thread
93        if t is not None and t is not threading.current_thread():
94            t.join(timeout=2)