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