use std::{collections::BTreeMap, sync::Arc, time::Duration};
use agent_client_protocol::v1::schema::SessionId as AcpSessionId;
use rho_protocol::{BackgroundItem, BackgroundWork, ProcessOutput, SessionId};
use tokio::time::{interval, Interval, MissedTickBehavior};
use super::Attacher;
use crate::app::acp::{inputs::InputContext, AcpClientPort};
pub(super) const READ_EVERY: Duration = Duration::from_millis(250);
pub(super) struct Outputs {
reader: Option<Reader>,
followed: BTreeMap<String, u64>,
reads: Option<Interval>,
}
struct Reader {
attacher: Arc<dyn Attacher>,
port: Arc<dyn AcpClientPort>,
session: SessionId,
acp_id: AcpSessionId,
}
impl Reader {
async fn read(&self, process: &str, from: u64) -> Option<ProcessOutput> {
self.attacher
.process_output(&self.session, process, from)
.await
}
fn tell(&self, process: &str, output: &ProcessOutput) -> u64 {
let text = text(output);
if !text.is_empty() {
self.port.terminal_output(&self.acp_id, process, &text);
}
output.next_cursor
}
}
impl Outputs {
pub(super) fn new(context: &InputContext, attacher: &Arc<dyn Attacher>) -> Self {
let reader = context.features.display_terminals().then(|| Reader {
attacher: Arc::clone(attacher),
port: Arc::clone(&context.port),
session: context.session.clone(),
acp_id: context.acp_id.clone(),
});
Self {
reader,
followed: BTreeMap::new(),
reads: None,
}
}
pub(super) async fn due(&mut self) {
match &mut self.reads {
Some(reads) => {
reads.tick().await;
}
None => std::future::pending().await,
}
}
pub(super) async fn read(&mut self) {
let Some(reader) = &self.reader else { return };
for (process, cursor) in &mut self.followed {
if let Some(output) = reader.read(process, *cursor).await {
*cursor = reader.tell(process, &output);
}
}
}
pub(super) async fn changed(&mut self, current: &[BackgroundWork]) {
let Some(reader) = &self.reader else { return };
let running = running(current);
let stopped: Vec<_> = self
.followed
.keys()
.filter(|process| !running.contains(&process.as_str()))
.cloned()
.collect();
for process in stopped {
if let Some(cursor) = self.followed.remove(&process) {
if let Some(output) = reader.read(&process, cursor).await {
reader.tell(&process, &output);
}
}
}
for process in running {
self.followed.entry(process.to_owned()).or_insert(0);
}
self.schedule();
}
pub(super) async fn snapshot(
&mut self,
current: &[BackgroundWork],
) -> BTreeMap<String, String> {
self.followed.clear();
let mut snapshots = BTreeMap::new();
if let Some(reader) = &self.reader {
for process in running(current) {
let (text, next) = match reader.read(process, 0).await {
Some(output) => (text(&output), output.next_cursor),
None => (String::new(), 0),
};
snapshots.insert(process.to_owned(), text);
self.followed.insert(process.to_owned(), next);
}
}
self.schedule();
snapshots
}
pub(super) fn stop(&mut self) {
self.followed.clear();
self.schedule();
}
fn schedule(&mut self) {
if self.followed.is_empty() {
self.reads = None;
} else if self.reads.is_none() {
let mut reads = interval(READ_EVERY);
reads.set_missed_tick_behavior(MissedTickBehavior::Delay);
self.reads = Some(reads);
}
}
}
fn text(output: &ProcessOutput) -> String {
output.chunks.iter().map(|chunk| &*chunk.text).collect()
}
fn running(work: &[BackgroundWork]) -> Vec<&str> {
work.iter()
.filter(|work| work.status.is_running())
.filter_map(|work| match &work.item {
BackgroundItem::Process { id } => Some(id.as_str()),
_ => None,
})
.collect()
}