agentmux_srv/server/
pane_measure.rs1use std::collections::HashMap;
13use std::sync::{Mutex, OnceLock};
14use std::time::Duration;
15
16use super::*;
17use crate::backend::mps_events::{MeasurePanes, MeasurePanesEvent};
18use crate::backend::rpc_types::MeasuredPane;
19
20const WAIT: Duration = Duration::from_secs(2);
22
23type Waiters = Mutex<HashMap<String, tokio::sync::oneshot::Sender<Vec<MeasuredPane>>>>;
25
26fn waiters() -> &'static Waiters {
27 static W: OnceLock<Waiters> = OnceLock::new();
28 W.get_or_init(Default::default)
29}
30
31pub(crate) fn answered(request_id: &str, sizes: Vec<MeasuredPane>) -> bool {
33 let tx = waiters().lock().unwrap_or_else(|e| e.into_inner()).remove(request_id);
34 tx.is_some_and(|tx| tx.send(sizes).is_ok())
35}
36
37async fn ask(state: &AppState, window_id: &str, blocks: Vec<String>) -> Option<Vec<MeasuredPane>> {
39 let id = uuid::Uuid::new_v4().to_string();
40 let (tx, rx) = tokio::sync::oneshot::channel();
42 waiters().lock().unwrap_or_else(|e| e.into_inner()).insert(id.clone(), tx);
43 state.broker.publish_event::<MeasurePanes>(&MeasurePanesEvent { request_id: id.clone(), block_ids: blocks }, vec![window_id.to_string()], 0);
44 match tokio::time::timeout(WAIT, rx).await {
45 Ok(Ok(sizes)) => Some(sizes),
46 _ => {
47 waiters().lock().unwrap_or_else(|e| e.into_inner()).remove(&id);
48 None
49 }
50 }
51}
52
53fn showing_panes(window: &serde_json::Value) -> Vec<String> {
55 let tabs = window.get("tabs").and_then(|t| t.as_array()).into_iter().flatten();
56 let showing = tabs.filter(|t| t.get("active").and_then(|a| a.as_bool()) == Some(true));
57 showing
58 .flat_map(|t| t.get("panes").and_then(|p| p.as_array()).into_iter().flatten())
59 .filter(|p| p.get("floating").and_then(|f| f.as_bool()) != Some(true))
60 .filter_map(|p| p.get("block_id").and_then(|b| b.as_str()).map(str::to_string))
61 .collect()
62}
63
64fn size_of(answer: &[MeasuredPane], block: &str) -> Option<(u64, u64)> {
66 let m = answer.iter().find(|m| m.block_id == block)?;
67 match (m.width, m.height) {
68 (Some(w), Some(h)) if w > 0.0 && h > 0.0 => Some((w.round() as u64, h.round() as u64)),
69 _ => None,
70 }
71}
72
73pub(super) async fn report_docked(state: &AppState, layout: &mut serde_json::Value) {
76 let Some(windows) = layout.get_mut("windows").and_then(|w| w.as_array_mut()) else { return };
77 let asked: Vec<(String, Vec<String>)> = windows
78 .iter()
79 .filter_map(|w| Some((w.get("window_id")?.as_str()?.to_string(), showing_panes(w))))
80 .filter(|(_, panes)| !panes.is_empty())
81 .collect();
82 let answers = futures_util::future::join_all(asked.iter().map(|(win, panes)| ask(state, win, panes.clone()))).await;
83 for window in windows.iter_mut() {
84 let win = window.get("window_id").and_then(|w| w.as_str()).map(str::to_string).unwrap_or_default();
85 let showing = asked.iter().position(|(w, _)| *w == win);
86 let answer = showing.and_then(|i| answers[i].as_deref());
87 let tabs = window.get_mut("tabs").and_then(|t| t.as_array_mut()).into_iter().flatten();
88 for tab in tabs {
89 let active = tab.get("active").and_then(|a| a.as_bool()) == Some(true);
90 for pane in tab.get_mut("panes").and_then(|p| p.as_array_mut()).into_iter().flatten() {
91 if pane.get("floating").and_then(|f| f.as_bool()) == Some(true) {
92 continue;
93 }
94 let block = pane.get("block_id").and_then(|b| b.as_str()).unwrap_or_default().to_string();
95 let measured = if active { answer.and_then(|a| size_of(a, &block)) } else { None };
96 match measured {
97 Some((w, h)) => pane["size"] = json!({ "width": w, "height": h }),
98 None => {
99 pane["size"] = json!(null);
100 pane["size_unavailable"] = json!(if !active {
101 "its tab is not showing"
102 } else if answer.is_none() {
103 "the window did not answer (it may be hidden or still starting)"
104 } else {
105 "the window does not draw this pane now"
106 });
107 }
108 }
109 }
110 }
111 }
112}
113
114#[cfg(test)]
115#[path = "pane_measure_tests.rs"]
116mod tests;