1pub mod mappings;
2
3pub use alacritty_terminal;
4
5mod pty_info;
6mod terminal_hyperlinks;
7pub mod terminal_settings;
8
9use alacritty_terminal::{
10 Term,
11 event::{Event as AlacTermEvent, EventListener, Notify, WindowSize},
12 event_loop::{EventLoop, Msg, Notifier},
13 grid::{Dimensions, Grid, Row, Scroll as AlacScroll},
14 index::{Boundary, Column, Direction as AlacDirection, Line, Point as AlacPoint},
15 selection::{Selection, SelectionRange, SelectionType},
16 sync::FairMutex,
17 term::{
18 Config, RenderableCursor, TermMode,
19 cell::{Cell, Flags},
20 search::{Match, RegexIter, RegexSearch},
21 },
22 tty::{self},
23 vi_mode::{ViModeCursor, ViMotion},
24 vte::ansi::{
25 ClearMode, CursorStyle as AlacCursorStyle, Handler, NamedPrivateMode, PrivateMode,
26 },
27};
28use anyhow::{Result, bail};
29
30use futures::{
31 FutureExt,
32 channel::mpsc::{UnboundedReceiver, UnboundedSender, unbounded},
33};
34
35use mappings::mouse::{
36 alt_scroll, grid_point, grid_point_and_side, mouse_button_report, mouse_moved_report,
37 scroll_report,
38};
39
40use collections::{HashMap, VecDeque};
41use futures::StreamExt;
42use pty_info::PtyProcessInfo;
43use serde::{Deserialize, Serialize};
44use settings::Settings;
45use smol::channel::{Receiver, Sender};
46use task::{HideStrategy, Shell, TaskId};
47use terminal_hyperlinks::RegexSearches;
48use terminal_settings::{AlternateScroll, CursorShape, TerminalSettings};
49use theme::{ActiveTheme, Theme};
50use util::{paths::home_dir, truncate_and_trailoff};
51
52use std::{
53 borrow::Cow,
54 cmp::{self, min},
55 fmt::Display,
56 ops::{Deref, RangeInclusive},
57 path::PathBuf,
58 process::ExitStatus,
59 sync::Arc,
60 time::Duration,
61};
62use thiserror::Error;
63
64use gpui::{
65 AnyWindowHandle, App, AppContext as _, Bounds, ClipboardItem, Context, EventEmitter, Hsla,
66 Keystroke, Modifiers, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, Pixels, Point,
67 Rgba, ScrollWheelEvent, SharedString, Size, Task, TouchPhase, Window, actions, black, px,
68};
69
70use crate::mappings::{colors::to_alac_rgb, keys::to_esc_str};
71
72actions!(
73 terminal,
74 [
75 Clear,
76 Copy,
77 Paste,
78 ShowCharacterPalette,
79 SearchTest,
80 ScrollLineUp,
81 ScrollLineDown,
82 ScrollPageUp,
83 ScrollPageDown,
84 ScrollToTop,
85 ScrollToBottom,
86 ToggleViMode,
87 ]
88);
89
90///Scrolling is unbearably sluggish by default. Alacritty supports a configurable
91///Scroll multiplier that is set to 3 by default. This will be removed when I
92///Implement scroll bars.
93#[cfg(target_os = "macos")]
94const SCROLL_MULTIPLIER: f32 = 4.;
95#[cfg(not(target_os = "macos"))]
96const SCROLL_MULTIPLIER: f32 = 1.;
97const DEBUG_TERMINAL_WIDTH: Pixels = px(500.);
98const DEBUG_TERMINAL_HEIGHT: Pixels = px(30.);
99const DEBUG_CELL_WIDTH: Pixels = px(5.);
100const DEBUG_LINE_HEIGHT: Pixels = px(5.);
101
102///Upward flowing events, for changing the title and such
103#[derive(Clone, Debug)]
104pub enum Event {
105 TitleChanged,
106 BreadcrumbsChanged,
107 CloseTerminal,
108 Bell,
109 Wakeup,
110 BlinkChanged(bool),
111 SelectionsChanged,
112 NewNavigationTarget(Option<MaybeNavigationTarget>),
113 Open(MaybeNavigationTarget),
114}
115
116#[derive(Clone, Debug)]
117pub struct PathLikeTarget {
118 /// File system path, absolute or relative, existing or not.
119 /// Might have line and column number(s) attached as `file.rs:1:23`
120 pub maybe_path: String,
121 /// Current working directory of the terminal
122 pub terminal_dir: Option<PathBuf>,
123}
124
125/// A string inside terminal, potentially useful as a URI that can be opened.
126#[derive(Clone, Debug)]
127pub enum MaybeNavigationTarget {
128 /// HTTP, git, etc. string determined by the `URL_REGEX` regex.
129 Url(String),
130 /// File system path, absolute or relative, existing or not.
131 /// Might have line and column number(s) attached as `file.rs:1:23`
132 PathLike(PathLikeTarget),
133}
134
135#[derive(Clone)]
136enum InternalEvent {
137 Resize(TerminalBounds),
138 Clear,
139 // FocusNextMatch,
140 Scroll(AlacScroll),
141 ScrollToAlacPoint(AlacPoint),
142 SetSelection(Option<(Selection, AlacPoint)>),
143 UpdateSelection(Point<Pixels>),
144 // Adjusted mouse position, should open
145 FindHyperlink(Point<Pixels>, bool),
146 Copy,
147 // Vi mode events
148 ToggleViMode,
149 ViMotion(ViMotion),
150}
151
152///A translation struct for Alacritty to communicate with us from their event loop
153#[derive(Clone)]
154pub struct ZedListener(pub UnboundedSender<AlacTermEvent>);
155
156impl EventListener for ZedListener {
157 fn send_event(&self, event: AlacTermEvent) {
158 self.0.unbounded_send(event).ok();
159 }
160}
161
162pub fn init(cx: &mut App) {
163 TerminalSettings::register(cx);
164}
165
166#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
167pub struct TerminalBounds {
168 pub cell_width: Pixels,
169 pub line_height: Pixels,
170 pub bounds: Bounds<Pixels>,
171}
172
173impl TerminalBounds {
174 pub fn new(line_height: Pixels, cell_width: Pixels, bounds: Bounds<Pixels>) -> Self {
175 TerminalBounds {
176 cell_width,
177 line_height,
178 bounds,
179 }
180 }
181
182 pub fn num_lines(&self) -> usize {
183 (self.bounds.size.height / self.line_height).floor() as usize
184 }
185
186 pub fn num_columns(&self) -> usize {
187 (self.bounds.size.width / self.cell_width).floor() as usize
188 }
189
190 pub fn height(&self) -> Pixels {
191 self.bounds.size.height
192 }
193
194 pub fn width(&self) -> Pixels {
195 self.bounds.size.width
196 }
197
198 pub fn cell_width(&self) -> Pixels {
199 self.cell_width
200 }
201
202 pub fn line_height(&self) -> Pixels {
203 self.line_height
204 }
205}
206
207impl Default for TerminalBounds {
208 fn default() -> Self {
209 TerminalBounds::new(
210 DEBUG_LINE_HEIGHT,
211 DEBUG_CELL_WIDTH,
212 Bounds {
213 origin: Point::default(),
214 size: Size {
215 width: DEBUG_TERMINAL_WIDTH,
216 height: DEBUG_TERMINAL_HEIGHT,
217 },
218 },
219 )
220 }
221}
222
223impl From<TerminalBounds> for WindowSize {
224 fn from(val: TerminalBounds) -> Self {
225 WindowSize {
226 num_lines: val.num_lines() as u16,
227 num_cols: val.num_columns() as u16,
228 cell_width: f32::from(val.cell_width()) as u16,
229 cell_height: f32::from(val.line_height()) as u16,
230 }
231 }
232}
233
234impl Dimensions for TerminalBounds {
235 /// Note: this is supposed to be for the back buffer's length,
236 /// but we exclusively use it to resize the terminal, which does not
237 /// use this method. We still have to implement it for the trait though,
238 /// hence, this comment.
239 fn total_lines(&self) -> usize {
240 self.screen_lines()
241 }
242
243 fn screen_lines(&self) -> usize {
244 self.num_lines()
245 }
246
247 fn columns(&self) -> usize {
248 self.num_columns()
249 }
250}
251
252#[derive(Error, Debug)]
253pub struct TerminalError {
254 pub directory: Option<PathBuf>,
255 pub shell: Shell,
256 pub source: std::io::Error,
257}
258
259impl TerminalError {
260 pub fn fmt_directory(&self) -> String {
261 self.directory
262 .clone()
263 .map(|path| {
264 match path
265 .into_os_string()
266 .into_string()
267 .map_err(|os_str| format!("<non-utf8 path> {}", os_str.to_string_lossy()))
268 {
269 Ok(s) => s,
270 Err(s) => s,
271 }
272 })
273 .unwrap_or_else(|| match dirs::home_dir() {
274 Some(dir) => format!(
275 "<none specified, using home directory> {}",
276 dir.into_os_string().to_string_lossy()
277 ),
278 None => "<none specified, could not find home directory>".to_string(),
279 })
280 }
281
282 pub fn fmt_shell(&self) -> String {
283 match &self.shell {
284 Shell::System => "<system defined shell>".to_string(),
285 Shell::Program(s) => s.to_string(),
286 Shell::WithArguments {
287 program,
288 args,
289 title_override,
290 } => {
291 if let Some(title_override) = title_override {
292 format!("{} {} ({})", program, args.join(" "), title_override)
293 } else {
294 format!("{} {}", program, args.join(" "))
295 }
296 }
297 }
298 }
299}
300
301impl Display for TerminalError {
302 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
303 let dir_string: String = self.fmt_directory();
304 let shell = self.fmt_shell();
305
306 write!(
307 f,
308 "Working directory: {} Shell command: `{}`, IOError: {}",
309 dir_string, shell, self.source
310 )
311 }
312}
313
314// https://github.com/alacritty/alacritty/blob/cb3a79dbf6472740daca8440d5166c1d4af5029e/extra/man/alacritty.5.scd?plain=1#L207-L213
315const DEFAULT_SCROLL_HISTORY_LINES: usize = 10_000;
316pub const MAX_SCROLL_HISTORY_LINES: usize = 100_000;
317
318pub struct TerminalBuilder {
319 terminal: Terminal,
320 events_rx: UnboundedReceiver<AlacTermEvent>,
321}
322
323impl TerminalBuilder {
324 pub fn new(
325 working_directory: Option<PathBuf>,
326 python_venv_directory: Option<PathBuf>,
327 task: Option<TaskState>,
328 shell: Shell,
329 mut env: HashMap<String, String>,
330 cursor_shape: CursorShape,
331 alternate_scroll: AlternateScroll,
332 max_scroll_history_lines: Option<usize>,
333 is_ssh_terminal: bool,
334 window: AnyWindowHandle,
335 completion_tx: Sender<Option<ExitStatus>>,
336 cx: &App,
337 ) -> Result<TerminalBuilder> {
338 // If the parent environment doesn't have a locale set
339 // (As is the case when launched from a .app on MacOS),
340 // and the Project doesn't have a locale set, then
341 // set a fallback for our child environment to use.
342 if std::env::var("LANG").is_err() {
343 env.entry("LANG".to_string())
344 .or_insert_with(|| "en_US.UTF-8".to_string());
345 }
346
347 env.insert("ZED_TERM".to_string(), "true".to_string());
348 env.insert("TERM_PROGRAM".to_string(), "zed".to_string());
349 env.insert("TERM".to_string(), "xterm-256color".to_string());
350 env.insert(
351 "TERM_PROGRAM_VERSION".to_string(),
352 release_channel::AppVersion::global(cx).to_string(),
353 );
354
355 let mut terminal_title_override = None;
356
357 let pty_options = {
358 let alac_shell = match shell.clone() {
359 Shell::System => {
360 #[cfg(target_os = "windows")]
361 {
362 Some(alacritty_terminal::tty::Shell::new(
363 util::get_windows_system_shell(),
364 Vec::new(),
365 ))
366 }
367 #[cfg(not(target_os = "windows"))]
368 {
369 None
370 }
371 }
372 Shell::Program(program) => {
373 Some(alacritty_terminal::tty::Shell::new(program, Vec::new()))
374 }
375 Shell::WithArguments {
376 program,
377 args,
378 title_override,
379 } => {
380 terminal_title_override = title_override;
381 Some(alacritty_terminal::tty::Shell::new(program, args))
382 }
383 };
384
385 alacritty_terminal::tty::Options {
386 shell: alac_shell,
387 working_directory: working_directory
388 .clone()
389 .or_else(|| Some(home_dir().to_path_buf())),
390 drain_on_exit: true,
391 env: env.into_iter().collect(),
392 }
393 };
394
395 // Setup Alacritty's env, which modifies the current process's environment
396 alacritty_terminal::tty::setup_env();
397
398 let default_cursor_style = AlacCursorStyle::from(cursor_shape);
399 let scrolling_history = if task.is_some() {
400 // Tasks like `cargo build --all` may produce a lot of output, ergo allow maximum scrolling.
401 // After the task finishes, we do not allow appending to that terminal, so small tasks output should not
402 // cause excessive memory usage over time.
403 MAX_SCROLL_HISTORY_LINES
404 } else {
405 max_scroll_history_lines
406 .unwrap_or(DEFAULT_SCROLL_HISTORY_LINES)
407 .min(MAX_SCROLL_HISTORY_LINES)
408 };
409 let config = Config {
410 scrolling_history,
411 default_cursor_style,
412 ..Config::default()
413 };
414
415 //Spawn a task so the Alacritty EventLoop can communicate with us
416 //TODO: Remove with a bounded sender which can be dispatched on &self
417 let (events_tx, events_rx) = unbounded();
418 //Set up the terminal...
419 let mut term = Term::new(
420 config.clone(),
421 &TerminalBounds::default(),
422 ZedListener(events_tx.clone()),
423 );
424
425 //Alacritty defaults to alternate scrolling being on, so we just need to turn it off.
426 if let AlternateScroll::Off = alternate_scroll {
427 term.unset_private_mode(PrivateMode::Named(NamedPrivateMode::AlternateScroll));
428 }
429
430 let term = Arc::new(FairMutex::new(term));
431
432 //Setup the pty...
433 let pty = match tty::new(
434 &pty_options,
435 TerminalBounds::default().into(),
436 window.window_id().as_u64(),
437 ) {
438 Ok(pty) => pty,
439 Err(error) => {
440 bail!(TerminalError {
441 directory: working_directory,
442 shell,
443 source: error,
444 });
445 }
446 };
447
448 let pty_info = PtyProcessInfo::new(&pty);
449
450 //And connect them together
451 let event_loop = EventLoop::new(
452 term.clone(),
453 ZedListener(events_tx.clone()),
454 pty,
455 pty_options.drain_on_exit,
456 false,
457 )?;
458
459 //Kick things off
460 let pty_tx = event_loop.channel();
461 let _io_thread = event_loop.spawn(); // DANGER
462
463 let terminal = Terminal {
464 task,
465 pty_tx: Notifier(pty_tx),
466 completion_tx,
467 term,
468 term_config: config,
469 title_override: terminal_title_override,
470 events: VecDeque::with_capacity(10), //Should never get this high.
471 last_content: Default::default(),
472 last_mouse: None,
473 matches: Vec::new(),
474 selection_head: None,
475 pty_info,
476 breadcrumb_text: String::new(),
477 scroll_px: px(0.),
478 next_link_id: 0,
479 selection_phase: SelectionPhase::Ended,
480 // hovered_word: false,
481 hyperlink_regex_searches: RegexSearches::new(),
482 vi_mode_enabled: false,
483 is_ssh_terminal,
484 python_venv_directory,
485 };
486
487 Ok(TerminalBuilder {
488 terminal,
489 events_rx,
490 })
491 }
492
493 pub fn subscribe(mut self, cx: &Context<Terminal>) -> Terminal {
494 //Event loop
495 cx.spawn(async move |terminal, cx| {
496 while let Some(event) = self.events_rx.next().await {
497 terminal.update(cx, |terminal, cx| {
498 //Process the first event immediately for lowered latency
499 terminal.process_event(event, cx);
500 })?;
501
502 'outer: loop {
503 let mut events = Vec::new();
504 let mut timer = cx
505 .background_executor()
506 .timer(Duration::from_millis(4))
507 .fuse();
508 let mut wakeup = false;
509 loop {
510 futures::select_biased! {
511 _ = timer => break,
512 event = self.events_rx.next() => {
513 if let Some(event) = event {
514 if matches!(event, AlacTermEvent::Wakeup) {
515 wakeup = true;
516 } else {
517 events.push(event);
518 }
519
520 if events.len() > 100 {
521 break;
522 }
523 } else {
524 break;
525 }
526 },
527 }
528 }
529
530 if events.is_empty() && !wakeup {
531 smol::future::yield_now().await;
532 break 'outer;
533 }
534
535 terminal.update(cx, |this, cx| {
536 if wakeup {
537 this.process_event(AlacTermEvent::Wakeup, cx);
538 }
539
540 for event in events {
541 this.process_event(event, cx);
542 }
543 })?;
544 smol::future::yield_now().await;
545 }
546 }
547
548 anyhow::Ok(())
549 })
550 .detach();
551
552 self.terminal
553 }
554}
555
556#[derive(Debug, Clone, Deserialize, Serialize)]
557pub struct IndexedCell {
558 pub point: AlacPoint,
559 pub cell: Cell,
560}
561
562impl Deref for IndexedCell {
563 type Target = Cell;
564
565 #[inline]
566 fn deref(&self) -> &Cell {
567 &self.cell
568 }
569}
570
571// TODO: Un-pub
572#[derive(Clone)]
573pub struct TerminalContent {
574 pub cells: Vec<IndexedCell>,
575 pub mode: TermMode,
576 pub display_offset: usize,
577 pub selection_text: Option<String>,
578 pub selection: Option<SelectionRange>,
579 pub cursor: RenderableCursor,
580 pub cursor_char: char,
581 pub terminal_bounds: TerminalBounds,
582 pub last_hovered_word: Option<HoveredWord>,
583 pub scrolled_to_top: bool,
584 pub scrolled_to_bottom: bool,
585}
586
587#[derive(Debug, Clone, Eq, PartialEq)]
588pub struct HoveredWord {
589 pub word: String,
590 pub word_match: RangeInclusive<AlacPoint>,
591 pub id: usize,
592}
593
594impl Default for TerminalContent {
595 fn default() -> Self {
596 TerminalContent {
597 cells: Default::default(),
598 mode: Default::default(),
599 display_offset: Default::default(),
600 selection_text: Default::default(),
601 selection: Default::default(),
602 cursor: RenderableCursor {
603 shape: alacritty_terminal::vte::ansi::CursorShape::Block,
604 point: AlacPoint::new(Line(0), Column(0)),
605 },
606 cursor_char: Default::default(),
607 terminal_bounds: Default::default(),
608 last_hovered_word: None,
609 scrolled_to_top: false,
610 scrolled_to_bottom: false,
611 }
612 }
613}
614
615#[derive(PartialEq, Eq)]
616pub enum SelectionPhase {
617 Selecting,
618 Ended,
619}
620
621pub struct Terminal {
622 pty_tx: Notifier,
623 completion_tx: Sender<Option<ExitStatus>>,
624 term: Arc<FairMutex<Term<ZedListener>>>,
625 term_config: Config,
626 events: VecDeque<InternalEvent>,
627 /// This is only used for mouse mode cell change detection
628 last_mouse: Option<(AlacPoint, AlacDirection)>,
629 pub matches: Vec<RangeInclusive<AlacPoint>>,
630 pub last_content: TerminalContent,
631 pub selection_head: Option<AlacPoint>,
632 pub breadcrumb_text: String,
633 pub pty_info: PtyProcessInfo,
634 title_override: Option<SharedString>,
635 pub python_venv_directory: Option<PathBuf>,
636 scroll_px: Pixels,
637 next_link_id: usize,
638 selection_phase: SelectionPhase,
639 hyperlink_regex_searches: RegexSearches,
640 task: Option<TaskState>,
641 vi_mode_enabled: bool,
642 is_ssh_terminal: bool,
643}
644
645pub struct TaskState {
646 pub id: TaskId,
647 pub full_label: String,
648 pub label: String,
649 pub command_label: String,
650 pub status: TaskStatus,
651 pub completion_rx: Receiver<Option<ExitStatus>>,
652 pub hide: HideStrategy,
653 pub show_summary: bool,
654 pub show_command: bool,
655 pub show_rerun: bool,
656}
657
658/// A status of the current terminal tab's task.
659#[derive(Debug, Clone, Copy, PartialEq, Eq)]
660pub enum TaskStatus {
661 /// The task had been started, but got cancelled or somehow otherwise it did not
662 /// report its exit code before the terminal event loop was shut down.
663 Unknown,
664 /// The task is started and running currently.
665 Running,
666 /// After the start, the task stopped running and reported its error code back.
667 Completed { success: bool },
668}
669
670impl TaskStatus {
671 fn register_terminal_exit(&mut self) {
672 if self == &Self::Running {
673 *self = Self::Unknown;
674 }
675 }
676
677 fn register_task_exit(&mut self, error_code: i32) {
678 *self = TaskStatus::Completed {
679 success: error_code == 0,
680 };
681 }
682}
683
684impl Terminal {
685 fn process_event(&mut self, event: AlacTermEvent, cx: &mut Context<Self>) {
686 match event {
687 AlacTermEvent::Title(title) => {
688 self.breadcrumb_text = title;
689 cx.emit(Event::BreadcrumbsChanged);
690 }
691 AlacTermEvent::ResetTitle => {
692 self.breadcrumb_text = String::new();
693 cx.emit(Event::BreadcrumbsChanged);
694 }
695 AlacTermEvent::ClipboardStore(_, data) => {
696 cx.write_to_clipboard(ClipboardItem::new_string(data))
697 }
698 AlacTermEvent::ClipboardLoad(_, format) => {
699 self.write_to_pty(
700 match &cx.read_from_clipboard().and_then(|item| item.text()) {
701 // The terminal only supports pasting strings, not images.
702 Some(text) => format(text),
703 _ => format(""),
704 }
705 .into_bytes(),
706 )
707 }
708 AlacTermEvent::PtyWrite(out) => self.write_to_pty(out.into_bytes()),
709 AlacTermEvent::TextAreaSizeRequest(format) => {
710 self.write_to_pty(format(self.last_content.terminal_bounds.into()).into_bytes())
711 }
712 AlacTermEvent::CursorBlinkingChange => {
713 let terminal = self.term.lock();
714 let blinking = terminal.cursor_style().blinking;
715 cx.emit(Event::BlinkChanged(blinking));
716 }
717 AlacTermEvent::Bell => {
718 cx.emit(Event::Bell);
719 }
720 AlacTermEvent::Exit => self.register_task_finished(None, cx),
721 AlacTermEvent::MouseCursorDirty => {
722 //NOOP, Handled in render
723 }
724 AlacTermEvent::Wakeup => {
725 cx.emit(Event::Wakeup);
726
727 if self.pty_info.has_changed() {
728 cx.emit(Event::TitleChanged);
729 }
730 }
731 AlacTermEvent::ColorRequest(index, format) => {
732 // It's important that the color request is processed here to retain relative order
733 // with other PTY writes. Otherwise applications might witness out-of-order
734 // responses to requests. For example: An application sending `OSC 11 ; ? ST`
735 // (color request) followed by `CSI c` (request device attributes) would receive
736 // the response to `CSI c` first.
737 // Instead of locking, we could store the colors in `self.last_content`. But then
738 // we might respond with out of date value if a "set color" sequence is immediately
739 // followed by a color request sequence.
740 let color = self.term.lock().colors()[index]
741 .unwrap_or_else(|| to_alac_rgb(get_color_at_index(index, cx.theme().as_ref())));
742 self.write_to_pty(format(color).into_bytes());
743 }
744 AlacTermEvent::ChildExit(error_code) => {
745 self.register_task_finished(Some(error_code), cx);
746 }
747 }
748 }
749
750 pub fn selection_started(&self) -> bool {
751 self.selection_phase == SelectionPhase::Selecting
752 }
753
754 fn process_terminal_event(
755 &mut self,
756 event: &InternalEvent,
757 term: &mut Term<ZedListener>,
758 window: &mut Window,
759 cx: &mut Context<Self>,
760 ) {
761 match event {
762 &InternalEvent::Resize(mut new_bounds) => {
763 new_bounds.bounds.size.height =
764 cmp::max(new_bounds.line_height, new_bounds.height());
765 new_bounds.bounds.size.width = cmp::max(new_bounds.cell_width, new_bounds.width());
766
767 self.last_content.terminal_bounds = new_bounds;
768
769 self.pty_tx.0.send(Msg::Resize(new_bounds.into())).ok();
770
771 term.resize(new_bounds);
772 }
773 InternalEvent::Clear => {
774 // Clear back buffer
775 term.clear_screen(ClearMode::Saved);
776
777 let cursor = term.grid().cursor.point;
778
779 // Clear the lines above
780 term.grid_mut().reset_region(..cursor.line);
781
782 // Copy the current line up
783 let line = term.grid()[cursor.line][..Column(term.grid().columns())]
784 .iter()
785 .cloned()
786 .enumerate()
787 .collect::<Vec<(usize, Cell)>>();
788
789 for (i, cell) in line {
790 term.grid_mut()[Line(0)][Column(i)] = cell;
791 }
792
793 // Reset the cursor
794 term.grid_mut().cursor.point =
795 AlacPoint::new(Line(0), term.grid_mut().cursor.point.column);
796 let new_cursor = term.grid().cursor.point;
797
798 // Clear the lines below the new cursor
799 if (new_cursor.line.0 as usize) < term.screen_lines() - 1 {
800 term.grid_mut().reset_region((new_cursor.line + 1)..);
801 }
802
803 cx.emit(Event::Wakeup);
804 }
805 InternalEvent::Scroll(scroll) => {
806 term.scroll_display(*scroll);
807 self.refresh_hovered_word(window);
808
809 if self.vi_mode_enabled {
810 match *scroll {
811 AlacScroll::Delta(delta) => {
812 term.vi_mode_cursor = term.vi_mode_cursor.scroll(&term, delta);
813 }
814 AlacScroll::PageUp => {
815 let lines = term.screen_lines() as i32;
816 term.vi_mode_cursor = term.vi_mode_cursor.scroll(&term, lines);
817 }
818 AlacScroll::PageDown => {
819 let lines = -(term.screen_lines() as i32);
820 term.vi_mode_cursor = term.vi_mode_cursor.scroll(&term, lines);
821 }
822 AlacScroll::Top => {
823 let point = AlacPoint::new(term.topmost_line(), Column(0));
824 term.vi_mode_cursor = ViModeCursor::new(point);
825 }
826 AlacScroll::Bottom => {
827 let point = AlacPoint::new(term.bottommost_line(), Column(0));
828 term.vi_mode_cursor = ViModeCursor::new(point);
829 }
830 }
831 if let Some(mut selection) = term.selection.take() {
832 let point = term.vi_mode_cursor.point;
833 selection.update(point, AlacDirection::Right);
834 term.selection = Some(selection);
835
836 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
837 if let Some(selection_text) = term.selection_to_string() {
838 cx.write_to_primary(ClipboardItem::new_string(selection_text));
839 }
840
841 self.selection_head = Some(point);
842 cx.emit(Event::SelectionsChanged)
843 }
844 }
845 }
846 InternalEvent::SetSelection(selection) => {
847 term.selection = selection.as_ref().map(|(sel, _)| sel.clone());
848
849 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
850 if let Some(selection_text) = term.selection_to_string() {
851 cx.write_to_primary(ClipboardItem::new_string(selection_text));
852 }
853
854 if let Some((_, head)) = selection {
855 self.selection_head = Some(*head);
856 }
857 cx.emit(Event::SelectionsChanged)
858 }
859 InternalEvent::UpdateSelection(position) => {
860 if let Some(mut selection) = term.selection.take() {
861 let (point, side) = grid_point_and_side(
862 *position,
863 self.last_content.terminal_bounds,
864 term.grid().display_offset(),
865 );
866
867 selection.update(point, side);
868 term.selection = Some(selection);
869
870 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
871 if let Some(selection_text) = term.selection_to_string() {
872 cx.write_to_primary(ClipboardItem::new_string(selection_text));
873 }
874
875 self.selection_head = Some(point);
876 cx.emit(Event::SelectionsChanged)
877 }
878 }
879
880 InternalEvent::Copy => {
881 if let Some(txt) = term.selection_to_string() {
882 cx.write_to_clipboard(ClipboardItem::new_string(txt))
883 }
884 }
885 InternalEvent::ScrollToAlacPoint(point) => {
886 term.scroll_to_point(*point);
887 self.refresh_hovered_word(window);
888 }
889 InternalEvent::ToggleViMode => {
890 self.vi_mode_enabled = !self.vi_mode_enabled;
891 term.toggle_vi_mode();
892 }
893 InternalEvent::ViMotion(motion) => {
894 term.vi_motion(*motion);
895 }
896 InternalEvent::FindHyperlink(position, open) => {
897 let prev_hovered_word = self.last_content.last_hovered_word.take();
898
899 let point = grid_point(
900 *position,
901 self.last_content.terminal_bounds,
902 term.grid().display_offset(),
903 )
904 .grid_clamp(term, Boundary::Grid);
905
906 match terminal_hyperlinks::find_from_grid_point(
907 term,
908 point,
909 &mut self.hyperlink_regex_searches,
910 ) {
911 Some((maybe_url_or_path, is_url, url_match)) => {
912 let target = if is_url {
913 MaybeNavigationTarget::Url(maybe_url_or_path.clone())
914 } else {
915 MaybeNavigationTarget::PathLike(PathLikeTarget {
916 maybe_path: maybe_url_or_path.clone(),
917 terminal_dir: self.working_directory(),
918 })
919 };
920 if *open {
921 cx.emit(Event::Open(target));
922 } else {
923 self.update_selected_word(
924 prev_hovered_word,
925 url_match,
926 maybe_url_or_path,
927 target,
928 cx,
929 );
930 }
931 }
932 None => {
933 cx.emit(Event::NewNavigationTarget(None));
934 }
935 }
936 }
937 }
938 }
939
940 fn update_selected_word(
941 &mut self,
942 prev_word: Option<HoveredWord>,
943 word_match: RangeInclusive<AlacPoint>,
944 word: String,
945 navigation_target: MaybeNavigationTarget,
946 cx: &mut Context<Self>,
947 ) {
948 if let Some(prev_word) = prev_word {
949 if prev_word.word == word && prev_word.word_match == word_match {
950 self.last_content.last_hovered_word = Some(HoveredWord {
951 word,
952 word_match,
953 id: prev_word.id,
954 });
955 return;
956 }
957 }
958
959 self.last_content.last_hovered_word = Some(HoveredWord {
960 word,
961 word_match,
962 id: self.next_link_id(),
963 });
964 cx.emit(Event::NewNavigationTarget(Some(navigation_target)));
965 cx.notify()
966 }
967
968 fn next_link_id(&mut self) -> usize {
969 let res = self.next_link_id;
970 self.next_link_id = self.next_link_id.wrapping_add(1);
971 res
972 }
973
974 pub fn last_content(&self) -> &TerminalContent {
975 &self.last_content
976 }
977
978 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape) {
979 self.term_config.default_cursor_style = cursor_shape.into();
980 self.term.lock().set_options(self.term_config.clone());
981 }
982
983 pub fn total_lines(&self) -> usize {
984 let term = self.term.clone();
985 let terminal = term.lock_unfair();
986 terminal.total_lines()
987 }
988
989 pub fn viewport_lines(&self) -> usize {
990 let term = self.term.clone();
991 let terminal = term.lock_unfair();
992 terminal.screen_lines()
993 }
994
995 //To test:
996 //- Activate match on terminal (scrolling and selection)
997 //- Editor search snapping behavior
998
999 pub fn activate_match(&mut self, index: usize) {
1000 if let Some(search_match) = self.matches.get(index).cloned() {
1001 self.set_selection(Some((make_selection(&search_match), *search_match.end())));
1002
1003 self.events
1004 .push_back(InternalEvent::ScrollToAlacPoint(*search_match.start()));
1005 }
1006 }
1007
1008 pub fn select_matches(&mut self, matches: &[RangeInclusive<AlacPoint>]) {
1009 let matches_to_select = self
1010 .matches
1011 .iter()
1012 .filter(|self_match| matches.contains(self_match))
1013 .cloned()
1014 .collect::<Vec<_>>();
1015 for match_to_select in matches_to_select {
1016 self.set_selection(Some((
1017 make_selection(&match_to_select),
1018 *match_to_select.end(),
1019 )));
1020 }
1021 }
1022
1023 pub fn select_all(&mut self) {
1024 let term = self.term.lock();
1025 let start = AlacPoint::new(term.topmost_line(), Column(0));
1026 let end = AlacPoint::new(term.bottommost_line(), term.last_column());
1027 drop(term);
1028 self.set_selection(Some((make_selection(&(start..=end)), end)));
1029 }
1030
1031 fn set_selection(&mut self, selection: Option<(Selection, AlacPoint)>) {
1032 self.events
1033 .push_back(InternalEvent::SetSelection(selection));
1034 }
1035
1036 pub fn copy(&mut self) {
1037 self.events.push_back(InternalEvent::Copy);
1038 }
1039
1040 pub fn clear(&mut self) {
1041 self.events.push_back(InternalEvent::Clear)
1042 }
1043
1044 pub fn scroll_line_up(&mut self) {
1045 self.events
1046 .push_back(InternalEvent::Scroll(AlacScroll::Delta(1)));
1047 }
1048
1049 pub fn scroll_up_by(&mut self, lines: usize) {
1050 self.events
1051 .push_back(InternalEvent::Scroll(AlacScroll::Delta(lines as i32)));
1052 }
1053
1054 pub fn scroll_line_down(&mut self) {
1055 self.events
1056 .push_back(InternalEvent::Scroll(AlacScroll::Delta(-1)));
1057 }
1058
1059 pub fn scroll_down_by(&mut self, lines: usize) {
1060 self.events
1061 .push_back(InternalEvent::Scroll(AlacScroll::Delta(-(lines as i32))));
1062 }
1063
1064 pub fn scroll_page_up(&mut self) {
1065 self.events
1066 .push_back(InternalEvent::Scroll(AlacScroll::PageUp));
1067 }
1068
1069 pub fn scroll_page_down(&mut self) {
1070 self.events
1071 .push_back(InternalEvent::Scroll(AlacScroll::PageDown));
1072 }
1073
1074 pub fn scroll_to_top(&mut self) {
1075 self.events
1076 .push_back(InternalEvent::Scroll(AlacScroll::Top));
1077 }
1078
1079 pub fn scroll_to_bottom(&mut self) {
1080 self.events
1081 .push_back(InternalEvent::Scroll(AlacScroll::Bottom));
1082 }
1083
1084 pub fn scrolled_to_top(&self) -> bool {
1085 self.last_content.scrolled_to_top
1086 }
1087
1088 pub fn scrolled_to_bottom(&self) -> bool {
1089 self.last_content.scrolled_to_bottom
1090 }
1091
1092 ///Resize the terminal and the PTY.
1093 pub fn set_size(&mut self, new_bounds: TerminalBounds) {
1094 if self.last_content.terminal_bounds != new_bounds {
1095 self.events.push_back(InternalEvent::Resize(new_bounds))
1096 }
1097 }
1098
1099 ///Write the Input payload to the tty.
1100 fn write_to_pty(&self, input: impl Into<Cow<'static, [u8]>>) {
1101 self.pty_tx.notify(input.into());
1102 }
1103
1104 pub fn input(&mut self, input: impl Into<Cow<'static, [u8]>>) {
1105 self.events
1106 .push_back(InternalEvent::Scroll(AlacScroll::Bottom));
1107 self.events.push_back(InternalEvent::SetSelection(None));
1108
1109 self.write_to_pty(input);
1110 }
1111
1112 pub fn toggle_vi_mode(&mut self) {
1113 self.events.push_back(InternalEvent::ToggleViMode);
1114 }
1115
1116 pub fn vi_motion(&mut self, keystroke: &Keystroke) {
1117 if !self.vi_mode_enabled {
1118 return;
1119 }
1120
1121 let key: Cow<'_, str> = if keystroke.modifiers.shift {
1122 Cow::Owned(keystroke.key.to_uppercase())
1123 } else {
1124 Cow::Borrowed(keystroke.key.as_str())
1125 };
1126
1127 let motion: Option<ViMotion> = match key.as_ref() {
1128 "h" | "left" => Some(ViMotion::Left),
1129 "j" | "down" => Some(ViMotion::Down),
1130 "k" | "up" => Some(ViMotion::Up),
1131 "l" | "right" => Some(ViMotion::Right),
1132 "w" => Some(ViMotion::WordRight),
1133 "b" if !keystroke.modifiers.control => Some(ViMotion::WordLeft),
1134 "e" => Some(ViMotion::WordRightEnd),
1135 "%" => Some(ViMotion::Bracket),
1136 "$" => Some(ViMotion::Last),
1137 "0" => Some(ViMotion::First),
1138 "^" => Some(ViMotion::FirstOccupied),
1139 "H" => Some(ViMotion::High),
1140 "M" => Some(ViMotion::Middle),
1141 "L" => Some(ViMotion::Low),
1142 _ => None,
1143 };
1144
1145 if let Some(motion) = motion {
1146 let cursor = self.last_content.cursor.point;
1147 let cursor_pos = Point {
1148 x: cursor.column.0 as f32 * self.last_content.terminal_bounds.cell_width,
1149 y: cursor.line.0 as f32 * self.last_content.terminal_bounds.line_height,
1150 };
1151 self.events
1152 .push_back(InternalEvent::UpdateSelection(cursor_pos));
1153 self.events.push_back(InternalEvent::ViMotion(motion));
1154 return;
1155 }
1156
1157 let scroll_motion = match key.as_ref() {
1158 "g" => Some(AlacScroll::Top),
1159 "G" => Some(AlacScroll::Bottom),
1160 "b" if keystroke.modifiers.control => Some(AlacScroll::PageUp),
1161 "f" if keystroke.modifiers.control => Some(AlacScroll::PageDown),
1162 "d" if keystroke.modifiers.control => {
1163 let amount = self.last_content.terminal_bounds.line_height().to_f64() as i32 / 2;
1164 Some(AlacScroll::Delta(-amount))
1165 }
1166 "u" if keystroke.modifiers.control => {
1167 let amount = self.last_content.terminal_bounds.line_height().to_f64() as i32 / 2;
1168 Some(AlacScroll::Delta(amount))
1169 }
1170 _ => None,
1171 };
1172
1173 if let Some(scroll_motion) = scroll_motion {
1174 self.events.push_back(InternalEvent::Scroll(scroll_motion));
1175 return;
1176 }
1177
1178 match key.as_ref() {
1179 "v" => {
1180 let point = self.last_content.cursor.point;
1181 let selection_type = SelectionType::Simple;
1182 let side = AlacDirection::Right;
1183 let selection = Selection::new(selection_type, point, side);
1184 self.events
1185 .push_back(InternalEvent::SetSelection(Some((selection, point))));
1186 return;
1187 }
1188
1189 "escape" => {
1190 self.events.push_back(InternalEvent::SetSelection(None));
1191 return;
1192 }
1193
1194 "y" => {
1195 self.events.push_back(InternalEvent::Copy);
1196 self.events.push_back(InternalEvent::SetSelection(None));
1197 return;
1198 }
1199
1200 "i" => {
1201 self.scroll_to_bottom();
1202 self.toggle_vi_mode();
1203 return;
1204 }
1205 _ => {}
1206 }
1207 }
1208
1209 pub fn try_keystroke(&mut self, keystroke: &Keystroke, alt_is_meta: bool) -> bool {
1210 if self.vi_mode_enabled {
1211 self.vi_motion(keystroke);
1212 return true;
1213 }
1214
1215 // Keep default terminal behavior
1216 let esc = to_esc_str(keystroke, &self.last_content.mode, alt_is_meta);
1217 if let Some(esc) = esc {
1218 match esc {
1219 Cow::Borrowed(string) => self.input(string.as_bytes()),
1220 Cow::Owned(string) => self.input(string.into_bytes()),
1221 };
1222 true
1223 } else {
1224 false
1225 }
1226 }
1227
1228 pub fn try_modifiers_change(
1229 &mut self,
1230 modifiers: &Modifiers,
1231 window: &Window,
1232 cx: &mut Context<Self>,
1233 ) {
1234 if self
1235 .last_content
1236 .terminal_bounds
1237 .bounds
1238 .contains(&window.mouse_position())
1239 && modifiers.secondary()
1240 {
1241 self.refresh_hovered_word(window);
1242 }
1243 cx.notify();
1244 }
1245
1246 ///Paste text into the terminal
1247 pub fn paste(&mut self, text: &str) {
1248 let paste_text = if self.last_content.mode.contains(TermMode::BRACKETED_PASTE) {
1249 format!("{}{}{}", "\x1b[200~", text.replace('\x1b', ""), "\x1b[201~")
1250 } else {
1251 text.replace("\r\n", "\r").replace('\n', "\r")
1252 };
1253
1254 self.input(paste_text.into_bytes());
1255 }
1256
1257 pub fn sync(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1258 let term = self.term.clone();
1259 let mut terminal = term.lock_unfair();
1260 //Note that the ordering of events matters for event processing
1261 while let Some(e) = self.events.pop_front() {
1262 self.process_terminal_event(&e, &mut terminal, window, cx)
1263 }
1264
1265 self.last_content = Self::make_content(&terminal, &self.last_content);
1266 }
1267
1268 fn make_content(term: &Term<ZedListener>, last_content: &TerminalContent) -> TerminalContent {
1269 let content = term.renderable_content();
1270 TerminalContent {
1271 cells: content
1272 .display_iter
1273 //TODO: Add this once there's a way to retain empty lines
1274 // .filter(|ic| {
1275 // !ic.flags.contains(Flags::HIDDEN)
1276 // && !(ic.bg == Named(NamedColor::Background)
1277 // && ic.c == ' '
1278 // && !ic.flags.contains(Flags::INVERSE))
1279 // })
1280 .map(|ic| IndexedCell {
1281 point: ic.point,
1282 cell: ic.cell.clone(),
1283 })
1284 .collect::<Vec<IndexedCell>>(),
1285 mode: content.mode,
1286 display_offset: content.display_offset,
1287 selection_text: term.selection_to_string(),
1288 selection: content.selection,
1289 cursor: content.cursor,
1290 cursor_char: term.grid()[content.cursor.point].c,
1291 terminal_bounds: last_content.terminal_bounds,
1292 last_hovered_word: last_content.last_hovered_word.clone(),
1293 scrolled_to_top: content.display_offset == term.history_size(),
1294 scrolled_to_bottom: content.display_offset == 0,
1295 }
1296 }
1297
1298 pub fn get_content(&self) -> String {
1299 let term = self.term.lock_unfair();
1300 let start = AlacPoint::new(term.topmost_line(), Column(0));
1301 let end = AlacPoint::new(term.bottommost_line(), term.last_column());
1302 term.bounds_to_string(start, end)
1303 }
1304
1305 pub fn last_n_non_empty_lines(&self, n: usize) -> Vec<String> {
1306 let term = self.term.clone();
1307 let terminal = term.lock_unfair();
1308 let grid = terminal.grid();
1309 let mut lines = Vec::new();
1310
1311 let mut current_line = grid.bottommost_line().0;
1312 let topmost_line = grid.topmost_line().0;
1313
1314 while current_line >= topmost_line && lines.len() < n {
1315 let logical_line_start = self.find_logical_line_start(grid, current_line, topmost_line);
1316 let logical_line = self.construct_logical_line(grid, logical_line_start, current_line);
1317
1318 if let Some(line) = self.process_line(logical_line) {
1319 lines.push(line);
1320 }
1321
1322 // Move to the line above the start of the current logical line
1323 current_line = logical_line_start - 1;
1324 }
1325
1326 lines.reverse();
1327 lines
1328 }
1329
1330 fn find_logical_line_start(&self, grid: &Grid<Cell>, current: i32, topmost: i32) -> i32 {
1331 let mut line_start = current;
1332 while line_start > topmost {
1333 let prev_line = Line(line_start - 1);
1334 let last_cell = &grid[prev_line][Column(grid.columns() - 1)];
1335 if !last_cell.flags.contains(Flags::WRAPLINE) {
1336 break;
1337 }
1338 line_start -= 1;
1339 }
1340 line_start
1341 }
1342
1343 fn construct_logical_line(&self, grid: &Grid<Cell>, start: i32, end: i32) -> String {
1344 let mut logical_line = String::new();
1345 for row in start..=end {
1346 let grid_row = &grid[Line(row)];
1347 logical_line.push_str(&row_to_string(grid_row));
1348 }
1349 logical_line
1350 }
1351
1352 fn process_line(&self, line: String) -> Option<String> {
1353 let trimmed = line.trim_end().to_string();
1354 if !trimmed.is_empty() {
1355 Some(trimmed)
1356 } else {
1357 None
1358 }
1359 }
1360
1361 pub fn focus_in(&self) {
1362 if self.last_content.mode.contains(TermMode::FOCUS_IN_OUT) {
1363 self.write_to_pty("\x1b[I".as_bytes());
1364 }
1365 }
1366
1367 pub fn focus_out(&mut self) {
1368 if self.last_content.mode.contains(TermMode::FOCUS_IN_OUT) {
1369 self.write_to_pty("\x1b[O".as_bytes());
1370 }
1371 }
1372
1373 pub fn mouse_changed(&mut self, point: AlacPoint, side: AlacDirection) -> bool {
1374 match self.last_mouse {
1375 Some((old_point, old_side)) => {
1376 if old_point == point && old_side == side {
1377 false
1378 } else {
1379 self.last_mouse = Some((point, side));
1380 true
1381 }
1382 }
1383 None => {
1384 self.last_mouse = Some((point, side));
1385 true
1386 }
1387 }
1388 }
1389
1390 pub fn mouse_mode(&self, shift: bool) -> bool {
1391 self.last_content.mode.intersects(TermMode::MOUSE_MODE) && !shift
1392 }
1393
1394 pub fn mouse_move(&mut self, e: &MouseMoveEvent, cx: &mut Context<Self>) {
1395 let position = e.position - self.last_content.terminal_bounds.bounds.origin;
1396 if self.mouse_mode(e.modifiers.shift) {
1397 let (point, side) = grid_point_and_side(
1398 position,
1399 self.last_content.terminal_bounds,
1400 self.last_content.display_offset,
1401 );
1402
1403 if self.mouse_changed(point, side) {
1404 if let Some(bytes) =
1405 mouse_moved_report(point, e.pressed_button, e.modifiers, self.last_content.mode)
1406 {
1407 self.pty_tx.notify(bytes);
1408 }
1409 }
1410 } else if e.modifiers.secondary() {
1411 self.word_from_position(e.position);
1412 }
1413 cx.notify();
1414 }
1415
1416 fn word_from_position(&mut self, position: Point<Pixels>) {
1417 if self.selection_phase == SelectionPhase::Selecting {
1418 self.last_content.last_hovered_word = None;
1419 } else if self.last_content.terminal_bounds.bounds.contains(&position) {
1420 self.events.push_back(InternalEvent::FindHyperlink(
1421 position - self.last_content.terminal_bounds.bounds.origin,
1422 false,
1423 ));
1424 } else {
1425 self.last_content.last_hovered_word = None;
1426 }
1427 }
1428
1429 pub fn select_word_at_event_position(&mut self, e: &MouseDownEvent) {
1430 let position = e.position - self.last_content.terminal_bounds.bounds.origin;
1431 let (point, side) = grid_point_and_side(
1432 position,
1433 self.last_content.terminal_bounds,
1434 self.last_content.display_offset,
1435 );
1436 let selection = Selection::new(SelectionType::Semantic, point, side);
1437 self.events
1438 .push_back(InternalEvent::SetSelection(Some((selection, point))));
1439 }
1440
1441 pub fn mouse_drag(
1442 &mut self,
1443 e: &MouseMoveEvent,
1444 region: Bounds<Pixels>,
1445 cx: &mut Context<Self>,
1446 ) {
1447 let position = e.position - self.last_content.terminal_bounds.bounds.origin;
1448 if !self.mouse_mode(e.modifiers.shift) {
1449 self.selection_phase = SelectionPhase::Selecting;
1450 // Alacritty has the same ordering, of first updating the selection
1451 // then scrolling 15ms later
1452 self.events
1453 .push_back(InternalEvent::UpdateSelection(position));
1454
1455 // Doesn't make sense to scroll the alt screen
1456 if !self.last_content.mode.contains(TermMode::ALT_SCREEN) {
1457 let scroll_lines = match self.drag_line_delta(e, region) {
1458 Some(value) => value,
1459 None => return,
1460 };
1461
1462 self.events
1463 .push_back(InternalEvent::Scroll(AlacScroll::Delta(scroll_lines)));
1464 }
1465
1466 cx.notify();
1467 }
1468 }
1469
1470 fn drag_line_delta(&self, e: &MouseMoveEvent, region: Bounds<Pixels>) -> Option<i32> {
1471 let top = region.origin.y;
1472 let bottom = region.bottom_left().y;
1473
1474 let scroll_lines = if e.position.y < top {
1475 let scroll_delta = (top - e.position.y).pow(1.1);
1476 (scroll_delta / self.last_content.terminal_bounds.line_height).ceil() as i32
1477 } else if e.position.y > bottom {
1478 let scroll_delta = -((e.position.y - bottom).pow(1.1));
1479 (scroll_delta / self.last_content.terminal_bounds.line_height).floor() as i32
1480 } else {
1481 return None;
1482 };
1483
1484 Some(scroll_lines.clamp(-3, 3))
1485 }
1486
1487 pub fn mouse_down(&mut self, e: &MouseDownEvent, _cx: &mut Context<Self>) {
1488 let position = e.position - self.last_content.terminal_bounds.bounds.origin;
1489 let point = grid_point(
1490 position,
1491 self.last_content.terminal_bounds,
1492 self.last_content.display_offset,
1493 );
1494
1495 if self.mouse_mode(e.modifiers.shift) {
1496 if let Some(bytes) =
1497 mouse_button_report(point, e.button, e.modifiers, true, self.last_content.mode)
1498 {
1499 self.pty_tx.notify(bytes);
1500 }
1501 } else {
1502 match e.button {
1503 MouseButton::Left => {
1504 let (point, side) = grid_point_and_side(
1505 position,
1506 self.last_content.terminal_bounds,
1507 self.last_content.display_offset,
1508 );
1509
1510 let selection_type = match e.click_count {
1511 0 => return, //This is a release
1512 1 => Some(SelectionType::Simple),
1513 2 => Some(SelectionType::Semantic),
1514 3 => Some(SelectionType::Lines),
1515 _ => None,
1516 };
1517
1518 if selection_type == Some(SelectionType::Simple) && e.modifiers.shift {
1519 self.events
1520 .push_back(InternalEvent::UpdateSelection(position));
1521 return;
1522 }
1523
1524 let selection = selection_type
1525 .map(|selection_type| Selection::new(selection_type, point, side));
1526
1527 if let Some(sel) = selection {
1528 self.events
1529 .push_back(InternalEvent::SetSelection(Some((sel, point))));
1530 }
1531 }
1532 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1533 MouseButton::Middle => {
1534 if let Some(item) = _cx.read_from_primary() {
1535 let text = item.text().unwrap_or_default().to_string();
1536 self.input(text.into_bytes());
1537 }
1538 }
1539 _ => {}
1540 }
1541 }
1542 }
1543
1544 pub fn mouse_up(&mut self, e: &MouseUpEvent, cx: &Context<Self>) {
1545 let setting = TerminalSettings::get_global(cx);
1546
1547 let position = e.position - self.last_content.terminal_bounds.bounds.origin;
1548 if self.mouse_mode(e.modifiers.shift) {
1549 let point = grid_point(
1550 position,
1551 self.last_content.terminal_bounds,
1552 self.last_content.display_offset,
1553 );
1554
1555 if let Some(bytes) =
1556 mouse_button_report(point, e.button, e.modifiers, false, self.last_content.mode)
1557 {
1558 self.pty_tx.notify(bytes);
1559 }
1560 } else {
1561 if e.button == MouseButton::Left && setting.copy_on_select {
1562 self.copy();
1563 }
1564
1565 //Hyperlinks
1566 if self.selection_phase == SelectionPhase::Ended {
1567 let mouse_cell_index =
1568 content_index_for_mouse(position, &self.last_content.terminal_bounds);
1569 if let Some(link) = self.last_content.cells[mouse_cell_index].hyperlink() {
1570 cx.open_url(link.uri());
1571 } else if e.modifiers.secondary() {
1572 self.events
1573 .push_back(InternalEvent::FindHyperlink(position, true));
1574 }
1575 }
1576 }
1577
1578 self.selection_phase = SelectionPhase::Ended;
1579 self.last_mouse = None;
1580 }
1581
1582 ///Scroll the terminal
1583 pub fn scroll_wheel(&mut self, e: &ScrollWheelEvent) {
1584 let mouse_mode = self.mouse_mode(e.shift);
1585
1586 if let Some(scroll_lines) = self.determine_scroll_lines(e, mouse_mode) {
1587 if mouse_mode {
1588 let point = grid_point(
1589 e.position - self.last_content.terminal_bounds.bounds.origin,
1590 self.last_content.terminal_bounds,
1591 self.last_content.display_offset,
1592 );
1593
1594 if let Some(scrolls) = scroll_report(point, scroll_lines, e, self.last_content.mode)
1595 {
1596 for scroll in scrolls {
1597 self.pty_tx.notify(scroll);
1598 }
1599 };
1600 } else if self
1601 .last_content
1602 .mode
1603 .contains(TermMode::ALT_SCREEN | TermMode::ALTERNATE_SCROLL)
1604 && !e.shift
1605 {
1606 self.pty_tx.notify(alt_scroll(scroll_lines))
1607 } else if scroll_lines != 0 {
1608 let scroll = AlacScroll::Delta(scroll_lines);
1609
1610 self.events.push_back(InternalEvent::Scroll(scroll));
1611 }
1612 }
1613 }
1614
1615 fn refresh_hovered_word(&mut self, window: &Window) {
1616 self.word_from_position(window.mouse_position());
1617 }
1618
1619 fn determine_scroll_lines(&mut self, e: &ScrollWheelEvent, mouse_mode: bool) -> Option<i32> {
1620 let scroll_multiplier = if mouse_mode { 1. } else { SCROLL_MULTIPLIER };
1621 let line_height = self.last_content.terminal_bounds.line_height;
1622 match e.touch_phase {
1623 /* Reset scroll state on started */
1624 TouchPhase::Started => {
1625 self.scroll_px = px(0.);
1626 None
1627 }
1628 /* Calculate the appropriate scroll lines */
1629 TouchPhase::Moved => {
1630 let old_offset = (self.scroll_px / line_height) as i32;
1631
1632 self.scroll_px += e.delta.pixel_delta(line_height).y * scroll_multiplier;
1633
1634 let new_offset = (self.scroll_px / line_height) as i32;
1635
1636 // Whenever we hit the edges, reset our stored scroll to 0
1637 // so we can respond to changes in direction quickly
1638 self.scroll_px %= self.last_content.terminal_bounds.height();
1639
1640 Some(new_offset - old_offset)
1641 }
1642 TouchPhase::Ended => None,
1643 }
1644 }
1645
1646 pub fn find_matches(
1647 &self,
1648 mut searcher: RegexSearch,
1649 cx: &Context<Self>,
1650 ) -> Task<Vec<RangeInclusive<AlacPoint>>> {
1651 let term = self.term.clone();
1652 cx.background_spawn(async move {
1653 let term = term.lock();
1654
1655 all_search_matches(&term, &mut searcher).collect()
1656 })
1657 }
1658
1659 pub fn working_directory(&self) -> Option<PathBuf> {
1660 if self.is_ssh_terminal {
1661 // We can't yet reliably detect the working directory of a shell on the
1662 // SSH host. Until we can do that, it doesn't make sense to display
1663 // the working directory on the client and persist that.
1664 None
1665 } else {
1666 self.client_side_working_directory()
1667 }
1668 }
1669
1670 /// Returns the working directory of the process that's connected to the PTY.
1671 /// That means it returns the working directory of the local shell or program
1672 /// that's running inside the terminal.
1673 ///
1674 /// This does *not* return the working directory of the shell that runs on the
1675 /// remote host, in case Zed is connected to a remote host.
1676 fn client_side_working_directory(&self) -> Option<PathBuf> {
1677 self.pty_info
1678 .current
1679 .as_ref()
1680 .map(|process| process.cwd.clone())
1681 }
1682
1683 pub fn title(&self, truncate: bool) -> String {
1684 const MAX_CHARS: usize = 25;
1685 match &self.task {
1686 Some(task_state) => {
1687 if truncate {
1688 truncate_and_trailoff(&task_state.label, MAX_CHARS)
1689 } else {
1690 task_state.full_label.clone()
1691 }
1692 }
1693 None => self
1694 .title_override
1695 .as_ref()
1696 .map(|title_override| title_override.to_string())
1697 .unwrap_or_else(|| {
1698 self.pty_info
1699 .current
1700 .as_ref()
1701 .map(|fpi| {
1702 let process_file = fpi
1703 .cwd
1704 .file_name()
1705 .map(|name| name.to_string_lossy().to_string())
1706 .unwrap_or_default();
1707
1708 let argv = fpi.argv.as_slice();
1709 let process_name = format!(
1710 "{}{}",
1711 fpi.name,
1712 if !argv.is_empty() {
1713 format!(" {}", (argv[1..]).join(" "))
1714 } else {
1715 "".to_string()
1716 }
1717 );
1718 let (process_file, process_name) = if truncate {
1719 (
1720 truncate_and_trailoff(&process_file, MAX_CHARS),
1721 truncate_and_trailoff(&process_name, MAX_CHARS),
1722 )
1723 } else {
1724 (process_file, process_name)
1725 };
1726 format!("{process_file} — {process_name}")
1727 })
1728 .unwrap_or_else(|| "Terminal".to_string())
1729 }),
1730 }
1731 }
1732
1733 pub fn task(&self) -> Option<&TaskState> {
1734 self.task.as_ref()
1735 }
1736
1737 pub fn wait_for_completed_task(&self, cx: &App) -> Task<Option<ExitStatus>> {
1738 if let Some(task) = self.task() {
1739 if task.status == TaskStatus::Running {
1740 let completion_receiver = task.completion_rx.clone();
1741 return cx.spawn(async move |_| completion_receiver.recv().await.ok().flatten());
1742 } else if let Ok(status) = task.completion_rx.try_recv() {
1743 return Task::ready(status);
1744 }
1745 }
1746 Task::ready(None)
1747 }
1748
1749 fn register_task_finished(&mut self, error_code: Option<i32>, cx: &mut Context<Terminal>) {
1750 let e: Option<ExitStatus> = error_code.map(|code| {
1751 #[cfg(unix)]
1752 {
1753 return std::os::unix::process::ExitStatusExt::from_raw(code);
1754 }
1755 #[cfg(windows)]
1756 {
1757 return std::os::windows::process::ExitStatusExt::from_raw(code as u32);
1758 }
1759 });
1760
1761 self.completion_tx.try_send(e).ok();
1762 let task = match &mut self.task {
1763 Some(task) => task,
1764 None => {
1765 if error_code.is_none() {
1766 cx.emit(Event::CloseTerminal);
1767 }
1768 return;
1769 }
1770 };
1771 if task.status != TaskStatus::Running {
1772 return;
1773 }
1774 match error_code {
1775 Some(error_code) => {
1776 task.status.register_task_exit(error_code);
1777 }
1778 None => {
1779 task.status.register_terminal_exit();
1780 }
1781 };
1782
1783 let (finished_successfully, task_line, command_line) = task_summary(task, error_code);
1784 let mut lines_to_show = Vec::new();
1785 if task.show_summary {
1786 lines_to_show.push(task_line.as_str());
1787 }
1788 if task.show_command {
1789 lines_to_show.push(command_line.as_str());
1790 }
1791
1792 if !lines_to_show.is_empty() {
1793 // SAFETY: the invocation happens on non `TaskStatus::Running` tasks, once,
1794 // after either `AlacTermEvent::Exit` or `AlacTermEvent::ChildExit` events that are spawned
1795 // when Zed task finishes and no more output is made.
1796 // After the task summary is output once, no more text is appended to the terminal.
1797 unsafe { append_text_to_term(&mut self.term.lock(), &lines_to_show) };
1798 }
1799
1800 match task.hide {
1801 HideStrategy::Never => {}
1802 HideStrategy::Always => {
1803 cx.emit(Event::CloseTerminal);
1804 }
1805 HideStrategy::OnSuccess => {
1806 if finished_successfully {
1807 cx.emit(Event::CloseTerminal);
1808 }
1809 }
1810 }
1811 }
1812
1813 pub fn vi_mode_enabled(&self) -> bool {
1814 self.vi_mode_enabled
1815 }
1816}
1817
1818// Helper function to convert a grid row to a string
1819pub fn row_to_string(row: &Row<Cell>) -> String {
1820 row[..Column(row.len())]
1821 .iter()
1822 .map(|cell| cell.c)
1823 .collect::<String>()
1824}
1825
1826const TASK_DELIMITER: &str = "⏵ ";
1827fn task_summary(task: &TaskState, error_code: Option<i32>) -> (bool, String, String) {
1828 let escaped_full_label = task.full_label.replace("\r\n", "\r").replace('\n', "\r");
1829 let (success, task_line) = match error_code {
1830 Some(0) => (
1831 true,
1832 format!("{TASK_DELIMITER}Task `{escaped_full_label}` finished successfully"),
1833 ),
1834 Some(error_code) => (
1835 false,
1836 format!(
1837 "{TASK_DELIMITER}Task `{escaped_full_label}` finished with non-zero error code: {error_code}"
1838 ),
1839 ),
1840 None => (
1841 false,
1842 format!("{TASK_DELIMITER}Task `{escaped_full_label}` finished"),
1843 ),
1844 };
1845 let escaped_command_label = task.command_label.replace("\r\n", "\r").replace('\n', "\r");
1846 let command_line = format!("{TASK_DELIMITER}Command: {escaped_command_label}");
1847 (success, task_line, command_line)
1848}
1849
1850/// Appends a stringified task summary to the terminal, after its output.
1851///
1852/// SAFETY: This function should only be called after terminal's PTY is no longer alive.
1853/// New text being added to the terminal here, uses "less public" APIs,
1854/// which are not maintaining the entire terminal state intact.
1855///
1856///
1857/// The library
1858///
1859/// * does not increment inner grid cursor's _lines_ on `input` calls
1860/// (but displaying the lines correctly and incrementing cursor's columns)
1861///
1862/// * ignores `\n` and \r` character input, requiring the `newline` call instead
1863///
1864/// * does not alter grid state after `newline` call
1865/// so its `bottommost_line` is always the same additions, and
1866/// the cursor's `point` is not updated to the new line and column values
1867///
1868/// * ??? there could be more consequences, and any further "proper" streaming from the PTY might bug and/or panic.
1869/// Still, subsequent `append_text_to_term` invocations are possible and display the contents correctly.
1870///
1871/// Despite the quirks, this is the simplest approach to appending text to the terminal: its alternative, `grid_mut` manipulations,
1872/// do not properly set the scrolling state and display odd text after appending; also those manipulations are more tedious and error-prone.
1873/// The function achieves proper display and scrolling capabilities, at a cost of grid state not properly synchronized.
1874/// This is enough for printing moderately-sized texts like task summaries, but might break or perform poorly for larger texts.
1875unsafe fn append_text_to_term(term: &mut Term<ZedListener>, text_lines: &[&str]) {
1876 term.newline();
1877 term.grid_mut().cursor.point.column = Column(0);
1878 for line in text_lines {
1879 for c in line.chars() {
1880 term.input(c);
1881 }
1882 term.newline();
1883 term.grid_mut().cursor.point.column = Column(0);
1884 }
1885}
1886
1887impl Drop for Terminal {
1888 fn drop(&mut self) {
1889 self.pty_tx.0.send(Msg::Shutdown).ok();
1890 }
1891}
1892
1893impl EventEmitter<Event> for Terminal {}
1894
1895fn make_selection(range: &RangeInclusive<AlacPoint>) -> Selection {
1896 let mut selection = Selection::new(SelectionType::Simple, *range.start(), AlacDirection::Left);
1897 selection.update(*range.end(), AlacDirection::Right);
1898 selection
1899}
1900
1901fn all_search_matches<'a, T>(
1902 term: &'a Term<T>,
1903 regex: &'a mut RegexSearch,
1904) -> impl Iterator<Item = Match> + 'a {
1905 let start = AlacPoint::new(term.grid().topmost_line(), Column(0));
1906 let end = AlacPoint::new(term.grid().bottommost_line(), term.grid().last_column());
1907 RegexIter::new(start, end, AlacDirection::Right, term, regex)
1908}
1909
1910fn content_index_for_mouse(pos: Point<Pixels>, terminal_bounds: &TerminalBounds) -> usize {
1911 let col = (pos.x / terminal_bounds.cell_width()).round() as usize;
1912 let clamped_col = min(col, terminal_bounds.columns() - 1);
1913 let row = (pos.y / terminal_bounds.line_height()).round() as usize;
1914 let clamped_row = min(row, terminal_bounds.screen_lines() - 1);
1915 clamped_row * terminal_bounds.columns() + clamped_col
1916}
1917
1918/// Converts an 8 bit ANSI color to its GPUI equivalent.
1919/// Accepts `usize` for compatibility with the `alacritty::Colors` interface,
1920/// Other than that use case, should only be called with values in the `[0,255]` range
1921pub fn get_color_at_index(index: usize, theme: &Theme) -> Hsla {
1922 let colors = theme.colors();
1923
1924 match index {
1925 // 0-15 are the same as the named colors above
1926 0 => colors.terminal_ansi_black,
1927 1 => colors.terminal_ansi_red,
1928 2 => colors.terminal_ansi_green,
1929 3 => colors.terminal_ansi_yellow,
1930 4 => colors.terminal_ansi_blue,
1931 5 => colors.terminal_ansi_magenta,
1932 6 => colors.terminal_ansi_cyan,
1933 7 => colors.terminal_ansi_white,
1934 8 => colors.terminal_ansi_bright_black,
1935 9 => colors.terminal_ansi_bright_red,
1936 10 => colors.terminal_ansi_bright_green,
1937 11 => colors.terminal_ansi_bright_yellow,
1938 12 => colors.terminal_ansi_bright_blue,
1939 13 => colors.terminal_ansi_bright_magenta,
1940 14 => colors.terminal_ansi_bright_cyan,
1941 15 => colors.terminal_ansi_bright_white,
1942 // 16-231 are a 6x6x6 RGB color cube, mapped to 0-255 using steps defined by XTerm.
1943 // See: https://github.com/xterm-x11/xterm-snapshots/blob/master/256colres.pl
1944 16..=231 => {
1945 let (r, g, b) = rgb_for_index(index as u8);
1946 rgba_color(
1947 if r == 0 { 0 } else { r * 40 + 55 },
1948 if g == 0 { 0 } else { g * 40 + 55 },
1949 if b == 0 { 0 } else { b * 40 + 55 },
1950 )
1951 }
1952 // 232-255 are a 24-step grayscale ramp from (8, 8, 8) to (238, 238, 238).
1953 232..=255 => {
1954 let i = index as u8 - 232; // Align index to 0..24
1955 let value = i * 10 + 8;
1956 rgba_color(value, value, value)
1957 }
1958 // For compatibility with the alacritty::Colors interface
1959 // See: https://github.com/alacritty/alacritty/blob/master/alacritty_terminal/src/term/color.rs
1960 256 => colors.terminal_foreground,
1961 257 => colors.terminal_background,
1962 258 => theme.players().local().cursor,
1963 259 => colors.terminal_ansi_dim_black,
1964 260 => colors.terminal_ansi_dim_red,
1965 261 => colors.terminal_ansi_dim_green,
1966 262 => colors.terminal_ansi_dim_yellow,
1967 263 => colors.terminal_ansi_dim_blue,
1968 264 => colors.terminal_ansi_dim_magenta,
1969 265 => colors.terminal_ansi_dim_cyan,
1970 266 => colors.terminal_ansi_dim_white,
1971 267 => colors.terminal_bright_foreground,
1972 268 => colors.terminal_ansi_black, // 'Dim Background', non-standard color
1973
1974 _ => black(),
1975 }
1976}
1977
1978/// Generates the RGB channels in [0, 5] for a given index into the 6x6x6 ANSI color cube.
1979/// See: [8 bit ANSI color](https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit).
1980///
1981/// Wikipedia gives a formula for calculating the index for a given color:
1982///
1983/// ```
1984/// index = 16 + 36 × r + 6 × g + b (0 ≤ r, g, b ≤ 5)
1985/// ```
1986///
1987/// This function does the reverse, calculating the `r`, `g`, and `b` components from a given index.
1988fn rgb_for_index(i: u8) -> (u8, u8, u8) {
1989 debug_assert!((16..=231).contains(&i));
1990 let i = i - 16;
1991 let r = (i - (i % 36)) / 36;
1992 let g = ((i % 36) - (i % 6)) / 6;
1993 let b = (i % 36) % 6;
1994 (r, g, b)
1995}
1996
1997pub fn rgba_color(r: u8, g: u8, b: u8) -> Hsla {
1998 Rgba {
1999 r: (r as f32 / 255.),
2000 g: (g as f32 / 255.),
2001 b: (b as f32 / 255.),
2002 a: 1.,
2003 }
2004 .into()
2005}
2006
2007#[cfg(test)]
2008mod tests {
2009 use alacritty_terminal::{
2010 index::{Column, Line, Point as AlacPoint},
2011 term::cell::Cell,
2012 };
2013 use gpui::{Pixels, Point, bounds, point, size};
2014 use rand::{Rng, distributions::Alphanumeric, rngs::ThreadRng, thread_rng};
2015
2016 use crate::{
2017 IndexedCell, TerminalBounds, TerminalContent, content_index_for_mouse, rgb_for_index,
2018 };
2019
2020 #[test]
2021 fn test_rgb_for_index() {
2022 // Test every possible value in the color cube.
2023 for i in 16..=231 {
2024 let (r, g, b) = rgb_for_index(i);
2025 assert_eq!(i, 16 + 36 * r + 6 * g + b);
2026 }
2027 }
2028
2029 #[test]
2030 fn test_mouse_to_cell_test() {
2031 let mut rng = thread_rng();
2032 const ITERATIONS: usize = 10;
2033 const PRECISION: usize = 1000;
2034
2035 for _ in 0..ITERATIONS {
2036 let viewport_cells = rng.gen_range(15..20);
2037 let cell_size = rng.gen_range(5 * PRECISION..20 * PRECISION) as f32 / PRECISION as f32;
2038
2039 let size = crate::TerminalBounds {
2040 cell_width: Pixels::from(cell_size),
2041 line_height: Pixels::from(cell_size),
2042 bounds: bounds(
2043 Point::default(),
2044 size(
2045 Pixels::from(cell_size * (viewport_cells as f32)),
2046 Pixels::from(cell_size * (viewport_cells as f32)),
2047 ),
2048 ),
2049 };
2050
2051 let cells = get_cells(size, &mut rng);
2052 let content = convert_cells_to_content(size, &cells);
2053
2054 for row in 0..(viewport_cells - 1) {
2055 let row = row as usize;
2056 for col in 0..(viewport_cells - 1) {
2057 let col = col as usize;
2058
2059 let row_offset = rng.gen_range(0..PRECISION) as f32 / PRECISION as f32;
2060 let col_offset = rng.gen_range(0..PRECISION) as f32 / PRECISION as f32;
2061
2062 let mouse_pos = point(
2063 Pixels::from(col as f32 * cell_size + col_offset),
2064 Pixels::from(row as f32 * cell_size + row_offset),
2065 );
2066
2067 let content_index =
2068 content_index_for_mouse(mouse_pos, &content.terminal_bounds);
2069 let mouse_cell = content.cells[content_index].c;
2070 let real_cell = cells[row][col];
2071
2072 assert_eq!(mouse_cell, real_cell);
2073 }
2074 }
2075 }
2076 }
2077
2078 #[test]
2079 fn test_mouse_to_cell_clamp() {
2080 let mut rng = thread_rng();
2081
2082 let size = crate::TerminalBounds {
2083 cell_width: Pixels::from(10.),
2084 line_height: Pixels::from(10.),
2085 bounds: bounds(
2086 Point::default(),
2087 size(Pixels::from(100.), Pixels::from(100.)),
2088 ),
2089 };
2090
2091 let cells = get_cells(size, &mut rng);
2092 let content = convert_cells_to_content(size, &cells);
2093
2094 assert_eq!(
2095 content.cells[content_index_for_mouse(
2096 point(Pixels::from(-10.), Pixels::from(-10.)),
2097 &content.terminal_bounds,
2098 )]
2099 .c,
2100 cells[0][0]
2101 );
2102 assert_eq!(
2103 content.cells[content_index_for_mouse(
2104 point(Pixels::from(1000.), Pixels::from(1000.)),
2105 &content.terminal_bounds,
2106 )]
2107 .c,
2108 cells[9][9]
2109 );
2110 }
2111
2112 fn get_cells(size: TerminalBounds, rng: &mut ThreadRng) -> Vec<Vec<char>> {
2113 let mut cells = Vec::new();
2114
2115 for _ in 0..((size.height() / size.line_height()) as usize) {
2116 let mut row_vec = Vec::new();
2117 for _ in 0..((size.width() / size.cell_width()) as usize) {
2118 let cell_char = rng.sample(Alphanumeric) as char;
2119 row_vec.push(cell_char)
2120 }
2121 cells.push(row_vec)
2122 }
2123
2124 cells
2125 }
2126
2127 fn convert_cells_to_content(
2128 terminal_bounds: TerminalBounds,
2129 cells: &[Vec<char>],
2130 ) -> TerminalContent {
2131 let mut ic = Vec::new();
2132
2133 for (index, row) in cells.iter().enumerate() {
2134 for (cell_index, cell_char) in row.iter().enumerate() {
2135 ic.push(IndexedCell {
2136 point: AlacPoint::new(Line(index as i32), Column(cell_index)),
2137 cell: Cell {
2138 c: *cell_char,
2139 ..Default::default()
2140 },
2141 });
2142 }
2143 }
2144
2145 TerminalContent {
2146 cells: ic,
2147 terminal_bounds,
2148 ..Default::default()
2149 }
2150 }
2151}