175 lines
6.7 KiB
Python
175 lines
6.7 KiB
Python
"""Start the native cab/control companion whenever the installed ATS opens."""
|
|
import argparse
|
|
import ctypes
|
|
from ctypes import wintypes as w
|
|
from datetime import datetime
|
|
import os
|
|
from pathlib import Path
|
|
import subprocess
|
|
import sys
|
|
import time
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
if str(ROOT) not in sys.path:
|
|
sys.path.insert(0, str(ROOT))
|
|
DEFAULT_GAME = Path(r'C:\Program Files (x86)\DODI-Repacks\American Truck Simulator\bin\win_x64\amtrucks.exe')
|
|
|
|
|
|
class ProcessEntry(ctypes.Structure):
|
|
_fields_ = [('size', w.DWORD), ('usage', w.DWORD), ('pid', w.DWORD),
|
|
('heap', ctypes.c_size_t), ('module', w.DWORD), ('threads', w.DWORD),
|
|
('parent', w.DWORD), ('priority', w.LONG), ('flags', w.DWORD),
|
|
('name', w.WCHAR * 260)]
|
|
|
|
|
|
def kernel():
|
|
api = ctypes.WinDLL('kernel32', use_last_error=True)
|
|
signatures = {
|
|
'OpenProcess': ([w.DWORD, w.BOOL, w.DWORD], w.HANDLE),
|
|
'CloseHandle': ([w.HANDLE], w.BOOL),
|
|
'WaitForSingleObject': ([w.HANDLE, w.DWORD], w.DWORD),
|
|
'CreateToolhelp32Snapshot': ([w.DWORD, w.DWORD], w.HANDLE),
|
|
'Process32FirstW': ([w.HANDLE, ctypes.POINTER(ProcessEntry)], w.BOOL),
|
|
'Process32NextW': ([w.HANDLE, ctypes.POINTER(ProcessEntry)], w.BOOL),
|
|
'QueryFullProcessImageNameW': ([w.HANDLE, w.DWORD, w.LPWSTR, ctypes.POINTER(w.DWORD)], w.BOOL),
|
|
}
|
|
for name, (args, result) in signatures.items():
|
|
getattr(api, name).argtypes, getattr(api, name).restype = args, result
|
|
return api
|
|
|
|
|
|
class ProcessLifetime:
|
|
"""Retain the real process handle so a reused PID cannot extend its life."""
|
|
def __init__(self, pid):
|
|
self.api = kernel()
|
|
self.handle = self.api.OpenProcess(0x100000, False, pid)
|
|
if not self.handle:
|
|
raise OSError('Cannot observe ATS process lifetime')
|
|
|
|
def running(self):
|
|
return bool(self.handle and self.api.WaitForSingleObject(self.handle, 0) == 258)
|
|
|
|
def close(self):
|
|
if self.handle:
|
|
self.api.CloseHandle(self.handle)
|
|
self.handle = None
|
|
|
|
|
|
def game_processes(executable):
|
|
api = kernel()
|
|
snapshot = api.CreateToolhelp32Snapshot(2, 0)
|
|
if snapshot in (None, ctypes.c_void_p(-1).value):
|
|
raise OSError('Cannot list ATS processes')
|
|
expected = os.path.normcase(os.path.abspath(executable))
|
|
result = []
|
|
try:
|
|
entry = ProcessEntry(); entry.size = ctypes.sizeof(entry)
|
|
more = api.Process32FirstW(snapshot, ctypes.byref(entry))
|
|
while more:
|
|
if entry.name.lower() == 'amtrucks.exe':
|
|
handle = api.OpenProcess(0x1000, False, entry.pid)
|
|
if handle:
|
|
try:
|
|
size = w.DWORD(32768); buffer = ctypes.create_unicode_buffer(size.value)
|
|
if (api.QueryFullProcessImageNameW(handle, 0, buffer, ctypes.byref(size))
|
|
and os.path.normcase(buffer.value) == expected):
|
|
result.append(entry.pid)
|
|
finally:
|
|
api.CloseHandle(handle)
|
|
more = api.Process32NextW(snapshot, ctypes.byref(entry))
|
|
finally:
|
|
api.CloseHandle(snapshot)
|
|
return result
|
|
|
|
|
|
def companion_running():
|
|
from tools.run_native_gameplay import _acquire_instance_lock, _release_instance_lock
|
|
try:
|
|
handle = _acquire_instance_lock()
|
|
except RuntimeError:
|
|
return True
|
|
_release_instance_lock(handle)
|
|
return False
|
|
|
|
|
|
class Supervisor:
|
|
"""One companion per game; restart failures with a bounded retry delay."""
|
|
def __init__(self, launch, occupied=companion_running):
|
|
self.launch, self.occupied = launch, occupied
|
|
self.child = None
|
|
self.retry_at = 0.
|
|
self.failures = 0
|
|
self.game_pid = None
|
|
self.started_at = None
|
|
|
|
def tick(self, pids, now):
|
|
if self.child is not None and self.child.poll() is not None:
|
|
uptime = now-self.started_at
|
|
self.child = None
|
|
self.failures = self.failures+1 if uptime < 30. else 1
|
|
self.retry_at = now+min(60., 5.*2.**min(4, self.failures-1))
|
|
if len(pids) != 1:
|
|
if not pids and self.child is None:
|
|
self.game_pid = None; self.failures = 0; self.retry_at = 0.
|
|
return
|
|
if self.child is not None or now < self.retry_at or self.occupied():
|
|
return
|
|
self.game_pid = pids[0]
|
|
self.child = self.launch(self.game_pid)
|
|
self.started_at = now
|
|
|
|
|
|
def main(argv=None):
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument('--game', type=Path, default=DEFAULT_GAME)
|
|
parser.add_argument('--launch', action='store_true', help='Also open ATS if it is closed')
|
|
args, runner_args = parser.parse_known_args(argv)
|
|
if not args.game.is_file():
|
|
raise FileNotFoundError('ATS executable not found: '+str(args.game))
|
|
if args.launch and not game_processes(args.game):
|
|
subprocess.Popen([str(args.game)], cwd=args.game.parent)
|
|
# The login watcher and one-click shortcut share this lock. A second
|
|
# shortcut can open ATS, then leave the existing watcher in charge.
|
|
import msvcrt
|
|
logs = ROOT/'diagnostics'; logs.mkdir(exist_ok=True)
|
|
lock = (logs/'ats-autostart.lock').open('a+b')
|
|
lock.seek(0, os.SEEK_END)
|
|
if not lock.tell(): lock.write(b'0'); lock.flush()
|
|
lock.seek(0)
|
|
try:
|
|
msvcrt.locking(lock.fileno(), msvcrt.LK_NBLCK, 1)
|
|
except OSError:
|
|
lock.close()
|
|
return 0
|
|
def note(message):
|
|
with (logs/'ats-autostart.log').open('a', encoding='utf-8') as stream:
|
|
stream.write(datetime.now().isoformat(timespec='seconds')+' '+message+'\n')
|
|
def launch(pid):
|
|
output = logs/'native-runtime.log'
|
|
if output.exists() and output.stat().st_size > 5_000_000:
|
|
output.replace(logs/'native-runtime.previous.log')
|
|
python = str(Path(sys.executable).with_name('python.exe'))
|
|
command = [python, '-B', '-u', str(ROOT/'tools/run_native_gameplay.py'),
|
|
'--input', 'auto', '--game-pid', str(pid), *runner_args]
|
|
with output.open('ab', buffering=0) as stream:
|
|
child = subprocess.Popen(command, cwd=ROOT, stdout=stream, stderr=stream,
|
|
creationflags=subprocess.CREATE_NO_WINDOW)
|
|
note('Started native companion PID %s for ATS PID %s' % (child.pid, pid))
|
|
return child
|
|
supervisor = Supervisor(launch)
|
|
note('Watching '+str(args.game))
|
|
try:
|
|
while True:
|
|
try:
|
|
supervisor.tick(game_processes(args.game), time.monotonic())
|
|
except OSError as exc:
|
|
note('Retrying: '+str(exc))
|
|
time.sleep(5.)
|
|
time.sleep(1.)
|
|
finally:
|
|
lock.close()
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|