|
| 1 | +import asyncio |
| 2 | +import json |
| 3 | +import sys |
| 4 | +from dataclasses import dataclass |
| 5 | +from pathlib import Path |
| 6 | +from typing import Self |
| 7 | + |
| 8 | +from aiohttp import WSMsgType, web |
| 9 | +from watchdog.events import (DirModifiedEvent, FileModifiedEvent, |
| 10 | + FileSystemEventHandler) |
| 11 | +from watchdog.observers import Observer |
| 12 | + |
| 13 | +_STATIC_DIR = Path(__file__).resolve().parent / "www" |
| 14 | +_EXAMPLES_DIR = Path(__file__).resolve().parent / "frag-examples" |
| 15 | +_SHADER_DIR = Path(sys.argv[1] if len(sys.argv) > 1 else _EXAMPLES_DIR).resolve() |
| 16 | + |
| 17 | + |
| 18 | +class AsyncFileSystemEventHandler(FileSystemEventHandler): |
| 19 | + """Push the watchdog events into the specified queue""" |
| 20 | + |
| 21 | + def __init__(self, push_queue: asyncio.Queue): |
| 22 | + self._queue = push_queue |
| 23 | + self._loop = asyncio.get_running_loop() |
| 24 | + |
| 25 | + def on_modified(self, event: DirModifiedEvent | FileModifiedEvent): |
| 26 | + asyncio.run_coroutine_threadsafe(self._queue.put(event), self._loop) |
| 27 | + |
| 28 | + |
| 29 | +class EventBroadcaster: |
| 30 | + """Forward the content of 1 queue to N sub-queues""" |
| 31 | + |
| 32 | + def __init__(self, src_queue: asyncio.Queue): |
| 33 | + self._src_queue = src_queue |
| 34 | + self.subscribers = set() |
| 35 | + |
| 36 | + def subscribe(self, dst_queue: asyncio.Queue): |
| 37 | + self.subscribers.add(dst_queue) |
| 38 | + |
| 39 | + def unsubscribe(self, dst_queue: asyncio.Queue): |
| 40 | + self.subscribers.discard(dst_queue) |
| 41 | + |
| 42 | + async def start(self): |
| 43 | + while True: |
| 44 | + event = await self._src_queue.get() |
| 45 | + for dst_queue in self.subscribers: |
| 46 | + await dst_queue.put(event) |
| 47 | + |
| 48 | + |
| 49 | +@dataclass |
| 50 | +class State: |
| 51 | + """One websocket user context state""" |
| 52 | + |
| 53 | + frags: list[str] |
| 54 | + selected: str | None |
| 55 | + |
| 56 | + @classmethod |
| 57 | + def new(cls) -> Self: |
| 58 | + return cls(frags=[], selected=None) |
| 59 | + |
| 60 | + def select(self, id: str): |
| 61 | + if id not in self.frags: |
| 62 | + return |
| 63 | + self.selected = id |
| 64 | + |
| 65 | + async def refresh(self, ws: web.WebSocketResponse): |
| 66 | + self.frags = sorted(f.name for f in _SHADER_DIR.glob("*.frag")) |
| 67 | + if self.selected not in self.frags: |
| 68 | + self.selected = None |
| 69 | + await self._send_list(ws) |
| 70 | + |
| 71 | + async def _send_list(self, ws: web.WebSocketResponse): |
| 72 | + payload = dict(type="list", frags=self.frags) |
| 73 | + await self._send_payload(ws, payload) |
| 74 | + |
| 75 | + async def send_reload(self, ws: web.WebSocketResponse): |
| 76 | + payload = dict(type="reload") |
| 77 | + await self._send_payload(ws, payload) |
| 78 | + |
| 79 | + async def _send_payload(self, ws: web.WebSocketResponse, payload: dict): |
| 80 | + # print(f">> {payload}") |
| 81 | + await ws.send_json(payload) |
| 82 | + |
| 83 | + |
| 84 | +async def _ws_handler(request): |
| 85 | + ws = web.WebSocketResponse() |
| 86 | + await ws.prepare(request) |
| 87 | + |
| 88 | + state = State.new() |
| 89 | + await state.refresh(ws) |
| 90 | + |
| 91 | + fs_events_queue = asyncio.Queue() |
| 92 | + |
| 93 | + # Process incoming websocket messages (client events) |
| 94 | + async def process_ws_events(): |
| 95 | + async for msg in ws: |
| 96 | + if msg.type == WSMsgType.TEXT: |
| 97 | + payload = json.loads(msg.data) |
| 98 | + # print(f"<< {payload}") |
| 99 | + state.select(payload["pick"]) |
| 100 | + elif msg.type == WSMsgType.ERROR: |
| 101 | + print(f"WebSocket error: {ws.exception()}") |
| 102 | + |
| 103 | + # Process incoming queue messages (watchdog filesystem events) |
| 104 | + async def process_fs_events(): |
| 105 | + request.app["broadcaster"].subscribe(fs_events_queue) |
| 106 | + while True: |
| 107 | + msg: DirModifiedEvent | FileModifiedEvent = await fs_events_queue.get() |
| 108 | + # print(msg) |
| 109 | + if msg.is_directory: |
| 110 | + # print(f"directory {msg.src_path} changed") |
| 111 | + await state.refresh(ws) |
| 112 | + elif Path(str(msg.src_path)).name == state.selected: |
| 113 | + # print(f"change detected in {state.selected}") |
| 114 | + await state.send_reload(ws) |
| 115 | + |
| 116 | + # Process both sources in parallel |
| 117 | + try: |
| 118 | + await asyncio.gather(process_ws_events(), process_fs_events()) |
| 119 | + except asyncio.CancelledError: |
| 120 | + pass |
| 121 | + finally: |
| 122 | + request.app["broadcaster"].unsubscribe(fs_events_queue) |
| 123 | + await ws.close() |
| 124 | + |
| 125 | + return ws |
| 126 | + |
| 127 | + |
| 128 | +async def _index(_): |
| 129 | + return web.FileResponse(_STATIC_DIR / "index.html") |
| 130 | + |
| 131 | + |
| 132 | +async def _frag(request): |
| 133 | + fname = request.match_info["name"] |
| 134 | + return web.FileResponse(_SHADER_DIR / f"{fname}.frag") |
| 135 | + |
| 136 | + |
| 137 | +async def _init_app(): |
| 138 | + app = web.Application() |
| 139 | + app.router.add_get("/", _index) |
| 140 | + app.router.add_static("/static", _STATIC_DIR) |
| 141 | + app.router.add_get("/frag/{name}.frag", _frag) |
| 142 | + app.router.add_get("/ws", _ws_handler) |
| 143 | + |
| 144 | + print(f"Shader directory: {_SHADER_DIR}") |
| 145 | + |
| 146 | + # Setup event broadcaster: 1 filewatcher for N websockets |
| 147 | + event_queue = asyncio.Queue() |
| 148 | + app["broadcaster"] = EventBroadcaster(event_queue) |
| 149 | + asyncio.create_task(app["broadcaster"].start()) |
| 150 | + |
| 151 | + # File watcher events handler that will feed the broadcaster |
| 152 | + event_handler = AsyncFileSystemEventHandler(event_queue) |
| 153 | + |
| 154 | + # Spawn file system observer |
| 155 | + observer = Observer() |
| 156 | + observer.schedule(event_handler, path=_SHADER_DIR.as_posix(), recursive=False) |
| 157 | + observer.start() |
| 158 | + |
| 159 | + async def on_cleanup(_): |
| 160 | + observer.stop() |
| 161 | + observer.join() |
| 162 | + |
| 163 | + app.on_cleanup.append(on_cleanup) |
| 164 | + return app |
| 165 | + |
| 166 | + |
| 167 | +def main(): |
| 168 | + web.run_app(_init_app(), host="localhost", port=8080) |
0 commit comments