okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
6e1085c1d
main
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 (): 19import ctypes 20fn = ctypes .windll .kernel32 .SetThreadExecutionState 21fn .argtypes = [ctypes .c_uint32 ] 22fn .restype = ctypes .c_uint32 23return fn 24 25 26class KeepAwake : 27def __init__ (self ,call = None ): 28self ._call = call 29self ._count = 0 30self ._cond = threading .Condition () 31self ._closed = False 32self ._thread = None 33 34@classmethod 35def create (cls ,enabled :bool ,say = """None when off. On a system without SetThreadExecutionState: one line, and None.""" 37if not enabled : 38return None 39if not sys .platform .startswith ("win" ): 40say ('[strata] "prevent_sleep" is for Windows only: ignored here' ,flush = True ) 41return None 42try : 43ka = cls (_windows_call ()) 44except (ImportError ,AttributeError ,OSError )as e : 45say (f'[strata] "prevent_sleep" could not be set up: { e } ' ,flush = True ) 46return None 47atexit .register (ka .close ) 48say ('[strata] prevent_sleep: Windows stays awake while a request is running or queued' ,flush = True ) 49return ka 50 51def _loop (self ): 52held = False 53while True : 54with self ._cond : 55while not self ._closed and (self ._count > 0 )== held : 56self ._cond .wait () 57if self ._closed : 58break 59want = self ._count > 0 60try : 61self ._call (ES_CONTINUOUS | ES_SYSTEM_REQUIRED if want else ES_CONTINUOUS ) 62held = want 63except Exception :# noqa: BLE001 never fail a request over this 64held = want 65try : 66self ._call (ES_CONTINUOUS ) 67except Exception :# noqa: BLE001 68pass 69 70def _start (self ): 71if self ._thread is None : 72self ._thread = threading .Thread (target = self ._loop ,daemon = True ,name = "keep-awake" ) 73self ._thread .start () 74 75def acquire (self ): 76with self ._cond : 77if self ._closed : 78return 79self ._count += 1 80self ._start () 81self ._cond .notify_all () 82 83def release (self ): 84with self ._cond : 85self ._count = max (0 ,self ._count - 1 ) 86self ._cond .notify_all () 87 88def close (self ): 89with self ._cond : 90self ._closed = True 91self ._cond .notify_all () 92t = self ._thread 93if t is not None and t is not threading .current_thread (): 94t .join (timeout = 2 )