Compare commits

...

2 commits

Author SHA1 Message Date
ba5d560a01
Add timeout to signal awaiting configs. 2022-10-29 12:37:28 +02:00
6f49d819ac
Prevent potential racing conditions.
Prevent abort if superflous signal is received.
2022-10-29 02:52:41 +02:00

View file

@ -6,6 +6,7 @@ import collections.abc
import asyncio
import signal
import os
import time
import functools
import json
@ -272,7 +273,7 @@ def parse(s: str) -> Expression:
tokens = tokenize(s)
return build_expression(tokens)
def window_new(configs: list[dict], debug: bool):
def window_new(configs: list[dict], debug: bool, *, lock):
async def callback(ipc: i3ipc.aio.Connection, e: i3ipc.WorkspaceEvent):
assert e.change == 'new'
if debug:
@ -282,9 +283,11 @@ def window_new(configs: list[dict], debug: bool):
workspace = cfg['workspace']
if filter.reduce(e.ipc_data):
container_id = e.ipc_data['container']['id']
await ipc.command(f'for_window [con_id="{container_id}"] focus')
await ipc.command(f'move container to workspace {workspace}')
configs.pop(i)
async with lock:
await ipc.command(f'for_window [con_id="{container_id}"] focus')
await ipc.command(f'move container to workspace {workspace}')
await asyncio.sleep(1)
configs.pop(i)
if not configs:
ipc.main_quit()
return callback
@ -295,33 +298,49 @@ async def wait_signal(s):
await event.wait()
event.clear()
asyncio.get_running_loop().remove_signal_handler(s)
asyncio.get_running_loop().add_signal_handler(s, lambda: None)
async def coro_wait_signal(coro, s):
await coro
await wait_signal(s)
async def run(configs: list[dict], *, timeout: int, debug: bool):
window_configs = [c for c in configs if c.get('workspace') is not None]
lock = asyncio.Lock()
ipc = await i3ipc.aio.Connection().connect() # we only wait for configs which spawn a window
ipc.on('window::new', window_new(window_configs, debug=debug))
ipc.on('window::new', window_new(window_configs, debug=debug, lock=lock))
variables = {
'pid': os.getpid(),
}
coroutines = []
timeouts = [timeout]
started_at = time.monotonic_ns()
for cfg in configs:
cfg['filter'] = parse(cfg['filter'])
p = cfg['program']
t = cfg.get('timeout', timeout)
timeouts += [t]
if isinstance(p, collections.abc.Iterable) and not isinstance(p, str):
p = ' '.join(p)
p = p.format(**variables)
coro = ipc.command(f'exec {p}')
if cfg.get('signal_continue', False):
await coro
await wait_signal(signal.Signals(cfg.get('signal_continue')))
sig = signal.Signals(cfg.get('signal_continue'))
coro = coro_wait_signal(coro, sig)
try:
await asyncio.wait_for(coro, timeout=t/1000)
except asyncio.TimeoutError:
pass
else:
coroutines += [coro]
await asyncio.gather(*coroutines)
try:
if window_configs:
# run main loop only if we wait for something
await asyncio.wait_for(ipc.main(), timeout=timeout/1000)
diff = (time.monotonic_ns() - started_at) / (1000*1000)
new_timeout = max(max(*timeouts) - diff, 0)
await asyncio.wait_for(ipc.main(), timeout=new_timeout/1000)
except asyncio.TimeoutError:
return 1
return 0