| 1 | //! A view of the model's workspace-scoped PTYs, with ordered human input. |
| 2 | //! |
| 3 | //! Shell creation, input and reads run on one dedicated blocking worker; |
| 4 | //! the UI applies new output to the selected PTY screen. |
| 5 | |
| 6 | use codewhale_localization::MessageId; |
| 7 | use crossterm::event::KeyEvent; |
| 8 | #[cfg(all(unix, not(target_env = "ohos")))] |
| 9 | use crossterm::event::{KeyCode, KeyModifiers}; |
| 10 | use crossterm::event::{MouseButton, MouseEvent, MouseEventKind}; |
| 11 | use ratatui::{Frame, layout::Rect, prelude::Widget, style::Style, text::Line, widgets::Paragraph}; |
| 12 | |
| 13 | #[cfg(all(unix, not(target_env = "ohos")))] |
| 14 | use super::model::RailPanel; |
| 15 | use crate::tui::app::App; |
| 16 | use crate::tui::shell_key_routing::ShellBindingId; |
| 17 | #[cfg(all(unix, not(target_env = "ohos")))] |
| 18 | use crate::tui::shell_key_routing::{binding, display_chord}; |
| 19 | |
| 20 | #[cfg(all(unix, not(target_env = "ohos")))] |
| 21 | use codewhale_engine::tools::terminal_session::{self, TerminalSessionInfo}; |
| 22 | #[cfg(all(unix, not(target_env = "ohos")))] |
| 23 | use std::{ |
| 24 | collections::VecDeque, |
| 25 | path::PathBuf, |
| 26 | sync::mpsc, |
| 27 | time::{Duration, Instant}, |
| 28 | }; |
| 29 | |
| 30 | #[cfg(all(unix, not(target_env = "ohos")))] |
| 31 | #[derive(Debug, Default)] |
| 32 | pub(super) struct TerminalDock { |
| 33 | #[cfg(all(unix, not(target_env = "ohos")))] |
| 34 | workspace: PathBuf, |
| 35 | #[cfg(all(unix, not(target_env = "ohos")))] |
| 36 | worker: Option<Worker>, |
| 37 | #[cfg(all(unix, not(target_env = "ohos")))] |
| 38 | sessions: Vec<TerminalSessionInfo>, |
| 39 | #[cfg(all(unix, not(target_env = "ohos")))] |
| 40 | commands: Vec<codewhale_engine::tools::shell::ShellJobSnapshot>, |
| 41 | #[cfg(all(unix, not(target_env = "ohos")))] |
| 42 | selected: Option<String>, |
| 43 | #[cfg(all(unix, not(target_env = "ohos")))] |
| 44 | command_output: Vec<u8>, |
| 45 | screens: VecDeque<PtyScreen>, |
| 46 | pending_output: Option<terminal_session::OutputChunk>, |
| 47 | #[cfg(all(unix, not(target_env = "ohos")))] |
| 48 | dropped: u64, |
| 49 | #[cfg(all(unix, not(target_env = "ohos")))] |
| 50 | last_poll: Option<Instant>, |
| 51 | #[cfg(all(unix, not(target_env = "ohos")))] |
| 52 | refreshing: bool, |
| 53 | #[cfg(all(unix, not(target_env = "ohos")))] |
| 54 | size: Option<(u16, u16)>, |
| 55 | #[cfg(all(unix, not(target_env = "ohos")))] |
| 56 | lost: bool, |
| 57 | #[cfg(all(unix, not(target_env = "ohos")))] |
| 58 | creating: bool, |
| 59 | #[cfg(all(unix, not(target_env = "ohos")))] |
| 60 | session_tabs: Vec<(String, Rect)>, |
| 61 | #[cfg(all(unix, not(target_env = "ohos")))] |
| 62 | scroll: usize, |
| 63 | #[cfg(all(unix, not(target_env = "ohos")))] |
| 64 | error: Option<String>, |
| 65 | } |
| 66 | |
| 67 | #[cfg(all(unix, not(target_env = "ohos")))] |
| 68 | struct PtyScreen { |
| 69 | id: String, |
| 70 | parser: tui_term::vt100::Parser, |
| 71 | next: u64, |
| 72 | omitted: u64, |
| 73 | control: OutputControl, |
| 74 | } |
| 75 | |
| 76 | #[cfg(all(unix, not(target_env = "ohos")))] |
| 77 | #[derive(Debug, Default)] |
| 78 | enum OutputControl { |
| 79 | #[default] |
| 80 | Ground, |
| 81 | Escape, |
| 82 | IgnoreOsc, |
| 83 | } |
| 84 | |
| 85 | #[cfg(all(unix, not(target_env = "ohos")))] |
| 86 | impl std::fmt::Debug for PtyScreen { |
| 87 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 88 | f.debug_struct("PtyScreen") |
| 89 | .field("id", &self.id) |
| 90 | .field("next", &self.next) |
| 91 | .finish_non_exhaustive() |
| 92 | } |
| 93 | } |
| 94 | |
| 95 | #[cfg(all(unix, not(target_env = "ohos")))] |
| 96 | impl PtyScreen { |
| 97 | const SCROLLBACK_ROWS: usize = 256; |
| 98 | |
| 99 | fn new(id: String, size: (u16, u16)) -> Self { |
| 100 | Self { |
| 101 | id, |
| 102 | parser: tui_term::vt100::Parser::new(size.0, size.1, Self::SCROLLBACK_ROWS), |
| 103 | next: 0, |
| 104 | omitted: 0, |
| 105 | control: OutputControl::Ground, |
| 106 | } |
| 107 | } |
| 108 | |
| 109 | fn apply(&mut self, mut chunk: terminal_session::OutputChunk) { |
| 110 | if chunk.offset > self.next { |
| 111 | self.omitted += chunk.offset - self.next; |
| 112 | let size = self.parser.screen().size(); |
| 113 | self.parser = tui_term::vt100::Parser::new(size.0, size.1, Self::SCROLLBACK_ROWS); |
| 114 | self.control = OutputControl::Ground; |
| 115 | } |
| 116 | let skip = usize::try_from(self.next.saturating_sub(chunk.offset)).unwrap_or(usize::MAX); |
| 117 | let Some(bytes) = chunk.bytes.get_mut(skip..) else { |
| 118 | return; |
| 119 | }; |
| 120 | for byte in bytes.iter_mut() { |
| 121 | self.control = match (&self.control, *byte) { |
| 122 | (_, 0x1b) => OutputControl::Escape, |
| 123 | (OutputControl::Escape, b']') => { |
| 124 | const PRIVATE_MESSAGE: u8 = b'^'; |
| 125 | *byte = PRIVATE_MESSAGE; |
| 126 | OutputControl::IgnoreOsc |
| 127 | } |
| 128 | (OutputControl::IgnoreOsc, 7) => { |
| 129 | *byte = 0x18; |
| 130 | OutputControl::Ground |
| 131 | } |
| 132 | (_, 0x18 | 0x1a) => OutputControl::Ground, |
| 133 | (OutputControl::IgnoreOsc, _) => OutputControl::IgnoreOsc, |
| 134 | (OutputControl::Escape, 0..=0x1f | 0x7f..=0xff) => OutputControl::Escape, |
| 135 | _ => OutputControl::Ground, |
| 136 | }; |
| 137 | } |
| 138 | self.parser.process(bytes); |
| 139 | self.next = chunk.next_cursor; |
| 140 | } |
| 141 | |
| 142 | fn render(&self, area: Rect, buf: &mut ratatui::buffer::Buffer, style: Style, focused: bool) { |
| 143 | use tui_term::widget::{Cursor, PseudoTerminal}; |
| 144 | PseudoTerminal::new(self.parser.screen()) |
| 145 | .cursor(Cursor::default().visibility(focused)) |
| 146 | .render(area, buf); |
| 147 | for y in area.top()..area.bottom() { |
| 148 | for x in area.left()..area.right() { |
| 149 | let cell = &mut buf[(x, y)]; |
| 150 | if cell.fg == ratatui::style::Color::Reset { |
| 151 | cell.fg = style.fg.unwrap_or_default(); |
| 152 | } |
| 153 | if cell.bg == ratatui::style::Color::Reset { |
| 154 | cell.bg = style.bg.unwrap_or_default(); |
| 155 | } |
| 156 | if x + 1 == area.right() && unicode_width::UnicodeWidthStr::width(cell.symbol()) > 1 |
| 157 | { |
| 158 | cell.set_symbol(" "); |
| 159 | } |
| 160 | } |
| 161 | } |
| 162 | } |
| 163 | } |
| 164 | |
| 165 | #[cfg(all(unix, not(target_env = "ohos")))] |
| 166 | impl TerminalDock { |
| 167 | fn select(&mut self, id: String) { |
| 168 | self.selected = Some(id); |
| 169 | self.pending_output = None; |
| 170 | self.command_output.clear(); |
| 171 | self.dropped = self.selected_screen().map_or(0, |screen| screen.omitted); |
| 172 | self.error = None; |
| 173 | self.size = None; |
| 174 | self.last_poll = None; |
| 175 | self.lost = false; |
| 176 | self.scroll = 0; |
| 177 | if let Some(screen) = self |
| 178 | .screens |
| 179 | .iter_mut() |
| 180 | .find(|screen| Some(&screen.id) == self.selected.as_ref()) |
| 181 | { |
| 182 | screen.parser.screen_mut().set_scrollback(0); |
| 183 | } |
| 184 | } |
| 185 | |
| 186 | fn selected_screen(&self) -> Option<&PtyScreen> { |
| 187 | self.screens |
| 188 | .iter() |
| 189 | .find(|screen| Some(&screen.id) == self.selected.as_ref()) |
| 190 | } |
| 191 | |
| 192 | fn screen_at_size(&mut self, id: &str, size: (u16, u16)) -> &mut PtyScreen { |
| 193 | if self.screens.back().is_none_or(|screen| screen.id != id) { |
| 194 | let screen = self |
| 195 | .screens |
| 196 | .iter() |
| 197 | .position(|screen| screen.id == id) |
| 198 | .and_then(|index| self.screens.remove(index)) |
| 199 | .unwrap_or_else(|| PtyScreen::new(id.to_owned(), size)); |
| 200 | if self.screens.len() == 4 { |
| 201 | self.screens.pop_front(); |
| 202 | } |
| 203 | self.screens.push_back(screen); |
| 204 | } |
| 205 | let screen = self.screens.back_mut().expect("selected screen"); |
| 206 | if screen.parser.screen().size() != size { |
| 207 | screen.parser.screen_mut().set_size(size.0, size.1); |
| 208 | } |
| 209 | screen |
| 210 | } |
| 211 | |
| 212 | fn scroll_by(&mut self, up: bool, rows: usize) { |
| 213 | let moved = |current: usize| { |
| 214 | if up { |
| 215 | current.saturating_add(rows) |
| 216 | } else { |
| 217 | current.saturating_sub(rows) |
| 218 | } |
| 219 | }; |
| 220 | if let Some(screen) = self |
| 221 | .screens |
| 222 | .iter_mut() |
| 223 | .find(|screen| Some(&screen.id) == self.selected.as_ref()) |
| 224 | { |
| 225 | let scroll = moved(screen.parser.screen().scrollback()); |
| 226 | screen.parser.screen_mut().set_scrollback(scroll); |
| 227 | } else { |
| 228 | self.scroll = moved(self.scroll); |
| 229 | } |
| 230 | } |
| 231 | } |
| 232 | |
| 233 | // A copied presentation must not share an input queue or steal replies. |
| 234 | #[cfg(all(unix, not(target_env = "ohos")))] |
| 235 | impl Clone for TerminalDock { |
| 236 | fn clone(&self) -> Self { |
| 237 | Self::default() |
| 238 | } |
| 239 | } |
| 240 | |
| 241 | #[cfg(all(unix, not(target_env = "ohos")))] |
| 242 | #[derive(Debug)] |
| 243 | struct Worker { |
| 244 | requests: mpsc::SyncSender<Request>, |
| 245 | replies: mpsc::Receiver<Reply>, |
| 246 | } |
| 247 | |
| 248 | #[cfg(all(unix, not(target_env = "ohos")))] |
| 249 | #[derive(Debug)] |
| 250 | enum Request { |
| 251 | Refresh { |
| 252 | selected: Option<String>, |
| 253 | cursor: u64, |
| 254 | session: String, |
| 255 | }, |
| 256 | Create { |
| 257 | policy: codewhale_sandbox::SandboxPolicy, |
| 258 | owner: String, |
| 259 | }, |
| 260 | Input { |
| 261 | name: String, |
| 262 | id: String, |
| 263 | bytes: Vec<u8>, |
| 264 | policy: codewhale_sandbox::SandboxPolicy, |
| 265 | }, |
| 266 | Resize { |
| 267 | name: String, |
| 268 | id: String, |
| 269 | rows: u16, |
| 270 | cols: u16, |
| 271 | }, |
| 272 | } |
| 273 | |
| 274 | #[cfg(all(unix, not(target_env = "ohos")))] |
| 275 | #[derive(Debug)] |
| 276 | enum Reply { |
| 277 | Snapshot { |
| 278 | requested: Option<String>, |
| 279 | sessions: Vec<TerminalSessionInfo>, |
| 280 | output: Option<terminal_session::OutputChunk>, |
| 281 | commands: Vec<codewhale_engine::tools::shell::ShellJobSnapshot>, |
| 282 | }, |
| 283 | Created(String), |
| 284 | InputWritten(String), |
| 285 | Error(String), |
| 286 | } |
| 287 | |
| 288 | #[cfg(all(unix, not(target_env = "ohos")))] |
| 289 | impl Worker { |
| 290 | fn start( |
| 291 | workspace: PathBuf, |
| 292 | shell_manager: codewhale_engine::tools::shell::SharedShellManager, |
| 293 | ) -> Result<Self, String> { |
| 294 | let (requests, incoming) = mpsc::sync_channel(128); |
| 295 | let (outgoing, replies) = mpsc::sync_channel(32); |
| 296 | std::thread::Builder::new() |
| 297 | .name("terminal-dock".into()) |
| 298 | .spawn(move || { |
| 299 | while let Ok(request) = incoming.recv() { |
| 300 | let reply = match request { |
| 301 | Request::Refresh { |
| 302 | selected, |
| 303 | cursor, |
| 304 | session, |
| 305 | } => match terminal_session::inspect_workspace_since( |
| 306 | &workspace, |
| 307 | selected.as_deref(), |
| 308 | Some(cursor), |
| 309 | ) { |
| 310 | Ok((sessions, output)) => Reply::Snapshot { |
| 311 | requested: selected, |
| 312 | sessions, |
| 313 | output, |
| 314 | commands: shell_manager |
| 315 | .lock() |
| 316 | .map(|mut manager| { |
| 317 | dock_commands(manager.list_jobs_for_session(&session)) |
| 318 | }) |
| 319 | .unwrap_or_default(), |
| 320 | }, |
| 321 | Err(error) => Reply::Error(error), |
| 322 | }, |
| 323 | Request::Create { policy, owner } => { |
| 324 | let name = |
| 325 | format!("user-{}", &uuid::Uuid::new_v4().simple().to_string()[..8]); |
| 326 | match terminal_session::get_or_create( |
| 327 | &owner, |
| 328 | &name, |
| 329 | &workspace, |
| 330 | policy, |
| 331 | &shell_manager, |
| 332 | ) |
| 333 | .and_then(|_| terminal_session::inspect_workspace(&workspace, None)) |
| 334 | { |
| 335 | Ok((sessions, _)) => { |
| 336 | match sessions.into_iter().find(|session| session.name == name) |
| 337 | { |
| 338 | Some(session) => Reply::Created(session.id), |
| 339 | None => Reply::Error("created terminal disappeared".into()), |
| 340 | } |
| 341 | } |
| 342 | Err(error) => Reply::Error(error), |
| 343 | } |
| 344 | } |
| 345 | Request::Input { |
| 346 | name, |
| 347 | id, |
| 348 | bytes, |
| 349 | policy, |
| 350 | } => { |
| 351 | match terminal_session::write_dock_input( |
| 352 | &workspace, &name, &id, &bytes, &policy, |
| 353 | ) { |
| 354 | Ok(()) => Reply::InputWritten(id), |
| 355 | Err(error) => Reply::Error(error), |
| 356 | } |
| 357 | } |
| 358 | Request::Resize { |
| 359 | name, |
| 360 | id, |
| 361 | rows, |
| 362 | cols, |
| 363 | } => { |
| 364 | let result = terminal_session::resize_dock_session( |
| 365 | &workspace, &name, &id, rows, cols, |
| 366 | ); |
| 367 | match result { |
| 368 | Ok(()) => continue, |
| 369 | Err(error) => Reply::Error(error), |
| 370 | } |
| 371 | } |
| 372 | }; |
| 373 | if outgoing.send(reply).is_err() { |
| 374 | break; |
| 375 | } |
| 376 | } |
| 377 | }) |
| 378 | .map_err(|error| error.to_string())?; |
| 379 | Ok(Self { requests, replies }) |
| 380 | } |
| 381 | } |
| 382 | |
| 383 | #[cfg(all(unix, not(target_env = "ohos")))] |
| 384 | const COMMAND_TAB_PREFIX: &str = "cmd:"; |
| 385 | |
| 386 | #[cfg(all(unix, not(target_env = "ohos")))] |
| 387 | const FINISHED_COMMAND_TABS: usize = 5; |
| 388 | |
| 389 | #[cfg(all(unix, not(target_env = "ohos")))] |
| 390 | fn clipped_command_label(command: &str) -> String { |
| 391 | let mut graphemes = unicode_segmentation::UnicodeSegmentation::graphemes(command, true); |
| 392 | let mut label: String = graphemes.by_ref().take(32).collect(); |
| 393 | if graphemes.next().is_some() { |
| 394 | label.push('…'); |
| 395 | } |
| 396 | label |
| 397 | } |
| 398 | |
| 399 | #[cfg(all(unix, not(target_env = "ohos")))] |
| 400 | fn command_job_id(tab: &str) -> Option<&str> { |
| 401 | tab.strip_prefix(COMMAND_TAB_PREFIX) |
| 402 | } |
| 403 | |
| 404 | #[cfg(all(unix, not(target_env = "ohos")))] |
| 405 | fn command_tab_id(job: &codewhale_engine::tools::shell::ShellJobSnapshot) -> String { |
| 406 | format!("{COMMAND_TAB_PREFIX}{}", job.id) |
| 407 | } |
| 408 | |
| 409 | #[cfg(all(unix, not(target_env = "ohos")))] |
| 410 | fn dock_commands( |
| 411 | jobs: Vec<codewhale_engine::tools::shell::ShellJobSnapshot>, |
| 412 | ) -> Vec<codewhale_engine::tools::shell::ShellJobSnapshot> { |
| 413 | use codewhale_engine::tools::shell::ShellStatus; |
| 414 | let (mut running, mut finished): (Vec<_>, Vec<_>) = jobs |
| 415 | .into_iter() |
| 416 | .partition(|job| job.status == ShellStatus::Running); |
| 417 | finished.sort_by_key(|job| std::cmp::Reverse(job.finished_at)); |
| 418 | finished.truncate(FINISHED_COMMAND_TABS); |
| 419 | running.extend(finished); |
| 420 | running |
| 421 | } |
| 422 | |
| 423 | #[cfg(all(unix, not(target_env = "ohos")))] |
| 424 | fn command_output(job: &codewhale_engine::tools::shell::ShellJobSnapshot) -> Vec<u8> { |
| 425 | let mut output = job.stdout_tail.clone(); |
| 426 | if !job.stderr_tail.is_empty() { |
| 427 | if !output.is_empty() && !output.ends_with('\n') { |
| 428 | output.push('\n'); |
| 429 | } |
| 430 | output.push_str(&job.stderr_tail); |
| 431 | } |
| 432 | output.into_bytes() |
| 433 | } |
| 434 | |
| 435 | #[cfg(all(unix, not(target_env = "ohos")))] |
| 436 | fn tab_ids(dock: &TerminalDock) -> Vec<String> { |
| 437 | dock.sessions |
| 438 | .iter() |
| 439 | .map(|session| session.id.clone()) |
| 440 | .chain(dock.commands.iter().map(command_tab_id)) |
| 441 | .collect() |
| 442 | } |
| 443 | |
| 444 | #[cfg(all(unix, not(target_env = "ohos")))] |
| 445 | fn policy(app: &App) -> codewhale_sandbox::SandboxPolicy { |
| 446 | codewhale_engine::core::authority::sandbox_policy_for_turn( |
| 447 | app.mode, |
| 448 | app.approval_mode, |
| 449 | app.configured_sandbox_mode.as_deref(), |
| 450 | &app.workspace, |
| 451 | codewhale_engine::core::authority::SandboxNetworkAccess::from_config( |
| 452 | app.configured_sandbox_network, |
| 453 | ), |
| 454 | ) |
| 455 | } |
| 456 | |
| 457 | /// Called by the existing event loop, including when another panel is open. |
| 458 | pub(crate) fn poll(app: &mut App) { |
| 459 | #[cfg(all(unix, not(target_env = "ohos")))] |
| 460 | { |
| 461 | let visible = app.work_surface.panel == RailPanel::Terminal |
| 462 | && !app.work_surface.dismissed |
| 463 | && app.work_surface.explicit_view; |
| 464 | let session_id = app.current_session_id.clone().unwrap_or_default(); |
| 465 | let dock = &mut app.work_surface.terminal; |
| 466 | if dock.workspace != app.workspace { |
| 467 | *dock = TerminalDock { |
| 468 | workspace: app.workspace.clone(), |
| 469 | ..Default::default() |
| 470 | }; |
| 471 | } |
| 472 | tracing::trace!( |
| 473 | target: "codewhale::terminal_dock", |
| 474 | visible, |
| 475 | refreshing = dock.refreshing, |
| 476 | selected = ?dock.selected, |
| 477 | last_poll_age_ms = ?dock.last_poll.map(|last| last.elapsed().as_millis()), |
| 478 | "poll" |
| 479 | ); |
| 480 | if visible && dock.worker.is_none() && dock.error.is_none() { |
| 481 | let shell_manager = app |
| 482 | .runtime_services |
| 483 | .shell_manager |
| 484 | .clone() |
| 485 | .unwrap_or_else(|| { |
| 486 | codewhale_engine::tools::shell::new_shared_shell_manager(app.workspace.clone()) |
| 487 | }); |
| 488 | match Worker::start(app.workspace.clone(), shell_manager) { |
| 489 | Ok(worker) => dock.worker = Some(worker), |
| 490 | Err(error) => dock.error = Some(error), |
| 491 | } |
| 492 | } |
| 493 | while let Some(reply) = dock |
| 494 | .worker |
| 495 | .as_ref() |
| 496 | .and_then(|worker| worker.replies.try_recv().ok()) |
| 497 | { |
| 498 | match reply { |
| 499 | Reply::Snapshot { |
| 500 | requested, |
| 501 | sessions, |
| 502 | output, |
| 503 | commands, |
| 504 | } => { |
| 505 | tracing::trace!( |
| 506 | target: "codewhale::terminal_dock", |
| 507 | requested = ?requested, |
| 508 | selected = ?dock.selected, |
| 509 | accepted = dock.selected == requested, |
| 510 | session_states = ?sessions.iter().map(|session| (&session.id, session.state)).collect::<Vec<_>>(), |
| 511 | output_bytes = output.as_ref().map_or(0, |chunk| chunk.bytes.len()), |
| 512 | "snapshot" |
| 513 | ); |
| 514 | dock.refreshing = false; |
| 515 | if dock.selected != requested { |
| 516 | continue; |
| 517 | } |
| 518 | if dock.selected.is_none() { |
| 519 | dock.selected = sessions |
| 520 | .first() |
| 521 | .map(|session| session.id.clone()) |
| 522 | .or_else(|| commands.first().map(command_tab_id)); |
| 523 | } |
| 524 | let selected_command = dock |
| 525 | .selected |
| 526 | .as_deref() |
| 527 | .and_then(command_job_id) |
| 528 | .and_then(|id| commands.iter().find(|job| job.id == id)); |
| 529 | dock.lost = dock.selected.is_some() |
| 530 | && selected_command.is_none() |
| 531 | && !sessions |
| 532 | .iter() |
| 533 | .any(|session| Some(&session.id) == dock.selected.as_ref()); |
| 534 | let command_bytes = selected_command.map(command_output).unwrap_or_default(); |
| 535 | let screen = dock.selected_screen(); |
| 536 | let cursor = screen.map_or(0, |screen| screen.next); |
| 537 | let omitted = screen.map_or(0, |screen| screen.omitted); |
| 538 | let pending = output.filter(|chunk| chunk.next_cursor > cursor && !dock.lost); |
| 539 | let dropped = omitted |
| 540 | + pending |
| 541 | .as_ref() |
| 542 | .map_or(0, |chunk| chunk.offset.saturating_sub(cursor)); |
| 543 | if dock.sessions != sessions |
| 544 | || dock.commands != commands |
| 545 | || dock.command_output != command_bytes |
| 546 | || dock.dropped != dropped |
| 547 | || pending.is_some() |
| 548 | { |
| 549 | app.needs_redraw = true; |
| 550 | } |
| 551 | if let Some(chunk) = pending { |
| 552 | dock.pending_output = Some(chunk); |
| 553 | } |
| 554 | dock.screens |
| 555 | .retain(|screen| sessions.iter().any(|session| session.id == screen.id)); |
| 556 | dock.sessions = sessions; |
| 557 | dock.commands = commands; |
| 558 | dock.command_output = command_bytes; |
| 559 | dock.dropped = dropped; |
| 560 | } |
| 561 | Reply::Created(id) => { |
| 562 | dock.creating = false; |
| 563 | dock.select(id); |
| 564 | app.needs_redraw = true; |
| 565 | } |
| 566 | Reply::InputWritten(id) => { |
| 567 | if dock.selected.as_ref() == Some(&id) && dock.error.take().is_some() { |
| 568 | app.needs_redraw = true; |
| 569 | } |
| 570 | } |
| 571 | Reply::Error(error) => { |
| 572 | dock.creating = false; |
| 573 | dock.refreshing = false; |
| 574 | dock.error = Some(error); |
| 575 | app.needs_redraw = true; |
| 576 | } |
| 577 | } |
| 578 | } |
| 579 | if let Some(worker) = &dock.worker |
| 580 | && visible |
| 581 | && !dock.refreshing |
| 582 | && dock |
| 583 | .last_poll |
| 584 | .is_none_or(|last| last.elapsed() >= Duration::from_millis(100)) |
| 585 | { |
| 586 | match worker.requests.try_send(Request::Refresh { |
| 587 | cursor: dock.selected_screen().map_or(0, |screen| screen.next), |
| 588 | selected: dock.selected.clone(), |
| 589 | session: session_id.clone(), |
| 590 | }) { |
| 591 | Ok(()) => { |
| 592 | dock.refreshing = true; |
| 593 | dock.last_poll = Some(Instant::now()); |
| 594 | } |
| 595 | Err(error) => { |
| 596 | dock.error = Some(error.to_string()); |
| 597 | app.needs_redraw = true; |
| 598 | } |
| 599 | } |
| 600 | } |
| 601 | } |
| 602 | #[cfg(any(not(unix), target_env = "ohos"))] |
| 603 | let _ = app; |
| 604 | } |
| 605 | |
| 606 | #[cfg(all(unix, not(target_env = "ohos")))] |
| 607 | fn send(app: &mut App, request: Request) -> bool { |
| 608 | let dock = &mut app.work_surface.terminal; |
| 609 | let result = dock |
| 610 | .worker |
| 611 | .as_ref() |
| 612 | .ok_or_else(|| "terminal is not ready".to_string()) |
| 613 | .and_then(|worker| { |
| 614 | worker |
| 615 | .requests |
| 616 | .try_send(request) |
| 617 | .map_err(|error| error.to_string()) |
| 618 | }); |
| 619 | let sent = result.is_ok(); |
| 620 | if let Err(error) = result { |
| 621 | dock.error = Some(error); |
| 622 | } |
| 623 | dock.last_poll = None; |
| 624 | app.needs_redraw = true; |
| 625 | sent |
| 626 | } |
| 627 | |
| 628 | pub(super) fn handle_key(app: &mut App, key: KeyEvent) -> bool { |
| 629 | use crate::tui::shell_key_routing::route; |
| 630 | let action = route(crate::tui::shell_key_routing::Focus::TerminalPanel, &key); |
| 631 | if action == Some(ShellBindingId::TerminalDetach) { |
| 632 | super::interaction::release_focus(app); |
| 633 | return true; |
| 634 | } |
| 635 | // Shared shell shortcuts keep their meaning; ordinary Tab remains PTY input. |
| 636 | if action.is_some_and(|id| { |
| 637 | !matches!( |
| 638 | id, |
| 639 | ShellBindingId::TerminalNew |
| 640 | | ShellBindingId::TerminalNext |
| 641 | | ShellBindingId::TerminalPrevious |
| 642 | ) |
| 643 | }) { |
| 644 | return false; |
| 645 | } |
| 646 | #[cfg(all(unix, not(target_env = "ohos")))] |
| 647 | { |
| 648 | if action == Some(ShellBindingId::TerminalNew) { |
| 649 | if app.work_surface.terminal.worker.is_none() { |
| 650 | app.work_surface.terminal.error = None; |
| 651 | poll(app); |
| 652 | if app.work_surface.terminal.worker.is_none() { |
| 653 | return true; |
| 654 | } |
| 655 | } |
| 656 | let dock = &mut app.work_surface.terminal; |
| 657 | dock.select(uuid::Uuid::new_v4().to_string()); |
| 658 | dock.creating = true; |
| 659 | let owner = app.current_session_id.clone().unwrap_or_default(); |
| 660 | let sent = send( |
| 661 | app, |
| 662 | Request::Create { |
| 663 | policy: policy(app), |
| 664 | owner, |
| 665 | }, |
| 666 | ); |
| 667 | app.work_surface.terminal.creating = sent; |
| 668 | return true; |
| 669 | } |
| 670 | if matches!( |
| 671 | action, |
| 672 | Some(ShellBindingId::TerminalNext | ShellBindingId::TerminalPrevious) |
| 673 | ) { |
| 674 | let dock = &mut app.work_surface.terminal; |
| 675 | let tabs = tab_ids(dock); |
| 676 | if !tabs.is_empty() { |
| 677 | let current = tabs |
| 678 | .iter() |
| 679 | .position(|id| Some(id) == dock.selected.as_ref()); |
| 680 | let index = match (current, action) { |
| 681 | (Some(index), Some(ShellBindingId::TerminalPrevious)) => { |
| 682 | (index + tabs.len() - 1) % tabs.len() |
| 683 | } |
| 684 | (Some(index), _) => (index + 1) % tabs.len(), |
| 685 | (None, _) => 0, |
| 686 | }; |
| 687 | dock.select(tabs[index].clone()); |
| 688 | app.needs_redraw = true; |
| 689 | } |
| 690 | return true; |
| 691 | } |
| 692 | if matches!(key.code, KeyCode::PageUp | KeyCode::PageDown) { |
| 693 | let dock = &mut app.work_surface.terminal; |
| 694 | dock.scroll_by(key.code == KeyCode::PageUp, 8); |
| 695 | app.needs_redraw = true; |
| 696 | return true; |
| 697 | } |
| 698 | if let Some(bytes) = key_bytes(key) { |
| 699 | input(app, bytes); |
| 700 | } |
| 701 | } |
| 702 | true |
| 703 | } |
| 704 | |
| 705 | #[cfg(all(unix, not(target_env = "ohos")))] |
| 706 | fn input(app: &mut App, bytes: Vec<u8>) { |
| 707 | let dock = &app.work_surface.terminal; |
| 708 | if dock.selected.as_deref().and_then(command_job_id).is_some() { |
| 709 | return; |
| 710 | } |
| 711 | if let Some(session) = dock |
| 712 | .sessions |
| 713 | .iter() |
| 714 | .find(|session| Some(&session.id) == dock.selected.as_ref()) |
| 715 | { |
| 716 | send( |
| 717 | app, |
| 718 | Request::Input { |
| 719 | name: session.name.clone(), |
| 720 | id: session.id.clone(), |
| 721 | bytes, |
| 722 | policy: policy(app), |
| 723 | }, |
| 724 | ); |
| 725 | } else if !dock.sessions.is_empty() { |
| 726 | app.work_surface.terminal.error = Some(app.tr(MessageId::TerminalDockLost).into_owned()); |
| 727 | app.needs_redraw = true; |
| 728 | } |
| 729 | } |
| 730 | |
| 731 | pub(crate) fn handle_paste(app: &mut App, text: &str) -> bool { |
| 732 | if app.focus() != crate::tui::shell_key_routing::Focus::TerminalPanel |
| 733 | || app.work_surface.last_area.is_none() |
| 734 | { |
| 735 | return false; |
| 736 | } |
| 737 | #[cfg(all(unix, not(target_env = "ohos")))] |
| 738 | { |
| 739 | // Paste is deliberate terminal input. Limit it before queuing, and |
| 740 | // never pass terminal control sequences supplied by the clipboard. |
| 741 | if text.len() > 64 * 1024 |
| 742 | || text |
| 743 | .chars() |
| 744 | .any(|c| c.is_control() && !matches!(c, '\r' | '\n' | '\t')) |
| 745 | { |
| 746 | app.work_surface.terminal.error = |
| 747 | Some(app.tr(MessageId::TerminalDockPasteRefused).into_owned()); |
| 748 | } else { |
| 749 | input( |
| 750 | app, |
| 751 | text.replace("\r\n", "\n").replace('\r', "\n").into_bytes(), |
| 752 | ); |
| 753 | } |
| 754 | app.needs_redraw = true; |
| 755 | } |
| 756 | #[cfg(any(not(unix), target_env = "ohos"))] |
| 757 | let _ = text; |
| 758 | true |
| 759 | } |
| 760 | |
| 761 | #[cfg(all(unix, not(target_env = "ohos")))] |
| 762 | fn key_bytes(key: KeyEvent) -> Option<Vec<u8>> { |
| 763 | let control = |
| 764 | key.modifiers.contains(KeyModifiers::CONTROL) && !key.modifiers.contains(KeyModifiers::ALT); |
| 765 | let text = match key.code { |
| 766 | KeyCode::Char(c) if control && c.is_ascii() => vec![(c.to_ascii_uppercase() as u8) & 0x1f], |
| 767 | KeyCode::Char(c) => c.to_string().into_bytes(), |
| 768 | KeyCode::Enter => b"\r".to_vec(), |
| 769 | KeyCode::Tab => b"\t".to_vec(), |
| 770 | KeyCode::Backspace => vec![0x7f], |
| 771 | KeyCode::Up => b"\x1b[A".to_vec(), |
| 772 | KeyCode::Down => b"\x1b[B".to_vec(), |
| 773 | KeyCode::Right => b"\x1b[C".to_vec(), |
| 774 | KeyCode::Left => b"\x1b[D".to_vec(), |
| 775 | KeyCode::Home => b"\x1b[H".to_vec(), |
| 776 | KeyCode::End => b"\x1b[F".to_vec(), |
| 777 | KeyCode::Delete => b"\x1b[3~".to_vec(), |
| 778 | _ => return None, |
| 779 | }; |
| 780 | if key.modifiers.contains(KeyModifiers::ALT) && !key.modifiers.contains(KeyModifiers::CONTROL) { |
| 781 | Some([vec![0x1b], text].concat()) |
| 782 | } else { |
| 783 | Some(text) |
| 784 | } |
| 785 | } |
| 786 | |
| 787 | pub(super) fn render(frame: &mut Frame, area: Rect, app: &mut App) { |
| 788 | let style = Style::default() |
| 789 | .fg(app.ui_theme.text_body) |
| 790 | .bg(app.ui_theme.composer_bg); |
| 791 | let muted = Style::default() |
| 792 | .fg(app.ui_theme.text_muted) |
| 793 | .bg(app.ui_theme.composer_bg); |
| 794 | let mut lines = Vec::new(); |
| 795 | #[cfg(all(unix, not(target_env = "ohos")))] |
| 796 | { |
| 797 | use ansi_to_tui::IntoText; |
| 798 | let hints = app |
| 799 | .tr(MessageId::TerminalDockControls) |
| 800 | .replace( |
| 801 | "{new}", |
| 802 | &display_chord(binding(ShellBindingId::TerminalNew).footer_chord), |
| 803 | ) |
| 804 | .replace( |
| 805 | "{next}", |
| 806 | &display_chord(binding(ShellBindingId::TerminalNext).footer_chord), |
| 807 | ) |
| 808 | .replace( |
| 809 | "{detach}", |
| 810 | &display_chord(binding(ShellBindingId::TerminalDetach).footer_chord), |
| 811 | ); |
| 812 | let dock = &app.work_surface.terminal; |
| 813 | let mut session_tabs = Vec::new(); |
| 814 | // On compact hosts, remove help chrome before the shell's output. |
| 815 | if area.height >= 4 { |
| 816 | lines.push(Line::styled(hints, muted)); |
| 817 | } |
| 818 | if dock.creating { |
| 819 | lines.push(Line::styled(app.tr(MessageId::TerminalDockStarting), muted)); |
| 820 | } else if dock.lost { |
| 821 | lines.push(Line::styled(app.tr(MessageId::TerminalDockLost), muted)); |
| 822 | } else if dock.sessions.is_empty() && dock.commands.is_empty() { |
| 823 | lines.push(Line::styled( |
| 824 | app.tr(MessageId::TerminalDockEmpty) |
| 825 | .replace("{new}", binding(ShellBindingId::TerminalNew).footer_chord), |
| 826 | muted, |
| 827 | )); |
| 828 | } else if area.height >= 2 { |
| 829 | let ordered = dock |
| 830 | .sessions |
| 831 | .iter() |
| 832 | .filter(|session| Some(&session.id) == dock.selected.as_ref()) |
| 833 | .chain( |
| 834 | dock.sessions |
| 835 | .iter() |
| 836 | .filter(|session| Some(&session.id) != dock.selected.as_ref()), |
| 837 | ); |
| 838 | let mut spans = Vec::new(); |
| 839 | let mut column = area.x; |
| 840 | for session in ordered { |
| 841 | let selected = Some(&session.id) == dock.selected.as_ref(); |
| 842 | let status = if let Some(code) = session.exit_code { |
| 843 | app.tr(MessageId::TerminalDockExited) |
| 844 | .replace("{code}", &code.to_string()) |
| 845 | } else { |
| 846 | match session.state { |
| 847 | terminal_session::DurableTerminalState::Running => { |
| 848 | app.tr(MessageId::SubagentsStatusRunning) |
| 849 | } |
| 850 | terminal_session::DurableTerminalState::Canceled => { |
| 851 | app.tr(MessageId::AutomationRunStatusCanceled) |
| 852 | } |
| 853 | terminal_session::DurableTerminalState::Failed => { |
| 854 | app.tr(MessageId::AutomationRunStatusFailed) |
| 855 | } |
| 856 | _ => app.tr(MessageId::TerminalDockLive), |
| 857 | } |
| 858 | .into_owned() |
| 859 | }; |
| 860 | let activity = session |
| 861 | .last_activity |
| 862 | .map(|last| format!(" · {}s", last.elapsed().as_secs())) |
| 863 | .unwrap_or_default(); |
| 864 | let text = format!( |
| 865 | "{}{} ({status}{activity}) ", |
| 866 | if selected { "› " } else { "" }, |
| 867 | session.name |
| 868 | ); |
| 869 | let width = unicode_width::UnicodeWidthStr::width(text.as_str()) |
| 870 | .min(usize::from(area.right().saturating_sub(column))) |
| 871 | as u16; |
| 872 | if width == 0 { |
| 873 | break; |
| 874 | } |
| 875 | session_tabs.push(( |
| 876 | session.id.clone(), |
| 877 | Rect::new(column, area.y.saturating_add(lines.len() as u16), width, 1), |
| 878 | )); |
| 879 | column = column.saturating_add(width); |
| 880 | spans.push(ratatui::text::Span::styled( |
| 881 | text, |
| 882 | if selected && app.work_surface.focused { |
| 883 | style.bg(app.ui_theme.selection_bg) |
| 884 | } else { |
| 885 | style |
| 886 | }, |
| 887 | )); |
| 888 | } |
| 889 | for job in &dock.commands { |
| 890 | let id = command_tab_id(job); |
| 891 | let selected = Some(&id) == dock.selected.as_ref(); |
| 892 | let status = match job.exit_code { |
| 893 | Some(code) |
| 894 | if job.status != codewhale_engine::tools::shell::ShellStatus::Running => |
| 895 | { |
| 896 | app.tr(MessageId::TerminalDockExited) |
| 897 | .replace("{code}", &code.to_string()) |
| 898 | } |
| 899 | _ => app.tr(MessageId::SubagentsStatusRunning).into_owned(), |
| 900 | }; |
| 901 | let command = clipped_command_label(&job.command); |
| 902 | let text = format!( |
| 903 | "{}$ {command} ({status} · {}s) ", |
| 904 | if selected { "› " } else { "" }, |
| 905 | job.elapsed_ms / 1000 |
| 906 | ); |
| 907 | let width = unicode_width::UnicodeWidthStr::width(text.as_str()) |
| 908 | .min(usize::from(area.right().saturating_sub(column))) |
| 909 | as u16; |
| 910 | if width == 0 { |
| 911 | break; |
| 912 | } |
| 913 | session_tabs.push(( |
| 914 | id, |
| 915 | Rect::new(column, area.y.saturating_add(lines.len() as u16), width, 1), |
| 916 | )); |
| 917 | column = column.saturating_add(width); |
| 918 | spans.push(ratatui::text::Span::styled( |
| 919 | text, |
| 920 | if selected && app.work_surface.focused { |
| 921 | style.bg(app.ui_theme.selection_bg) |
| 922 | } else { |
| 923 | style |
| 924 | }, |
| 925 | )); |
| 926 | } |
| 927 | lines.push(Line::from(spans)); |
| 928 | } |
| 929 | if let Some(error) = &dock.error { |
| 930 | lines.push(Line::styled( |
| 931 | app.tr(MessageId::TerminalDockError) |
| 932 | .replace("{error}", error), |
| 933 | muted, |
| 934 | )); |
| 935 | } |
| 936 | if dock.dropped > 0 { |
| 937 | lines.push(Line::styled( |
| 938 | app.tr(MessageId::TerminalDockDropped) |
| 939 | .replace("{count}", &dock.dropped.to_string()), |
| 940 | muted, |
| 941 | )); |
| 942 | } |
| 943 | let header = lines.len().min(usize::from(area.height)) as u16; |
| 944 | let mut output_area = Rect::new( |
| 945 | area.x, |
| 946 | area.y.saturating_add(header), |
| 947 | area.width.min(512), |
| 948 | area.height.saturating_sub(header).min(256), |
| 949 | ); |
| 950 | output_area = output_area.intersection(frame.area()); |
| 951 | let session = dock |
| 952 | .sessions |
| 953 | .iter() |
| 954 | .find(|session| Some(&session.id) == dock.selected.as_ref()) |
| 955 | .map(|session| { |
| 956 | ( |
| 957 | session.id.clone(), |
| 958 | session.name.clone(), |
| 959 | session.exit_code.is_none(), |
| 960 | ) |
| 961 | }); |
| 962 | let scroll = if dock.selected.as_deref().and_then(command_job_id).is_some() { |
| 963 | let mut safe = String::new(); |
| 964 | codewhale_sanitize::sanitize::strip_ansi_keep_sgr_into( |
| 965 | &String::from_utf8_lossy(&dock.command_output), |
| 966 | &mut safe, |
| 967 | ); |
| 968 | let output = safe.into_text().unwrap_or_default(); |
| 969 | let available = usize::from(area.height.saturating_sub(header)); |
| 970 | let scroll = dock |
| 971 | .scroll |
| 972 | .min(output.lines.len().saturating_sub(available)); |
| 973 | let skip = output |
| 974 | .lines |
| 975 | .len() |
| 976 | .saturating_sub(available) |
| 977 | .saturating_sub(scroll); |
| 978 | lines.extend(output.lines.into_iter().skip(skip).take(available)); |
| 979 | scroll |
| 980 | } else { |
| 981 | 0 |
| 982 | }; |
| 983 | Paragraph::new(lines) |
| 984 | .style(style) |
| 985 | .render(area, frame.buffer_mut()); |
| 986 | let dock = &mut app.work_surface.terminal; |
| 987 | dock.session_tabs = session_tabs; |
| 988 | dock.scroll = scroll; |
| 989 | if let Some((id, name, running)) = session |
| 990 | && !output_area.is_empty() |
| 991 | { |
| 992 | let size = (output_area.height, output_area.width); |
| 993 | let pending = dock.pending_output.take(); |
| 994 | if pending |
| 995 | .as_ref() |
| 996 | .is_some_and(|chunk| chunk.next_cursor < chunk.total) |
| 997 | { |
| 998 | dock.last_poll = None; |
| 999 | } |
| 1000 | let screen = dock.screen_at_size(&id, size); |
| 1001 | if let Some(chunk) = pending { |
| 1002 | screen.apply(chunk); |
| 1003 | } |
| 1004 | screen.render( |
| 1005 | output_area, |
| 1006 | frame.buffer_mut(), |
| 1007 | style, |
| 1008 | running && app.work_surface.focused, |
| 1009 | ); |
| 1010 | if dock.size != Some(size) |
| 1011 | && send( |
| 1012 | app, |
| 1013 | Request::Resize { |
| 1014 | name, |
| 1015 | id, |
| 1016 | rows: size.0, |
| 1017 | cols: size.1, |
| 1018 | }, |
| 1019 | ) |
| 1020 | { |
| 1021 | app.work_surface.terminal.size = Some(size); |
| 1022 | } |
| 1023 | } |
| 1024 | } |
| 1025 | #[cfg(any(not(unix), target_env = "ohos"))] |
| 1026 | { |
| 1027 | lines.push(Line::styled( |
| 1028 | app.tr(MessageId::TerminalDockUnsupported), |
| 1029 | muted, |
| 1030 | )); |
| 1031 | Paragraph::new(lines) |
| 1032 | .style(style) |
| 1033 | .render(area, frame.buffer_mut()); |
| 1034 | } |
| 1035 | app.work_surface.visible_rows = usize::from(area.height); |
| 1036 | app.work_surface.total_rows = usize::from(area.height); |
| 1037 | app.work_surface.hitboxes.clear(); |
| 1038 | app.work_surface.latest_rows.clear(); |
| 1039 | } |
| 1040 | |
| 1041 | pub(super) fn handle_mouse(app: &mut App, mouse: MouseEvent) -> bool { |
| 1042 | if app.work_surface.panel != super::model::RailPanel::Terminal { |
| 1043 | return false; |
| 1044 | } |
| 1045 | match mouse.kind { |
| 1046 | MouseEventKind::Down(MouseButton::Left) => { |
| 1047 | super::interaction::claim_focus(app); |
| 1048 | #[cfg(all(unix, not(target_env = "ohos")))] |
| 1049 | if let Some(id) = app |
| 1050 | .work_surface |
| 1051 | .terminal |
| 1052 | .session_tabs |
| 1053 | .iter() |
| 1054 | .find(|(_, area)| area.contains((mouse.column, mouse.row).into())) |
| 1055 | .map(|(id, _)| id.clone()) |
| 1056 | { |
| 1057 | let dock = &mut app.work_surface.terminal; |
| 1058 | dock.select(id); |
| 1059 | } |
| 1060 | app.needs_redraw = true; |
| 1061 | } |
| 1062 | MouseEventKind::ScrollUp | MouseEventKind::ScrollDown => { |
| 1063 | #[cfg(all(unix, not(target_env = "ohos")))] |
| 1064 | { |
| 1065 | let dock = &mut app.work_surface.terminal; |
| 1066 | dock.scroll_by(mouse.kind == MouseEventKind::ScrollUp, 3); |
| 1067 | app.needs_redraw = true; |
| 1068 | } |
| 1069 | } |
| 1070 | _ => {} |
| 1071 | } |
| 1072 | true |
| 1073 | } |
| 1074 | |
| 1075 | #[cfg(all(test, unix, not(target_env = "ohos")))] |
| 1076 | mod tests { |
| 1077 | use super::*; |
| 1078 | |
| 1079 | fn chunk(offset: u64, bytes: &[u8]) -> terminal_session::OutputChunk { |
| 1080 | let end = offset + bytes.len() as u64; |
| 1081 | terminal_session::OutputChunk { |
| 1082 | bytes: bytes.to_vec(), |
| 1083 | offset, |
| 1084 | next_cursor: end, |
| 1085 | total: end, |
| 1086 | dropped: 0, |
| 1087 | gap: false, |
| 1088 | } |
| 1089 | } |
| 1090 | |
| 1091 | #[test] |
| 1092 | fn pty_overwrites_progress_restores_the_shell_and_clips_to_its_pane() { |
| 1093 | use ratatui::{buffer::Buffer, style::Color}; |
| 1094 | let mut screen = PtyScreen::new("one".into(), (3, 18)); |
| 1095 | screen.apply(chunk( |
| 1096 | 0, |
| 1097 | b"Progress 10%\rProgress 99%\x1b[2;1H\x1b[32mReady\x1b[0m", |
| 1098 | )); |
| 1099 | screen.apply(chunk(screen.next, b"\x1b[?1049h\x1b[HAlternate")); |
| 1100 | assert!(screen.parser.screen().alternate_screen()); |
| 1101 | assert_eq!(screen.parser.screen().contents(), "Alternate"); |
| 1102 | screen.apply(chunk(screen.next, b"\x1b[?1049l\x1b[2;3HX")); |
| 1103 | assert!(!screen.parser.screen().alternate_screen()); |
| 1104 | assert_eq!(screen.parser.screen().contents(), "Progress 99%\nReXdy"); |
| 1105 | let area = Rect::new(3, 1, 18, 3); |
| 1106 | let mut buffer = Buffer::empty(Rect::new(0, 0, 24, 5)); |
| 1107 | for cell in &mut buffer.content { |
| 1108 | cell.set_symbol("|"); |
| 1109 | } |
| 1110 | screen.render(area, &mut buffer, Style::default().bg(Color::Blue), false); |
| 1111 | assert_eq!(buffer[(3, 2)].fg, Color::Indexed(2)); |
| 1112 | assert_eq!(buffer[(3, 2)].bg, Color::Blue); |
| 1113 | assert_eq!(buffer[(5, 2)].symbol(), "X"); |
| 1114 | for (x, y) in [(2, 1), (21, 1), (3, 0), (3, 4)] { |
| 1115 | assert_eq!(buffer[(x, y)].symbol(), "|"); |
| 1116 | } |
| 1117 | } |
| 1118 | |
| 1119 | #[test] |
| 1120 | fn overlapping_snapshots_keep_split_text_and_discard_osc_without_host_actions() { |
| 1121 | let mut screen = PtyScreen::new("one".into(), (4, 30)); |
| 1122 | screen.apply(chunk(0, b"a\xc3")); |
| 1123 | screen.apply(chunk(1, b"\xc3\xa9\x1b")); |
| 1124 | screen.apply(chunk(2, b"\xa9\x1b")); |
| 1125 | screen.apply(chunk(screen.next, b"]52;c;")); |
| 1126 | for _ in 0..12 { |
| 1127 | screen.apply(chunk(screen.next, &[b'x'; 16384])); |
| 1128 | } |
| 1129 | screen.apply(chunk(screen.next, b"\x07b\x1b[6n\x1b]2;private\x1b")); |
| 1130 | screen.apply(chunk(screen.next, b"\\c")); |
| 1131 | assert_eq!(screen.parser.screen().contents(), "aébc"); |
| 1132 | let offset = screen.next + 400; |
| 1133 | screen.apply(chunk(offset, b"new")); |
| 1134 | assert_eq!(screen.omitted, 400); |
| 1135 | assert_eq!(screen.parser.screen().contents(), "new"); |
| 1136 | } |
| 1137 | |
| 1138 | #[test] |
| 1139 | fn tab_incarnations_resize_and_scroll_independently() { |
| 1140 | let mut dock = TerminalDock::default(); |
| 1141 | dock.select("old".into()); |
| 1142 | dock.screen_at_size("old", (3, 20)) |
| 1143 | .apply(chunk(0, b"one\r\ntwo\r\nthree\r\nfour\r\nfive")); |
| 1144 | dock.scroll_by(true, 1); |
| 1145 | let screen = dock.screen_at_size("old", (3, 20)); |
| 1146 | let anchored = screen.parser.screen().contents(); |
| 1147 | screen.apply(chunk(screen.next, b"\r\nsix")); |
| 1148 | assert_eq!(screen.parser.screen().contents(), anchored); |
| 1149 | dock.select("replacement".into()); |
| 1150 | assert!( |
| 1151 | dock.screen_at_size("replacement", (4, 22)) |
| 1152 | .parser |
| 1153 | .screen() |
| 1154 | .contents() |
| 1155 | .is_empty() |
| 1156 | ); |
| 1157 | dock.select("old".into()); |
| 1158 | let screen = dock.screen_at_size("old", (4, 22)); |
| 1159 | assert_eq!(screen.parser.screen().size(), (4, 22)); |
| 1160 | assert_eq!(screen.parser.screen().scrollback(), 0); |
| 1161 | assert!(screen.parser.screen().contents().contains("six")); |
| 1162 | } |
| 1163 | |
| 1164 | #[test] |
| 1165 | fn clipped_command_label_keeps_whole_clusters_and_ends_with_ellipsis() { |
| 1166 | let family = "👨👩👧👦"; |
| 1167 | let command = family.repeat(40); |
| 1168 | let label = clipped_command_label(&command); |
| 1169 | assert_eq!(label, format!("{}…", family.repeat(32))); |
| 1170 | assert_eq!(clipped_command_label("cargo test"), "cargo test"); |
| 1171 | } |
| 1172 | } |
| 1173 |