agent_hub_runtime/core/preview/
external_open.rs1use super::{super::error::AppError, OpenedDocument, Preview};
3use serde::Serialize;
4use std::{
5 path::PathBuf,
6 sync::{Arc, Mutex},
7};
8
9#[derive(Default)]
10pub struct ExternalOpens {
11 pending: Mutex<Vec<OpenedDocument>>,
12 signal: Mutex<Option<Arc<dyn Fn() + Send + Sync>>>,
13}
14
15#[derive(Debug, Serialize)]
16pub struct OpenReceipt {
17 pub id: String,
18 pub path: PathBuf,
19 pub status: &'static str,
20}
21
22impl Preview {
23 pub fn set_external_open_signal(&self, signal: impl Fn() + Send + Sync + 'static) {
24 *self
25 .external_opens
26 .signal
27 .lock()
28 .unwrap_or_else(|e| e.into_inner()) = Some(Arc::new(signal));
29 }
30
31 pub fn queue_external_document(&self, path: &str) -> Result<OpenReceipt, AppError> {
32 if self.closed.load(std::sync::atomic::Ordering::Acquire) {
33 return Err(AppError::cancelled("Preview is shutting down"));
34 }
35 let opened = self.open_document_path(path)?;
36 let mut pending = self
37 .external_opens
38 .pending
39 .lock()
40 .map_err(|_| AppError::internal("File-open queue unavailable"))?;
41 if self.closed.load(std::sync::atomic::Ordering::Acquire) {
42 self.documents.close(&opened.document.id);
43 return Err(AppError::cancelled("Preview is shutting down"));
44 }
45 let duplicate = pending
46 .iter()
47 .find(|item| item.document.path == opened.document.path);
48 let receipt = if let Some(existing) = duplicate {
49 self.documents.close(&opened.document.id);
50 OpenReceipt {
51 id: existing.document.id.clone(),
52 path: existing.document.path.clone(),
53 status: "requested",
54 }
55 } else {
56 if pending.len() >= 12 {
57 self.documents.close(&opened.document.id);
58 return Err(AppError::invalid_input(
59 "Close or open pending documents first",
60 ));
61 }
62 let receipt = OpenReceipt {
63 id: opened.document.id.clone(),
64 path: opened.document.path.clone(),
65 status: "requested",
66 };
67 pending.push(opened);
68 receipt
69 };
70 drop(pending);
71 let signal = self
72 .external_opens
73 .signal
74 .lock()
75 .map_err(|_| AppError::internal("File-open signal unavailable"))?
76 .clone();
77 if let Some(signal) = signal {
78 signal();
79 }
80 Ok(receipt)
81 }
82
83 pub fn take_external_documents(&self) -> Result<Vec<OpenedDocument>, AppError> {
84 let mut pending = self
85 .external_opens
86 .pending
87 .lock()
88 .map_err(|_| AppError::internal("File-open queue unavailable"))?;
89 Ok(std::mem::take(&mut *pending))
90 }
91
92 pub(super) fn clear_external_documents(&self) {
93 if let Ok(documents) = self.take_external_documents() {
94 for document in documents {
95 self.documents.close(&document.document.id);
96 }
97 }
98 self.external_opens
99 .signal
100 .lock()
101 .unwrap_or_else(|e| e.into_inner())
102 .take();
103 }
104}
105
106#[cfg(test)]
107mod tests;