Lutra/crates/control/src/backend.rs
danny f49b42836a F2: ui.screenshot captures the webview without focusing the window
On Windows the webview renders itself into a PNG through WebView2
CapturePreview (scheduled on the main thread via with_webview, 10 s
timeout, PNG signature and 64 MiB cap checked). macOS and Linux keep the
xcap screen-region capture as a documented fallback, now without focusing.
app.focus is the only control method that changes focus. A --control
instance opens its window without taking the foreground. An ignored live
test samples the foreground window while the app starts and takes five
screenshots and fails if Lutra ever owns it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 17:13:38 +01:00

124 lines
4 KiB
Rust

//! The interface the control channel needs from its host, and the
//! subscriber list hosts use to publish engine events.
use std::path::Path;
use std::sync::mpsc::{SyncSender, TrySendError};
use std::sync::{Mutex, PoisonError};
use lutra_engine::{CommandInfo, EngineError, Event};
use serde_json::Value;
/// Queue of events for one subscriber. Bounded so that a client that stops
/// reading cannot make the host buffer without limit.
pub type EventSink = SyncSender<Event>;
/// Capacity of each subscriber's queue.
pub const EVENT_QUEUE: usize = 4096;
/// What the control channel can ask the host to do.
///
/// The desktop app implements it on top of its engine and window; tests
/// implement it with a bare engine. Methods are called from connection
/// threads, so implementations synchronise internally.
pub trait Backend: Send + Sync + 'static {
/// Runs an engine command, applies its effects and publishes its events.
///
/// # Errors
/// The engine's error for the command.
fn execute(&self, command: &str, params: Value) -> Result<Value, EngineError>;
/// Lists every command with its current enabled state.
fn list_commands(&self) -> Vec<CommandInfo>;
/// Writes a PNG screenshot of the main window to `path`. It must not
/// focus, raise or show any window; only [`Backend::focus`] may.
///
/// # Errors
/// A message if there is no window to capture or the file cannot be
/// written.
fn screenshot(&self, path: &Path) -> Result<(), String>;
/// Adds a subscriber that receives every engine event from now on.
fn subscribe(&self, sink: EventSink);
/// Brings the main window to the front, for the CLI and a second app
/// start. The only method that changes focus. The default has no window and fails.
///
/// # Errors
/// A message if there is no window or it cannot be focused.
fn focus(&self) -> Result<(), String> {
Err("there is no window".into())
}
}
/// The event subscribers of a host.
#[derive(Debug, Default)]
pub struct Subscribers {
/// Live subscribers.
sinks: Mutex<Vec<EventSink>>,
}
impl Subscribers {
/// Adds a subscriber.
pub fn add(&self, sink: EventSink) {
self.sinks
.lock()
.unwrap_or_else(PoisonError::into_inner)
.push(sink);
}
/// Sends `events` to every subscriber, in order. A subscriber whose
/// queue is full or whose receiver is gone is dropped: a full queue
/// means the client stopped reading, and dropping it keeps the host from
/// blocking or buffering without limit.
pub fn publish(&self, events: &[Event]) {
if events.is_empty() {
return;
}
let mut sinks = self.sinks.lock().unwrap_or_else(PoisonError::into_inner);
sinks.retain(|sink| {
events
.iter()
.all(|event| match sink.try_send(event.clone()) {
Ok(()) => true,
Err(TrySendError::Full(_) | TrySendError::Disconnected(_)) => false,
})
});
}
/// Number of live subscribers.
pub fn len(&self) -> usize {
self.sinks
.lock()
.unwrap_or_else(PoisonError::into_inner)
.len()
}
/// Whether there is no subscriber.
pub fn is_empty(&self) -> bool {
self.len() == 0
}
}
#[cfg(test)]
mod tests {
use std::sync::mpsc::sync_channel;
use super::*;
#[test]
fn publishes_in_order_and_drops_dead_or_slow_subscribers() {
let subs = Subscribers::default();
let (fast_tx, fast_rx) = sync_channel(10);
let (slow_tx, _slow_rx) = sync_channel(1);
let (dead_tx, dead_rx) = sync_channel(10);
subs.add(fast_tx);
subs.add(slow_tx);
subs.add(dead_tx);
drop(dead_rx);
subs.publish(&[Event::ProjectClosed, Event::BufferClosed { id: 1 }]);
assert_eq!(subs.len(), 1);
assert_eq!(fast_rx.try_recv().unwrap(), Event::ProjectClosed);
assert_eq!(fast_rx.try_recv().unwrap(), Event::BufferClosed { id: 1 });
}
}