use crate::config::Config;
use ratatui::layout::Rect;
use std::cell::RefCell;
use std::collections::{HashMap, HashSet};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TmuxWindow {
pub index: u32,
pub name: String,
pub cwd: Option<String>,
pub has_bell: bool,
pub workspace: Option<String>,
}
#[derive(Debug, Clone)]
pub enum TerminalsRow {
Service(String),
Window(TmuxWindow),
NewSentinel,
}
#[derive(Debug, Clone)]
pub struct TerminalsView {
pub tmux_available: Option<bool>,
pub session_name: String,
pub windows: Vec<TmuxWindow>,
pub previews: HashMap<u32, Vec<String>>,
pub selected: usize,
pub previous_bell: HashMap<u32, bool>,
pub pending_bell_emit: bool,
pub suppress_next_bell_emit: bool,
pub row_rects: RefCell<Vec<Rect>>,
}
impl TerminalsView {
pub fn default_for(config: &Config) -> Self {
let project = config.project.name.as_deref().unwrap_or("croft");
Self {
tmux_available: None,
session_name: format!("croft-{project}"),
windows: Vec::new(),
previews: HashMap::new(),
selected: 0,
previous_bell: HashMap::new(),
pending_bell_emit: false,
suppress_next_bell_emit: false,
row_rects: RefCell::new(Vec::new()),
}
}
pub fn set_tmux_available(&mut self, available: bool) {
self.tmux_available = Some(available);
}
pub fn set_preview(&mut self, index: u32, lines: Vec<String>) {
self.previews.insert(index, lines);
}
pub fn preview(&self, index: u32) -> Option<&Vec<String>> {
self.previews.get(&index)
}
pub fn take_pending_bell(&mut self) -> bool {
std::mem::replace(&mut self.pending_bell_emit, false)
}
pub fn silence_next_bell(&mut self) {
self.suppress_next_bell_emit = true;
}
pub fn select_next(&mut self, total_rows: usize) {
if total_rows > 0 {
self.selected = (self.selected + 1).min(total_rows - 1);
}
}
pub fn select_prev(&mut self) {
self.selected = self.selected.saturating_sub(1);
}
pub fn select_at(&mut self, idx: usize, total_rows: usize) {
if total_rows == 0 {
return;
}
self.selected = idx.min(total_rows - 1);
}
pub fn set_windows(&mut self, windows: Vec<TmuxWindow>, total_rows_after: usize) {
let live: HashSet<u32> = windows.iter().map(|w| w.index).collect();
let mut fresh_bell = false;
for w in &windows {
let prev = self.previous_bell.get(&w.index).copied().unwrap_or(false);
if w.has_bell && !prev {
fresh_bell = true;
}
self.previous_bell.insert(w.index, w.has_bell);
}
self.previous_bell.retain(|k, _| live.contains(k));
if self.suppress_next_bell_emit {
self.suppress_next_bell_emit = false;
} else if fresh_bell {
self.pending_bell_emit = true;
}
self.previews.retain(|k, _| live.contains(k));
self.windows = windows;
if total_rows_after > 0 && self.selected >= total_rows_after {
self.selected = total_rows_after - 1;
}
}
}