1pub mod background;
24pub mod chrome;
25pub mod layout;
26pub mod render;
27pub mod theme;
28
29pub use background::{BackgroundState, BackgroundStyle, ALL_STYLES, PREVIEW_H, PREVIEW_W};
30pub use chrome::{
31 is_local_id, keypress_to_bytes, ChromeOutput, ContainerEntry, ConversationKind,
32 ConversationPickerEntry, GenerationDefaults, ImageEntry, InputDialog, InputField, ModelEntry,
33 PaneSummary, PreChatSettingsState, PreChatType, RpcRequest, ServiceEntry, ServiceMode,
34 ShellChrome, ShellMode, Toast, ToastLevel, WindowSummary, WorkerEntry, WorkerTab, LOCAL_ID_BIT,
35 MENU_ITEMS,
36};
37pub use layout::{
38 CellUpdate, CursorState, FrameContent, FrameUpdate, LayoutTree, PaneId, PaneSource, PaneState,
39 PaneStorage, ScrollUpdate,
40};
41
42pub enum CompositorInput {
48 ServerFrame { pane_id: u32, ansi: Vec<u8> },
50 ServerFrameCapnp { frame: FrameUpdate },
52 AppFrame { app_id: u32, ansi: Vec<u8> },
54 WindowList(Vec<WindowSummary>),
56 PaneClosed { pane_id: u32 },
58 KeyPress(waxterm::input::KeyPress),
60 MouseClick { col: u16, row: u16 },
62 Resize(u16, u16),
64 AppExited { app_id: u32 },
66 ServiceList(Vec<crate::chrome::ServiceEntry>),
68 WorkerList {
70 sandboxes: Vec<crate::chrome::WorkerEntry>,
71 pool_summary: String,
72 },
73 WorkerImageList {
75 images: Vec<crate::chrome::ImageEntry>,
76 },
77}
78
79pub enum CompositorOutput {
81 Redraw,
83 Rpc(RpcRequest),
85 RouteInput { app_id: u32, data: Vec<u8> },
87 Quit,
89}
90
91pub struct Compositor {
97 pub chrome: ShellChrome,
98 pub layout: LayoutTree,
99 cols: u16,
100 rows: u16,
101}
102
103impl Compositor {
104 pub fn new(
105 cols: u16,
106 rows: u16,
107 session_id: u32,
108 viewer_id: u32,
109 windows: Vec<WindowSummary>,
110 models: Vec<ModelEntry>,
111 ) -> Self {
112 let pane_rows = rows.saturating_sub(4);
113 let pane_cols = cols.saturating_sub(2);
114 Self {
115 chrome: ShellChrome::new(pane_cols, pane_rows, session_id, viewer_id, windows, models),
116 layout: LayoutTree::new(pane_cols, pane_rows),
117 cols,
118 rows,
119 }
120 }
121
122 pub fn pane_block_area(&self, frame_area: ratatui::layout::Rect) -> ratatui::layout::Rect {
125 use ratatui::layout::{Constraint, Layout};
126 if matches!(self.chrome.mode, ShellMode::Fullscreen) {
127 return frame_area;
128 }
129 let [_, pane_block, _] = Layout::vertical([
130 Constraint::Length(1),
131 Constraint::Min(1),
132 Constraint::Length(1),
133 ])
134 .areas(frame_area);
135 pane_block
136 }
137
138 pub fn active_pane_id(&self) -> u32 {
140 self.chrome.active_pane_id()
141 }
142
143 pub fn render(&self, frame: &mut ratatui::Frame) {
145 render::draw(frame, &self.chrome, &self.layout);
146 }
147
148 pub fn handle(&mut self, input: CompositorInput) -> Vec<CompositorOutput> {
151 match input {
152 CompositorInput::ServerFrame { pane_id, ansi } => {
153 let pane = self.layout.get_or_create_server(pane_id);
154 pane.feed(&ansi);
155 vec![CompositorOutput::Redraw]
156 }
157
158 CompositorInput::ServerFrameCapnp { frame } => {
159 self.layout.apply_server_frame(&frame);
160 vec![CompositorOutput::Redraw]
161 }
162
163 CompositorInput::AppFrame { app_id, ansi } => {
164 if let Some(pane) = self.layout.get_pane_mut(app_id) {
165 pane.feed(&ansi);
166 vec![CompositorOutput::Redraw]
167 } else {
168 vec![]
169 }
170 }
171
172 CompositorInput::WindowList(wins) => {
173 if self.chrome.update_windows(wins) {
174 vec![CompositorOutput::Redraw]
175 } else {
176 vec![]
177 }
178 }
179
180 CompositorInput::PaneClosed { pane_id } => {
181 self.layout.remove_pane(pane_id);
182 vec![CompositorOutput::Redraw]
183 }
184
185 CompositorInput::KeyPress(key) => {
186 let co = self.chrome.handle_key(key);
187 self.dispatch_chrome(co)
188 }
189
190 CompositorInput::MouseClick { col, row } => self.handle_mouse_click(col, row),
191
192 CompositorInput::Resize(cols, rows) => {
193 self.cols = cols;
194 self.rows = rows;
195 let pane_rows = rows.saturating_sub(4);
196 let pane_cols = cols.saturating_sub(2);
197 self.chrome.cols = pane_cols;
198 self.chrome.pane_rows = pane_rows;
199 self.layout.resize(pane_cols, pane_rows);
200 vec![CompositorOutput::Redraw]
201 }
202
203 CompositorInput::ServiceList(entries) => {
204 self.chrome.update_service_list(entries);
205 if let ShellMode::ServiceManager { ref mut selected } = self.chrome.mode {
206 *selected = (*selected).min(self.chrome.service_list.len().saturating_sub(1));
207 }
208 vec![CompositorOutput::Redraw]
209 }
210
211 CompositorInput::WorkerList {
212 sandboxes,
213 pool_summary,
214 } => {
215 self.chrome.update_worker_list(sandboxes, pool_summary);
216 if let ShellMode::WorkerManager {
217 ref mut sandbox_sel,
218 ref mut container_sel,
219 ..
220 } = self.chrome.mode
221 {
222 *sandbox_sel =
223 (*sandbox_sel).min(self.chrome.worker_list.len().saturating_sub(1));
224 if let Some(sb) = self.chrome.worker_list.get(*sandbox_sel) {
225 *container_sel =
226 (*container_sel).min(sb.containers.len().saturating_sub(1));
227 } else {
228 *container_sel = 0;
229 }
230 }
231 vec![CompositorOutput::Redraw]
232 }
233
234 CompositorInput::WorkerImageList { images } => {
235 self.chrome.image_list = images;
236 if let ShellMode::WorkerManager {
237 ref mut image_sel, ..
238 } = self.chrome.mode
239 {
240 *image_sel = (*image_sel).min(self.chrome.image_list.len().saturating_sub(1));
241 }
242 vec![CompositorOutput::Redraw]
243 }
244
245 CompositorInput::AppExited { app_id } => {
246 self.layout.remove_pane(app_id);
247 self.chrome.private_panes.remove(&app_id);
248
249 let mut out = vec![CompositorOutput::Redraw];
251 if let Some(win_idx) = self
252 .chrome
253 .windows
254 .iter()
255 .position(|w| w.panes.iter().any(|p| p.id == app_id))
256 {
257 let window_id = self.chrome.windows[win_idx].id;
258 self.chrome.windows.remove(win_idx);
259 if self.chrome.windows.is_empty() {
260 self.chrome.active_win = 0;
261 } else {
262 self.chrome.active_win =
263 self.chrome.active_win.min(self.chrome.windows.len() - 1);
264 }
265 out.push(CompositorOutput::Rpc(RpcRequest::CloseWindow {
266 session_id: self.chrome.session_id,
267 window_id,
268 }));
269 }
270 out
271 }
272 }
273 }
274
275 fn dispatch_chrome(&mut self, chrome_outputs: Vec<ChromeOutput>) -> Vec<CompositorOutput> {
276 chrome_outputs
277 .into_iter()
278 .map(|co| match co {
279 ChromeOutput::Redraw => CompositorOutput::Redraw,
280 ChromeOutput::Rpc(req) => match req {
281 RpcRequest::Quit => CompositorOutput::Quit,
282 other => CompositorOutput::Rpc(other),
283 },
284 ChromeOutput::RouteInput { app_id, data } => {
285 CompositorOutput::RouteInput { app_id, data }
286 }
287 })
288 .collect()
289 }
290
291 fn handle_mouse_click(&mut self, col: u16, row: u16) -> Vec<CompositorOutput> {
294 use crate::render::{centered_rect, modal_percentages};
295 use crate::theme::CLOSE_BUTTON_WIDTH;
296
297 match self.chrome.mode {
298 ShellMode::Normal => {
300 let pane_top_row = 1u16;
301 if row == pane_top_row
302 && col >= self.cols.saturating_sub(1 + CLOSE_BUTTON_WIDTH)
303 && col < self.cols.saturating_sub(1)
304 {
305 if let Some(win) = self.chrome.windows.get(self.chrome.active_win) {
306 let sid = self.chrome.session_id;
307 let wid = win.id;
308 return vec![CompositorOutput::Rpc(RpcRequest::CloseWindow {
309 session_id: sid,
310 window_id: wid,
311 })];
312 }
313 }
314 vec![]
315 }
316
317 ShellMode::StartMenu { .. } => {
319 let popup_w: u16 = 26;
320 let popup_h: u16 = MENU_ITEMS.len() as u16 + 2;
321 let popup_y = self.rows.saturating_sub(popup_h + 1);
322 let inner_y = popup_y + 1;
323 let inner_x = 1u16;
324 let inner_right = popup_w.saturating_sub(1);
325
326 if row == popup_y
328 && col >= popup_w.saturating_sub(1 + CLOSE_BUTTON_WIDTH)
329 && col < popup_w.saturating_sub(1)
330 {
331 let out = self.chrome.handle_key(waxterm::input::KeyPress::Escape);
332 return self.dispatch_chrome(out);
333 }
334
335 if row >= inner_y
337 && row < inner_y + MENU_ITEMS.len() as u16
338 && col >= inner_x
339 && col < inner_right
340 {
341 let item_idx = (row - inner_y) as usize;
342 self.chrome.mode = ShellMode::Normal;
343 let out = self.chrome.execute_menu_action(item_idx);
344 return self.dispatch_chrome(out);
345 }
346
347 if col >= popup_w || row < popup_y || row >= popup_y + popup_h {
349 let out = self.chrome.handle_key(waxterm::input::KeyPress::Escape);
350 return self.dispatch_chrome(out);
351 }
352
353 vec![]
354 }
355
356 ShellMode::Console => vec![],
359
360 ShellMode::ModelList
362 | ShellMode::Settings
363 | ShellMode::ConversationPicker { .. }
364 | ShellMode::ServiceManager { .. }
365 | ShellMode::WorkerManager { .. }
366 | ShellMode::PreChatSettings(_) => {
367 let (pct_w, pct_h) = match modal_percentages(&self.chrome.mode) {
368 Some(p) => p,
369 None => return vec![],
370 };
371 let area = ratatui::layout::Rect::new(0, 0, self.cols, self.rows);
372 let modal = centered_rect(pct_w, pct_h, area);
373
374 if row == modal.y
376 && col >= modal.x + modal.width.saturating_sub(1 + CLOSE_BUTTON_WIDTH)
377 && col < modal.x + modal.width.saturating_sub(1)
378 {
379 let out = self.chrome.handle_key(waxterm::input::KeyPress::Escape);
380 return self.dispatch_chrome(out);
381 }
382
383 if col < modal.x
385 || col >= modal.x + modal.width
386 || row < modal.y
387 || row >= modal.y + modal.height
388 {
389 let out = self.chrome.handle_key(waxterm::input::KeyPress::Escape);
390 return self.dispatch_chrome(out);
391 }
392
393 let first_item_row = modal.y + 2; let inside_cols = col > modal.x && col < modal.x + modal.width - 1;
396
397 if inside_cols && row >= first_item_row {
398 let idx = (row - first_item_row) as usize;
399 match self.chrome.mode {
400 ShellMode::ModelList => {
401 if idx < self.chrome.model_list.items_mut().len() {
402 self.chrome.model_list.set_selected(idx);
403 let out = self.chrome.handle_key(waxterm::input::KeyPress::Enter);
404 return self.dispatch_chrome(out);
405 }
406 }
407 ShellMode::Settings => {
408 let inner_h = modal.height.saturating_sub(2);
410 let list_height = 5u16.min(inner_h / 2);
411 let max_visible = list_height.saturating_sub(1) as usize;
412 if idx < self.chrome.settings_list.items_mut().len()
413 && idx < max_visible
414 {
415 self.chrome.settings_list.set_selected(idx);
416 let out = self.chrome.handle_key(waxterm::input::KeyPress::Enter);
417 return self.dispatch_chrome(out);
418 }
419 }
420 ShellMode::ConversationPicker { ref mut list, .. } => {
421 if idx < list.items_mut().len() {
422 list.set_selected(idx);
423 let out = self.chrome.handle_key(waxterm::input::KeyPress::Enter);
424 return self.dispatch_chrome(out);
425 }
426 }
427 ShellMode::ServiceManager { ref mut selected } => {
428 if idx < self.chrome.service_list.len() {
430 *selected = idx;
431 return vec![CompositorOutput::Redraw];
432 }
433 }
434 ShellMode::WorkerManager {
435 ref mut sandbox_sel,
436 show_containers: false,
437 ..
438 } if idx < self.chrome.worker_list.len() => {
439 *sandbox_sel = idx;
440 let out = self.chrome.handle_key(waxterm::input::KeyPress::Enter);
441 return self.dispatch_chrome(out);
442 }
443 _ => {}
444 }
445 }
446
447 vec![]
448 }
449 _ => vec![],
450 }
451 }
452}
453
454#[cfg(test)]
455mod tests {
456 use super::*;
457
458 fn make_compositor() -> Compositor {
459 Compositor::new(120, 40, 1, 1, vec![], vec![])
460 }
461
462 #[test]
463 fn mouse_click_start_menu_item() {
464 let mut comp = make_compositor();
465 comp.chrome.mode = ShellMode::StartMenu { selected: 0 };
466 let popup_h = MENU_ITEMS.len() as u16 + 2;
469 let popup_y = 40u16.saturating_sub(popup_h + 1);
470 let first_item_row = popup_y + 1;
471 let out = comp.handle(CompositorInput::MouseClick {
473 col: 5,
474 row: first_item_row + 3,
475 });
476 assert!(matches!(comp.chrome.mode, ShellMode::ModelList));
478 assert!(out.iter().any(|o| matches!(o, CompositorOutput::Redraw)));
479 }
480
481 #[test]
482 fn mouse_click_outside_start_menu_dismisses() {
483 let mut comp = make_compositor();
484 comp.chrome.mode = ShellMode::StartMenu { selected: 0 };
485 let out = comp.handle(CompositorInput::MouseClick { col: 80, row: 20 });
487 assert!(matches!(comp.chrome.mode, ShellMode::Normal));
488 assert!(out.iter().any(|o| matches!(o, CompositorOutput::Redraw)));
489 }
490
491 #[test]
492 fn mouse_click_outside_modal_dismisses() {
493 let mut comp = make_compositor();
494 comp.chrome.mode = ShellMode::ModelList;
495 let out = comp.handle(CompositorInput::MouseClick { col: 0, row: 0 });
497 assert!(matches!(comp.chrome.mode, ShellMode::Normal));
498 assert!(out.iter().any(|o| matches!(o, CompositorOutput::Redraw)));
499 }
500
501 #[test]
502 fn mouse_click_model_list_item() {
503 use crate::render::{centered_rect, modal_percentages};
504 let models = vec![
505 ModelEntry {
506 model_ref: "a:main".into(),
507 path: "/tmp".into(),
508 loaded: true,
509 loading: false,
510 gen_defaults: GenerationDefaults::default(),
511 },
512 ModelEntry {
513 model_ref: "b:main".into(),
514 path: "/tmp".into(),
515 loaded: true,
516 loading: false,
517 gen_defaults: GenerationDefaults::default(),
518 },
519 ];
520 let mut comp = Compositor::new(120, 40, 1, 1, vec![], models);
521 comp.chrome.mode = ShellMode::ModelList;
522 let area = ratatui::layout::Rect::new(0, 0, 120, 40);
523 let (pw, ph) = modal_percentages(&ShellMode::ModelList).unwrap();
524 let modal = centered_rect(pw, ph, area);
525 let first_item_row = modal.y + 2; let item_col = modal.x + 2;
527 let out = comp.handle(CompositorInput::MouseClick {
529 col: item_col,
530 row: first_item_row + 1,
531 });
532 assert!(out.iter().any(|o| matches!(o,
533 CompositorOutput::Rpc(RpcRequest::ListConversations { ref model_ref })
534 if model_ref == "b:main"
535 )));
536 }
537
538 #[test]
539 fn mouse_click_close_button_on_pane() {
540 use crate::theme::CLOSE_BUTTON_WIDTH;
541 let wins = vec![WindowSummary {
542 id: 1,
543 name: "w".into(),
544 active_pane_id: 1,
545 panes: vec![PaneSummary {
546 id: 1,
547 cols: 80,
548 rows: 24,
549 is_private: false,
550 }],
551 }];
552 let mut comp = Compositor::new(120, 40, 1, 1, wins, vec![]);
553 let out = comp.handle(CompositorInput::MouseClick {
555 col: 120 - 1 - CLOSE_BUTTON_WIDTH + 1, row: 1,
557 });
558 assert!(out
559 .iter()
560 .any(|o| matches!(o, CompositorOutput::Rpc(RpcRequest::CloseWindow { .. }))));
561 }
562
563 #[test]
564 fn mouse_click_close_button_on_modal() {
565 use crate::render::{centered_rect, modal_percentages};
566 use crate::theme::CLOSE_BUTTON_WIDTH;
567 let mut comp = make_compositor();
568 comp.chrome.mode = ShellMode::ModelList;
569 let area = ratatui::layout::Rect::new(0, 0, 120, 40);
570 let (pw, ph) = modal_percentages(&ShellMode::ModelList).unwrap();
571 let modal = centered_rect(pw, ph, area);
572 let out = comp.handle(CompositorInput::MouseClick {
573 col: modal.x + modal.width - 1 - CLOSE_BUTTON_WIDTH + 1,
574 row: modal.y,
575 });
576 assert!(matches!(comp.chrome.mode, ShellMode::Normal));
577 assert!(out.iter().any(|o| matches!(o, CompositorOutput::Redraw)));
578 }
579
580 #[test]
581 fn mouse_click_bottom_gap_dismisses_start_menu() {
582 let mut comp = make_compositor();
583 comp.chrome.mode = ShellMode::StartMenu { selected: 0 };
584 let popup_h = MENU_ITEMS.len() as u16 + 2;
586 let popup_y = 40u16.saturating_sub(popup_h + 1);
587 let out = comp.handle(CompositorInput::MouseClick {
588 col: 5,
589 row: popup_y + popup_h,
590 });
591 assert!(matches!(comp.chrome.mode, ShellMode::Normal));
592 assert!(out.iter().any(|o| matches!(o, CompositorOutput::Redraw)));
593 }
594}