Skip to content

Commit 051d794

Browse files
Simplify EventBus: default to synchronous dispatch
EventBus.publish() now dispatches directly when no wrapper is set, eliminating the need for on_ready callbacks, log buffering, and explicit registration in headless mode.
1 parent 9436e88 commit 051d794

4 files changed

Lines changed: 12 additions & 48 deletions

File tree

event_bus.py

Lines changed: 9 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -7,26 +7,11 @@
77
class EventBus:
88
def __init__(self):
99
self._listeners: defaultdict[Type[BaseEvent], list[Callable[[Any], None]]] = defaultdict(list)
10-
self._main_thread_callback: Callable[[Callable], None] | None = None
11-
self._ready_callbacks: list[Callable[[], None]] = []
12-
13-
def register_main_thread_callback(self, fn: Callable[[Callable], None]):
14-
"""Set the function to call listeners from the main thread (e.g., Textual app.call_from_thread)."""
15-
self._main_thread_callback = fn
16-
17-
# Notify anyone waiting for the event bus to be ready
18-
for callback in self._ready_callbacks:
19-
callback()
20-
self._ready_callbacks.clear()
21-
22-
def on_ready(self, callback: Callable[[], None]):
23-
"""Register a callback to be called when the event bus is ready."""
24-
if self._main_thread_callback:
25-
# Already ready, call immediately
26-
callback()
27-
else:
28-
# Not ready yet, queue it
29-
self._ready_callbacks.append(callback)
10+
self._dispatch_wrapper: Callable[[Callable], None] | None = None
11+
12+
def register_dispatch_wrapper(self, fn: Callable[[Callable], None]):
13+
"""Set a wrapper for dispatching listeners (e.g., Textual's app.call_from_thread)."""
14+
self._dispatch_wrapper = fn
3015

3116
def subscribe(self, event_type: Type[BaseEvent], listener: Callable[[Any], None]):
3217
"""Registers a listener for a specific event type."""
@@ -39,7 +24,7 @@ def _dispatch():
3924
for listener in self._listeners[type(event)]:
4025
listener(event)
4126

42-
if not self._main_thread_callback:
43-
raise RuntimeError("No main thread callback set. Call register_main_thread_callback() first.")
44-
45-
self._main_thread_callback(_dispatch)
27+
if self._dispatch_wrapper:
28+
self._dispatch_wrapper(_dispatch)
29+
else:
30+
_dispatch()

plain2code.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -236,8 +236,6 @@ def render(args, run_state: RunState, event_bus: EventBus): # noqa: C901
236236
)
237237

238238
if args.headless:
239-
# Dispatch events synchronously without a TUI.
240-
event_bus.register_main_thread_callback(lambda fn: fn())
241239
# In headless mode, this will be the only output
242240
print(f"Render started. Render ID: {run_state.render_id}")
243241
module_renderer.render_module()

plain2code_logger.py

Lines changed: 2 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -40,15 +40,10 @@ class TuiLoggingHandler(logging.Handler):
4040
def __init__(self, event_bus: EventBus):
4141
super().__init__()
4242
self.event_bus = event_bus
43-
self._buffer = []
44-
self.start_time = time.time() # Record start time for offset calculation
45-
46-
# Register to be notified when event bus is ready
47-
self.event_bus.on_ready(self._flush_buffer)
43+
self.start_time = time.time()
4844

4945
def emit(self, record):
5046
try:
51-
# Extract structured data from the log record
5247
offset_seconds = record.created - self.start_time
5348
minutes = int(offset_seconds // 60)
5449
seconds = int(offset_seconds % 60)
@@ -60,28 +55,14 @@ def emit(self, record):
6055
message=record.getMessage(),
6156
timestamp=timestamp,
6257
)
63-
64-
# Try to publish, fall back to buffering if not ready
65-
if self.event_bus._main_thread_callback:
66-
self.event_bus.publish(event)
67-
else:
68-
self._buffer.append(event)
58+
self.event_bus.publish(event)
6959
except RuntimeError:
7060
# We're going to get this crash after the TUI app is closed (forcefully).
7161
# NOTE: This should be more thought out.
7262
pass
7363
except Exception:
7464
self.handleError(record)
7565

76-
def _flush_buffer(self):
77-
"""Flush buffered log messages to the event bus."""
78-
for event in self._buffer:
79-
try:
80-
self.event_bus.publish(event)
81-
except Exception:
82-
pass
83-
self._buffer.clear()
84-
8566

8667
class CrashLogHandler(logging.Handler):
8768
def __init__(self):

tui/plain2code_tui.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -125,7 +125,7 @@ def get_active_script_types(self) -> list[ScriptOutputType]:
125125

126126
def on_mount(self) -> None:
127127
"""Called when the app is mounted."""
128-
self.event_bus.register_main_thread_callback(self.call_from_thread)
128+
self.event_bus.register_dispatch_wrapper(self.call_from_thread)
129129

130130
self.event_bus.subscribe(RenderStateUpdated, self.on_render_state_updated)
131131
self.event_bus.subscribe(RenderCompleted, self.on_render_completed)

0 commit comments

Comments
 (0)