1pub mod mappings;
2
3pub use alacritty_terminal;
4
5mod pty_info;
6pub mod terminal_settings;
7
8use alacritty_terminal::{
9 event::{Event as AlacTermEvent, EventListener, Notify, WindowSize},
10 event_loop::{EventLoop, Msg, Notifier},
11 grid::{Dimensions, Scroll as AlacScroll},
12 index::{Boundary, Column, Direction as AlacDirection, Line, Point as AlacPoint},
13 selection::{Selection, SelectionRange, SelectionType},
14 sync::FairMutex,
15 term::{
16 cell::Cell,
17 search::{Match, RegexIter, RegexSearch},
18 Config, RenderableCursor, TermMode,
19 },
20 tty::{self, setup_env},
21 vte::ansi::{ClearMode, Handler, NamedPrivateMode, PrivateMode, Rgb},
22 Term,
23};
24use anyhow::{bail, Result};
25
26use futures::{
27 channel::mpsc::{unbounded, UnboundedReceiver, UnboundedSender},
28 FutureExt,
29};
30
31use mappings::mouse::{
32 alt_scroll, grid_point, grid_point_and_side, mouse_button_report, mouse_moved_report,
33 scroll_report,
34};
35
36use collections::{HashMap, VecDeque};
37use futures::StreamExt;
38use pty_info::PtyProcessInfo;
39use serde::{Deserialize, Serialize};
40use settings::Settings;
41use smol::channel::{Receiver, Sender};
42use task::{static_source::RevealStrategy, TaskId};
43use terminal_settings::{AlternateScroll, Shell, TerminalBlink, TerminalSettings};
44use theme::{ActiveTheme, Theme};
45use util::truncate_and_trailoff;
46
47use std::{
48 cmp::{self, min},
49 fmt::Display,
50 ops::{Deref, Index, RangeInclusive},
51 path::PathBuf,
52 sync::Arc,
53 time::Duration,
54};
55use thiserror::Error;
56
57use gpui::{
58 actions, black, px, AnyWindowHandle, AppContext, Bounds, ClipboardItem, EventEmitter, Hsla,
59 Keystroke, ModelContext, Modifiers, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent,
60 Pixels, Point, Rgba, ScrollWheelEvent, Size, Task, TouchPhase,
61};
62
63use crate::mappings::{colors::to_alac_rgb, keys::to_esc_str};
64
65actions!(
66 terminal,
67 [Clear, Copy, Paste, ShowCharacterPalette, SearchTest,]
68);
69
70///Scrolling is unbearably sluggish by default. Alacritty supports a configurable
71///Scroll multiplier that is set to 3 by default. This will be removed when I
72///Implement scroll bars.
73#[cfg(target_os = "macos")]
74const SCROLL_MULTIPLIER: f32 = 4.;
75#[cfg(not(target_os = "macos"))]
76const SCROLL_MULTIPLIER: f32 = 1.;
77const MAX_SEARCH_LINES: usize = 100;
78const DEBUG_TERMINAL_WIDTH: Pixels = px(500.);
79const DEBUG_TERMINAL_HEIGHT: Pixels = px(30.);
80const DEBUG_CELL_WIDTH: Pixels = px(5.);
81const DEBUG_LINE_HEIGHT: Pixels = px(5.);
82
83///Upward flowing events, for changing the title and such
84#[derive(Clone, Debug)]
85pub enum Event {
86 TitleChanged,
87 BreadcrumbsChanged,
88 CloseTerminal,
89 Bell,
90 Wakeup,
91 BlinkChanged,
92 SelectionsChanged,
93 NewNavigationTarget(Option<MaybeNavigationTarget>),
94 Open(MaybeNavigationTarget),
95}
96
97#[derive(Clone, Debug)]
98pub struct PathLikeTarget {
99 /// File system path, absolute or relative, existing or not.
100 /// Might have line and column number(s) attached as `file.rs:1:23`
101 pub maybe_path: String,
102 /// Current working directory of the terminal
103 pub terminal_dir: Option<PathBuf>,
104}
105
106/// A string inside terminal, potentially useful as a URI that can be opened.
107#[derive(Clone, Debug)]
108pub enum MaybeNavigationTarget {
109 /// HTTP, git, etc. string determined by the [`URL_REGEX`] regex.
110 Url(String),
111 /// File system path, absolute or relative, existing or not.
112 /// Might have line and column number(s) attached as `file.rs:1:23`
113 PathLike(PathLikeTarget),
114}
115
116#[derive(Clone)]
117enum InternalEvent {
118 ColorRequest(usize, Arc<dyn Fn(Rgb) -> String + Sync + Send + 'static>),
119 Resize(TerminalSize),
120 Clear,
121 // FocusNextMatch,
122 Scroll(AlacScroll),
123 ScrollToAlacPoint(AlacPoint),
124 SetSelection(Option<(Selection, AlacPoint)>),
125 UpdateSelection(Point<Pixels>),
126 // Adjusted mouse position, should open
127 FindHyperlink(Point<Pixels>, bool),
128 Copy,
129}
130
131///A translation struct for Alacritty to communicate with us from their event loop
132#[derive(Clone)]
133pub struct ZedListener(UnboundedSender<AlacTermEvent>);
134
135impl EventListener for ZedListener {
136 fn send_event(&self, event: AlacTermEvent) {
137 self.0.unbounded_send(event).ok();
138 }
139}
140
141pub fn init(cx: &mut AppContext) {
142 TerminalSettings::register(cx);
143}
144
145#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
146pub struct TerminalSize {
147 pub cell_width: Pixels,
148 pub line_height: Pixels,
149 pub size: Size<Pixels>,
150}
151
152impl TerminalSize {
153 pub fn new(line_height: Pixels, cell_width: Pixels, size: Size<Pixels>) -> Self {
154 TerminalSize {
155 cell_width,
156 line_height,
157 size,
158 }
159 }
160
161 pub fn num_lines(&self) -> usize {
162 (self.size.height / self.line_height).floor() as usize
163 }
164
165 pub fn num_columns(&self) -> usize {
166 (self.size.width / self.cell_width).floor() as usize
167 }
168
169 pub fn height(&self) -> Pixels {
170 self.size.height
171 }
172
173 pub fn width(&self) -> Pixels {
174 self.size.width
175 }
176
177 pub fn cell_width(&self) -> Pixels {
178 self.cell_width
179 }
180
181 pub fn line_height(&self) -> Pixels {
182 self.line_height
183 }
184}
185
186impl Default for TerminalSize {
187 fn default() -> Self {
188 TerminalSize::new(
189 DEBUG_LINE_HEIGHT,
190 DEBUG_CELL_WIDTH,
191 Size {
192 width: DEBUG_TERMINAL_WIDTH,
193 height: DEBUG_TERMINAL_HEIGHT,
194 },
195 )
196 }
197}
198
199impl From<TerminalSize> for WindowSize {
200 fn from(val: TerminalSize) -> Self {
201 WindowSize {
202 num_lines: val.num_lines() as u16,
203 num_cols: val.num_columns() as u16,
204 cell_width: f32::from(val.cell_width()) as u16,
205 cell_height: f32::from(val.line_height()) as u16,
206 }
207 }
208}
209
210impl Dimensions for TerminalSize {
211 /// Note: this is supposed to be for the back buffer's length,
212 /// but we exclusively use it to resize the terminal, which does not
213 /// use this method. We still have to implement it for the trait though,
214 /// hence, this comment.
215 fn total_lines(&self) -> usize {
216 self.screen_lines()
217 }
218
219 fn screen_lines(&self) -> usize {
220 self.num_lines()
221 }
222
223 fn columns(&self) -> usize {
224 self.num_columns()
225 }
226}
227
228#[derive(Error, Debug)]
229pub struct TerminalError {
230 pub directory: Option<PathBuf>,
231 pub shell: Shell,
232 pub source: std::io::Error,
233}
234
235impl TerminalError {
236 pub fn fmt_directory(&self) -> String {
237 self.directory
238 .clone()
239 .map(|path| {
240 match path
241 .into_os_string()
242 .into_string()
243 .map_err(|os_str| format!("<non-utf8 path> {}", os_str.to_string_lossy()))
244 {
245 Ok(s) => s,
246 Err(s) => s,
247 }
248 })
249 .unwrap_or_else(|| {
250 let default_dir =
251 dirs::home_dir().map(|buf| buf.into_os_string().to_string_lossy().to_string());
252 match default_dir {
253 Some(dir) => format!("<none specified, using home directory> {}", dir),
254 None => "<none specified, could not find home directory>".to_string(),
255 }
256 })
257 }
258
259 pub fn shell_to_string(&self) -> String {
260 match &self.shell {
261 Shell::System => "<system shell>".to_string(),
262 Shell::Program(p) => p.to_string(),
263 Shell::WithArguments { program, args } => format!("{} {}", program, args.join(" ")),
264 }
265 }
266
267 pub fn fmt_shell(&self) -> String {
268 match &self.shell {
269 Shell::System => "<system defined shell>".to_string(),
270 Shell::Program(s) => s.to_string(),
271 Shell::WithArguments { program, args } => format!("{} {}", program, args.join(" ")),
272 }
273 }
274}
275
276impl Display for TerminalError {
277 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
278 let dir_string: String = self.fmt_directory();
279 let shell = self.fmt_shell();
280
281 write!(
282 f,
283 "Working directory: {} Shell command: `{}`, IOError: {}",
284 dir_string, shell, self.source
285 )
286 }
287}
288
289pub struct SpawnTask {
290 pub id: TaskId,
291 pub label: String,
292 pub command: String,
293 pub args: Vec<String>,
294 pub env: HashMap<String, String>,
295 pub reveal: RevealStrategy,
296}
297
298// https://github.com/alacritty/alacritty/blob/cb3a79dbf6472740daca8440d5166c1d4af5029e/extra/man/alacritty.5.scd?plain=1#L207-L213
299const DEFAULT_SCROLL_HISTORY_LINES: usize = 10_000;
300const MAX_SCROLL_HISTORY_LINES: usize = 100_000;
301
302pub struct TerminalBuilder {
303 terminal: Terminal,
304 events_rx: UnboundedReceiver<AlacTermEvent>,
305}
306
307impl TerminalBuilder {
308 #[allow(clippy::too_many_arguments)]
309 pub fn new(
310 working_directory: Option<PathBuf>,
311 task: Option<TaskState>,
312 shell: Shell,
313 env: HashMap<String, String>,
314 blink_settings: Option<TerminalBlink>,
315 alternate_scroll: AlternateScroll,
316 max_scroll_history_lines: Option<usize>,
317 window: AnyWindowHandle,
318 completion_tx: Sender<()>,
319 ) -> Result<TerminalBuilder> {
320 let pty_options = {
321 let alac_shell = match shell.clone() {
322 Shell::System => None,
323 Shell::Program(program) => {
324 Some(alacritty_terminal::tty::Shell::new(program, Vec::new()))
325 }
326 Shell::WithArguments { program, args } => {
327 Some(alacritty_terminal::tty::Shell::new(program, args))
328 }
329 };
330
331 alacritty_terminal::tty::Options {
332 shell: alac_shell,
333 working_directory: working_directory.clone(),
334 hold: false,
335 }
336 };
337
338 // First, setup Alacritty's env
339 setup_env();
340
341 // Then setup configured environment variables
342 for (key, value) in env {
343 std::env::set_var(key, value);
344 }
345 //TODO: Properly set the current locale,
346 std::env::set_var("LC_ALL", "en_US.UTF-8");
347 std::env::set_var("ZED_TERM", "true");
348
349 let scrolling_history = if task.is_some() {
350 // Tasks like `cargo build --all` may produce a lot of output, ergo allow maximum scrolling.
351 // After the task finishes, we do not allow appending to that terminal, so small tasks output should not
352 // cause excessive memory usage over time.
353 MAX_SCROLL_HISTORY_LINES
354 } else {
355 max_scroll_history_lines
356 .unwrap_or(DEFAULT_SCROLL_HISTORY_LINES)
357 .min(MAX_SCROLL_HISTORY_LINES)
358 };
359 let config = Config {
360 scrolling_history,
361 ..Config::default()
362 };
363
364 //Spawn a task so the Alacritty EventLoop can communicate with us in a view context
365 //TODO: Remove with a bounded sender which can be dispatched on &self
366 let (events_tx, events_rx) = unbounded();
367 //Set up the terminal...
368 let mut term = Term::new(
369 config,
370 &TerminalSize::default(),
371 ZedListener(events_tx.clone()),
372 );
373
374 //Start off blinking if we need to
375 if let Some(TerminalBlink::On) = blink_settings {
376 term.set_private_mode(PrivateMode::Named(NamedPrivateMode::BlinkingCursor));
377 }
378
379 //Alacritty defaults to alternate scrolling being on, so we just need to turn it off.
380 if let AlternateScroll::Off = alternate_scroll {
381 term.unset_private_mode(PrivateMode::Named(NamedPrivateMode::AlternateScroll));
382 }
383
384 let term = Arc::new(FairMutex::new(term));
385
386 //Setup the pty...
387 let pty = match tty::new(
388 &pty_options,
389 TerminalSize::default().into(),
390 window.window_id().as_u64(),
391 ) {
392 Ok(pty) => pty,
393 Err(error) => {
394 bail!(TerminalError {
395 directory: working_directory,
396 shell,
397 source: error,
398 });
399 }
400 };
401
402 let pty_info = PtyProcessInfo::new(&pty);
403
404 //And connect them together
405 let event_loop = EventLoop::new(
406 term.clone(),
407 ZedListener(events_tx.clone()),
408 pty,
409 pty_options.hold,
410 false,
411 )?;
412
413 //Kick things off
414 let pty_tx = event_loop.channel();
415 let _io_thread = event_loop.spawn(); // DANGER
416
417 let url_regex = RegexSearch::new(r#"(ipfs:|ipns:|magnet:|mailto:|gemini://|gopher://|https://|http://|news:|file://|git://|ssh:|ftp://)[^\u{0000}-\u{001F}\u{007F}-\u{009F}<>"\s{-}\^⟨⟩`]+"#).unwrap();
418 let word_regex = RegexSearch::new(r#"[\$\+\w.\[\]:/@\-~]+"#).unwrap();
419
420 let terminal = Terminal {
421 task,
422 pty_tx: Notifier(pty_tx),
423 completion_tx,
424 term,
425 events: VecDeque::with_capacity(10), //Should never get this high.
426 last_content: Default::default(),
427 last_mouse: None,
428 matches: Vec::new(),
429 selection_head: None,
430 pty_info,
431 breadcrumb_text: String::new(),
432 scroll_px: px(0.),
433 last_mouse_position: None,
434 next_link_id: 0,
435 selection_phase: SelectionPhase::Ended,
436 cmd_pressed: false,
437 hovered_word: false,
438 url_regex,
439 word_regex,
440 };
441
442 Ok(TerminalBuilder {
443 terminal,
444 events_rx,
445 })
446 }
447
448 pub fn subscribe(mut self, cx: &mut ModelContext<Terminal>) -> Terminal {
449 //Event loop
450 cx.spawn(|terminal, mut cx| async move {
451 while let Some(event) = self.events_rx.next().await {
452 terminal.update(&mut cx, |terminal, cx| {
453 //Process the first event immediately for lowered latency
454 terminal.process_event(&event, cx);
455 })?;
456
457 'outer: loop {
458 let mut events = Vec::new();
459 let mut timer = cx
460 .background_executor()
461 .timer(Duration::from_millis(4))
462 .fuse();
463 let mut wakeup = false;
464 loop {
465 futures::select_biased! {
466 _ = timer => break,
467 event = self.events_rx.next() => {
468 if let Some(event) = event {
469 if matches!(event, AlacTermEvent::Wakeup) {
470 wakeup = true;
471 } else {
472 events.push(event);
473 }
474
475 if events.len() > 100 {
476 break;
477 }
478 } else {
479 break;
480 }
481 },
482 }
483 }
484
485 if events.is_empty() && !wakeup {
486 smol::future::yield_now().await;
487 break 'outer;
488 }
489
490 terminal.update(&mut cx, |this, cx| {
491 if wakeup {
492 this.process_event(&AlacTermEvent::Wakeup, cx);
493 }
494
495 for event in events {
496 this.process_event(&event, cx);
497 }
498 })?;
499 smol::future::yield_now().await;
500 }
501 }
502
503 anyhow::Ok(())
504 })
505 .detach();
506
507 self.terminal
508 }
509}
510
511#[derive(Debug, Clone, Deserialize, Serialize)]
512pub struct IndexedCell {
513 pub point: AlacPoint,
514 pub cell: Cell,
515}
516
517impl Deref for IndexedCell {
518 type Target = Cell;
519
520 #[inline]
521 fn deref(&self) -> &Cell {
522 &self.cell
523 }
524}
525
526// TODO: Un-pub
527#[derive(Clone)]
528pub struct TerminalContent {
529 pub cells: Vec<IndexedCell>,
530 pub mode: TermMode,
531 pub display_offset: usize,
532 pub selection_text: Option<String>,
533 pub selection: Option<SelectionRange>,
534 pub cursor: RenderableCursor,
535 pub cursor_char: char,
536 pub size: TerminalSize,
537 pub last_hovered_word: Option<HoveredWord>,
538}
539
540#[derive(Clone)]
541pub struct HoveredWord {
542 pub word: String,
543 pub word_match: RangeInclusive<AlacPoint>,
544 pub id: usize,
545}
546
547impl Default for TerminalContent {
548 fn default() -> Self {
549 TerminalContent {
550 cells: Default::default(),
551 mode: Default::default(),
552 display_offset: Default::default(),
553 selection_text: Default::default(),
554 selection: Default::default(),
555 cursor: RenderableCursor {
556 shape: alacritty_terminal::vte::ansi::CursorShape::Block,
557 point: AlacPoint::new(Line(0), Column(0)),
558 },
559 cursor_char: Default::default(),
560 size: Default::default(),
561 last_hovered_word: None,
562 }
563 }
564}
565
566#[derive(PartialEq, Eq)]
567pub enum SelectionPhase {
568 Selecting,
569 Ended,
570}
571
572pub struct Terminal {
573 pty_tx: Notifier,
574 completion_tx: Sender<()>,
575 term: Arc<FairMutex<Term<ZedListener>>>,
576 events: VecDeque<InternalEvent>,
577 /// This is only used for mouse mode cell change detection
578 last_mouse: Option<(AlacPoint, AlacDirection)>,
579 /// This is only used for terminal hovered word checking
580 last_mouse_position: Option<Point<Pixels>>,
581 pub matches: Vec<RangeInclusive<AlacPoint>>,
582 pub last_content: TerminalContent,
583 pub selection_head: Option<AlacPoint>,
584 pub breadcrumb_text: String,
585 pub pty_info: PtyProcessInfo,
586 scroll_px: Pixels,
587 next_link_id: usize,
588 selection_phase: SelectionPhase,
589 cmd_pressed: bool,
590 hovered_word: bool,
591 url_regex: RegexSearch,
592 word_regex: RegexSearch,
593 task: Option<TaskState>,
594}
595
596pub struct TaskState {
597 pub id: TaskId,
598 pub label: String,
599 pub completed: bool,
600 pub completion_rx: Receiver<()>,
601}
602
603impl Terminal {
604 fn process_event(&mut self, event: &AlacTermEvent, cx: &mut ModelContext<Self>) {
605 match event {
606 AlacTermEvent::Title(title) => {
607 self.breadcrumb_text = title.to_string();
608 cx.emit(Event::BreadcrumbsChanged);
609 }
610 AlacTermEvent::ResetTitle => {
611 self.breadcrumb_text = String::new();
612 cx.emit(Event::BreadcrumbsChanged);
613 }
614 AlacTermEvent::ClipboardStore(_, data) => {
615 cx.write_to_clipboard(ClipboardItem::new(data.to_string()))
616 }
617 AlacTermEvent::ClipboardLoad(_, format) => self.write_to_pty(format(
618 &cx.read_from_clipboard()
619 .map(|ci| ci.text().to_string())
620 .unwrap_or_else(|| "".to_string()),
621 )),
622 AlacTermEvent::PtyWrite(out) => self.write_to_pty(out.clone()),
623 AlacTermEvent::TextAreaSizeRequest(format) => {
624 self.write_to_pty(format(self.last_content.size.into()))
625 }
626 AlacTermEvent::CursorBlinkingChange => {
627 cx.emit(Event::BlinkChanged);
628 }
629 AlacTermEvent::Bell => {
630 cx.emit(Event::Bell);
631 }
632 AlacTermEvent::Exit => match &mut self.task {
633 Some(task) => {
634 task.completed = true;
635 self.completion_tx.try_send(()).ok();
636 }
637 None => cx.emit(Event::CloseTerminal),
638 },
639 AlacTermEvent::MouseCursorDirty => {
640 //NOOP, Handled in render
641 }
642 AlacTermEvent::Wakeup => {
643 cx.emit(Event::Wakeup);
644
645 if self.pty_info.has_changed() {
646 cx.emit(Event::TitleChanged);
647 }
648 }
649 AlacTermEvent::ColorRequest(idx, fun_ptr) => {
650 self.events
651 .push_back(InternalEvent::ColorRequest(*idx, fun_ptr.clone()));
652 }
653 }
654 }
655
656 pub fn selection_started(&self) -> bool {
657 self.selection_phase == SelectionPhase::Selecting
658 }
659
660 pub fn get_cwd(&self) -> Option<PathBuf> {
661 self.pty_info.current.as_ref().map(|info| info.cwd.clone())
662 }
663
664 ///Takes events from Alacritty and translates them to behavior on this view
665 fn process_terminal_event(
666 &mut self,
667 event: &InternalEvent,
668 term: &mut Term<ZedListener>,
669 cx: &mut ModelContext<Self>,
670 ) {
671 match event {
672 InternalEvent::ColorRequest(index, format) => {
673 let color = term.colors()[*index].unwrap_or_else(|| {
674 to_alac_rgb(get_color_at_index(*index, cx.theme().as_ref()))
675 });
676 self.write_to_pty(format(color))
677 }
678 InternalEvent::Resize(mut new_size) => {
679 new_size.size.height = cmp::max(new_size.line_height, new_size.height());
680 new_size.size.width = cmp::max(new_size.cell_width, new_size.width());
681
682 self.last_content.size = new_size;
683
684 self.pty_tx.0.send(Msg::Resize(new_size.into())).ok();
685
686 term.resize(new_size);
687 }
688 InternalEvent::Clear => {
689 // Clear back buffer
690 term.clear_screen(ClearMode::Saved);
691
692 let cursor = term.grid().cursor.point;
693
694 // Clear the lines above
695 term.grid_mut().reset_region(..cursor.line);
696
697 // Copy the current line up
698 let line = term.grid()[cursor.line][..Column(term.grid().columns())]
699 .iter()
700 .cloned()
701 .enumerate()
702 .collect::<Vec<(usize, Cell)>>();
703
704 for (i, cell) in line {
705 term.grid_mut()[Line(0)][Column(i)] = cell;
706 }
707
708 // Reset the cursor
709 term.grid_mut().cursor.point =
710 AlacPoint::new(Line(0), term.grid_mut().cursor.point.column);
711 let new_cursor = term.grid().cursor.point;
712
713 // Clear the lines below the new cursor
714 if (new_cursor.line.0 as usize) < term.screen_lines() - 1 {
715 term.grid_mut().reset_region((new_cursor.line + 1)..);
716 }
717
718 cx.emit(Event::Wakeup);
719 }
720 InternalEvent::Scroll(scroll) => {
721 term.scroll_display(*scroll);
722 self.refresh_hovered_word();
723 }
724 InternalEvent::SetSelection(selection) => {
725 term.selection = selection.as_ref().map(|(sel, _)| sel.clone());
726
727 if let Some((_, head)) = selection {
728 self.selection_head = Some(*head);
729 }
730 cx.emit(Event::SelectionsChanged)
731 }
732 InternalEvent::UpdateSelection(position) => {
733 if let Some(mut selection) = term.selection.take() {
734 let (point, side) = grid_point_and_side(
735 *position,
736 self.last_content.size,
737 term.grid().display_offset(),
738 );
739
740 selection.update(point, side);
741 term.selection = Some(selection);
742
743 self.selection_head = Some(point);
744 cx.emit(Event::SelectionsChanged)
745 }
746 }
747
748 InternalEvent::Copy => {
749 if let Some(txt) = term.selection_to_string() {
750 cx.write_to_clipboard(ClipboardItem::new(txt))
751 }
752 }
753 InternalEvent::ScrollToAlacPoint(point) => {
754 term.scroll_to_point(*point);
755 self.refresh_hovered_word();
756 }
757 InternalEvent::FindHyperlink(position, open) => {
758 let prev_hovered_word = self.last_content.last_hovered_word.take();
759
760 let point = grid_point(
761 *position,
762 self.last_content.size,
763 term.grid().display_offset(),
764 )
765 .grid_clamp(term, Boundary::Grid);
766
767 let link = term.grid().index(point).hyperlink();
768 let found_word = if link.is_some() {
769 let mut min_index = point;
770 loop {
771 let new_min_index = min_index.sub(term, Boundary::Cursor, 1);
772 if new_min_index == min_index {
773 break;
774 } else if term.grid().index(new_min_index).hyperlink() != link {
775 break;
776 } else {
777 min_index = new_min_index
778 }
779 }
780
781 let mut max_index = point;
782 loop {
783 let new_max_index = max_index.add(term, Boundary::Cursor, 1);
784 if new_max_index == max_index {
785 break;
786 } else if term.grid().index(new_max_index).hyperlink() != link {
787 break;
788 } else {
789 max_index = new_max_index
790 }
791 }
792
793 let url = link.unwrap().uri().to_owned();
794 let url_match = min_index..=max_index;
795
796 Some((url, true, url_match))
797 } else if let Some(word_match) = regex_match_at(term, point, &mut self.word_regex) {
798 let maybe_url_or_path =
799 term.bounds_to_string(*word_match.start(), *word_match.end());
800 let original_match = word_match.clone();
801 let (sanitized_match, sanitized_word) =
802 if maybe_url_or_path.starts_with('[') && maybe_url_or_path.ends_with(']') {
803 (
804 Match::new(
805 word_match.start().add(term, Boundary::Cursor, 1),
806 word_match.end().sub(term, Boundary::Cursor, 1),
807 ),
808 maybe_url_or_path[1..maybe_url_or_path.len() - 1].to_owned(),
809 )
810 } else {
811 (word_match, maybe_url_or_path)
812 };
813
814 let is_url = match regex_match_at(term, point, &mut self.url_regex) {
815 Some(url_match) => {
816 // `]` is a valid symbol in the `file://` URL, so the regex match will include it
817 // consider that when ensuring that the URL match is the same as the original word
818 if sanitized_match != original_match {
819 url_match.start() == sanitized_match.start()
820 && url_match.end() == original_match.end()
821 } else {
822 url_match == sanitized_match
823 }
824 }
825 None => false,
826 };
827 Some((sanitized_word, is_url, sanitized_match))
828 } else {
829 None
830 };
831
832 match found_word {
833 Some((maybe_url_or_path, is_url, url_match)) => {
834 if *open {
835 let target = if is_url {
836 MaybeNavigationTarget::Url(maybe_url_or_path)
837 } else {
838 MaybeNavigationTarget::PathLike(PathLikeTarget {
839 maybe_path: maybe_url_or_path,
840 terminal_dir: self.get_cwd(),
841 })
842 };
843 cx.emit(Event::Open(target));
844 } else {
845 self.update_selected_word(
846 prev_hovered_word,
847 url_match,
848 maybe_url_or_path,
849 is_url,
850 cx,
851 );
852 }
853 self.hovered_word = true;
854 }
855 None => {
856 if self.hovered_word {
857 cx.emit(Event::NewNavigationTarget(None));
858 }
859 self.hovered_word = false;
860 }
861 }
862 }
863 }
864 }
865
866 fn update_selected_word(
867 &mut self,
868 prev_word: Option<HoveredWord>,
869 word_match: RangeInclusive<AlacPoint>,
870 word: String,
871 is_url: bool,
872 cx: &mut ModelContext<Self>,
873 ) {
874 if let Some(prev_word) = prev_word {
875 if prev_word.word == word && prev_word.word_match == word_match {
876 self.last_content.last_hovered_word = Some(HoveredWord {
877 word,
878 word_match,
879 id: prev_word.id,
880 });
881 return;
882 }
883 }
884
885 self.last_content.last_hovered_word = Some(HoveredWord {
886 word: word.clone(),
887 word_match,
888 id: self.next_link_id(),
889 });
890 let navigation_target = if is_url {
891 MaybeNavigationTarget::Url(word)
892 } else {
893 MaybeNavigationTarget::PathLike(PathLikeTarget {
894 maybe_path: word,
895 terminal_dir: self.get_cwd(),
896 })
897 };
898 cx.emit(Event::NewNavigationTarget(Some(navigation_target)));
899 }
900
901 fn next_link_id(&mut self) -> usize {
902 let res = self.next_link_id;
903 self.next_link_id = self.next_link_id.wrapping_add(1);
904 res
905 }
906
907 pub fn last_content(&self) -> &TerminalContent {
908 &self.last_content
909 }
910
911 //To test:
912 //- Activate match on terminal (scrolling and selection)
913 //- Editor search snapping behavior
914
915 pub fn activate_match(&mut self, index: usize) {
916 if let Some(search_match) = self.matches.get(index).cloned() {
917 self.set_selection(Some((make_selection(&search_match), *search_match.end())));
918
919 self.events
920 .push_back(InternalEvent::ScrollToAlacPoint(*search_match.start()));
921 }
922 }
923
924 pub fn select_matches(&mut self, matches: Vec<RangeInclusive<AlacPoint>>) {
925 let matches_to_select = self
926 .matches
927 .iter()
928 .filter(|self_match| matches.contains(self_match))
929 .cloned()
930 .collect::<Vec<_>>();
931 for match_to_select in matches_to_select {
932 self.set_selection(Some((
933 make_selection(&match_to_select),
934 *match_to_select.end(),
935 )));
936 }
937 }
938
939 pub fn select_all(&mut self) {
940 let term = self.term.lock();
941 let start = AlacPoint::new(term.topmost_line(), Column(0));
942 let end = AlacPoint::new(term.bottommost_line(), term.last_column());
943 drop(term);
944 self.set_selection(Some((make_selection(&(start..=end)), end)));
945 }
946
947 fn set_selection(&mut self, selection: Option<(Selection, AlacPoint)>) {
948 self.events
949 .push_back(InternalEvent::SetSelection(selection));
950 }
951
952 pub fn copy(&mut self) {
953 self.events.push_back(InternalEvent::Copy);
954 }
955
956 pub fn clear(&mut self) {
957 self.events.push_back(InternalEvent::Clear)
958 }
959
960 ///Resize the terminal and the PTY.
961 pub fn set_size(&mut self, new_size: TerminalSize) {
962 self.events.push_back(InternalEvent::Resize(new_size))
963 }
964
965 ///Write the Input payload to the tty.
966 fn write_to_pty(&self, input: String) {
967 self.pty_tx.notify(input.into_bytes());
968 }
969
970 fn write_bytes_to_pty(&self, input: Vec<u8>) {
971 self.pty_tx.notify(input);
972 }
973
974 pub fn input(&mut self, input: String) {
975 self.events
976 .push_back(InternalEvent::Scroll(AlacScroll::Bottom));
977 self.events.push_back(InternalEvent::SetSelection(None));
978
979 self.write_to_pty(input);
980 }
981
982 pub fn input_bytes(&mut self, input: Vec<u8>) {
983 self.events
984 .push_back(InternalEvent::Scroll(AlacScroll::Bottom));
985 self.events.push_back(InternalEvent::SetSelection(None));
986
987 self.write_bytes_to_pty(input);
988 }
989
990 pub fn try_keystroke(&mut self, keystroke: &Keystroke, alt_is_meta: bool) -> bool {
991 let esc = to_esc_str(keystroke, &self.last_content.mode, alt_is_meta);
992 if let Some(esc) = esc {
993 self.input(esc);
994 true
995 } else {
996 false
997 }
998 }
999
1000 pub fn try_modifiers_change(&mut self, modifiers: &Modifiers) -> bool {
1001 let changed = self.cmd_pressed != modifiers.command;
1002 if !self.cmd_pressed && modifiers.command {
1003 self.refresh_hovered_word();
1004 }
1005 self.cmd_pressed = modifiers.command;
1006 changed
1007 }
1008
1009 ///Paste text into the terminal
1010 pub fn paste(&mut self, text: &str) {
1011 let paste_text = if self.last_content.mode.contains(TermMode::BRACKETED_PASTE) {
1012 format!("{}{}{}", "\x1b[200~", text.replace('\x1b', ""), "\x1b[201~")
1013 } else {
1014 text.replace("\r\n", "\r").replace('\n', "\r")
1015 };
1016
1017 self.input(paste_text);
1018 }
1019
1020 pub fn sync(&mut self, cx: &mut ModelContext<Self>) {
1021 let term = self.term.clone();
1022 let mut terminal = term.lock_unfair();
1023 //Note that the ordering of events matters for event processing
1024 while let Some(e) = self.events.pop_front() {
1025 self.process_terminal_event(&e, &mut terminal, cx)
1026 }
1027
1028 self.last_content = Self::make_content(&terminal, &self.last_content);
1029 }
1030
1031 fn make_content(term: &Term<ZedListener>, last_content: &TerminalContent) -> TerminalContent {
1032 let content = term.renderable_content();
1033 TerminalContent {
1034 cells: content
1035 .display_iter
1036 //TODO: Add this once there's a way to retain empty lines
1037 // .filter(|ic| {
1038 // !ic.flags.contains(Flags::HIDDEN)
1039 // && !(ic.bg == Named(NamedColor::Background)
1040 // && ic.c == ' '
1041 // && !ic.flags.contains(Flags::INVERSE))
1042 // })
1043 .map(|ic| IndexedCell {
1044 point: ic.point,
1045 cell: ic.cell.clone(),
1046 })
1047 .collect::<Vec<IndexedCell>>(),
1048 mode: content.mode,
1049 display_offset: content.display_offset,
1050 selection_text: term.selection_to_string(),
1051 selection: content.selection,
1052 cursor: content.cursor,
1053 cursor_char: term.grid()[content.cursor.point].c,
1054 size: last_content.size,
1055 last_hovered_word: last_content.last_hovered_word.clone(),
1056 }
1057 }
1058
1059 pub fn focus_in(&self) {
1060 if self.last_content.mode.contains(TermMode::FOCUS_IN_OUT) {
1061 self.write_to_pty("\x1b[I".to_string());
1062 }
1063 }
1064
1065 pub fn focus_out(&mut self) {
1066 self.last_mouse_position = None;
1067 if self.last_content.mode.contains(TermMode::FOCUS_IN_OUT) {
1068 self.write_to_pty("\x1b[O".to_string());
1069 }
1070 }
1071
1072 pub fn mouse_changed(&mut self, point: AlacPoint, side: AlacDirection) -> bool {
1073 match self.last_mouse {
1074 Some((old_point, old_side)) => {
1075 if old_point == point && old_side == side {
1076 false
1077 } else {
1078 self.last_mouse = Some((point, side));
1079 true
1080 }
1081 }
1082 None => {
1083 self.last_mouse = Some((point, side));
1084 true
1085 }
1086 }
1087 }
1088
1089 pub fn mouse_mode(&self, shift: bool) -> bool {
1090 self.last_content.mode.intersects(TermMode::MOUSE_MODE) && !shift
1091 }
1092
1093 pub fn mouse_move(&mut self, e: &MouseMoveEvent, origin: Point<Pixels>) {
1094 let position = e.position - origin;
1095 self.last_mouse_position = Some(position);
1096 if self.mouse_mode(e.modifiers.shift) {
1097 let (point, side) = grid_point_and_side(
1098 position,
1099 self.last_content.size,
1100 self.last_content.display_offset,
1101 );
1102
1103 if self.mouse_changed(point, side) {
1104 if let Some(bytes) = mouse_moved_report(point, e, self.last_content.mode) {
1105 self.pty_tx.notify(bytes);
1106 }
1107 }
1108 } else if self.cmd_pressed {
1109 self.word_from_position(Some(position));
1110 }
1111 }
1112
1113 fn word_from_position(&mut self, position: Option<Point<Pixels>>) {
1114 if self.selection_phase == SelectionPhase::Selecting {
1115 self.last_content.last_hovered_word = None;
1116 } else if let Some(position) = position {
1117 self.events
1118 .push_back(InternalEvent::FindHyperlink(position, false));
1119 }
1120 }
1121
1122 pub fn mouse_drag(
1123 &mut self,
1124 e: &MouseMoveEvent,
1125 origin: Point<Pixels>,
1126 region: Bounds<Pixels>,
1127 ) {
1128 let position = e.position - origin;
1129 self.last_mouse_position = Some(position);
1130
1131 if !self.mouse_mode(e.modifiers.shift) {
1132 self.selection_phase = SelectionPhase::Selecting;
1133 // Alacritty has the same ordering, of first updating the selection
1134 // then scrolling 15ms later
1135 self.events
1136 .push_back(InternalEvent::UpdateSelection(position));
1137
1138 // Doesn't make sense to scroll the alt screen
1139 if !self.last_content.mode.contains(TermMode::ALT_SCREEN) {
1140 let scroll_delta = match self.drag_line_delta(e, region) {
1141 Some(value) => value,
1142 None => return,
1143 };
1144
1145 let scroll_lines = (scroll_delta / self.last_content.size.line_height) as i32;
1146
1147 self.events
1148 .push_back(InternalEvent::Scroll(AlacScroll::Delta(scroll_lines)));
1149 }
1150 }
1151 }
1152
1153 fn drag_line_delta(&mut self, e: &MouseMoveEvent, region: Bounds<Pixels>) -> Option<Pixels> {
1154 //TODO: Why do these need to be doubled? Probably the same problem that the IME has
1155 let top = region.origin.y + (self.last_content.size.line_height * 2.);
1156 let bottom = region.lower_left().y - (self.last_content.size.line_height * 2.);
1157 let scroll_delta = if e.position.y < top {
1158 (top - e.position.y).pow(1.1)
1159 } else if e.position.y > bottom {
1160 -((e.position.y - bottom).pow(1.1))
1161 } else {
1162 return None; //Nothing to do
1163 };
1164 Some(scroll_delta)
1165 }
1166
1167 pub fn mouse_down(&mut self, e: &MouseDownEvent, origin: Point<Pixels>) {
1168 let position = e.position - origin;
1169 let point = grid_point(
1170 position,
1171 self.last_content.size,
1172 self.last_content.display_offset,
1173 );
1174
1175 if self.mouse_mode(e.modifiers.shift) {
1176 if let Some(bytes) =
1177 mouse_button_report(point, e.button, e.modifiers, true, self.last_content.mode)
1178 {
1179 self.pty_tx.notify(bytes);
1180 }
1181 } else if e.button == MouseButton::Left {
1182 let position = e.position - origin;
1183 let (point, side) = grid_point_and_side(
1184 position,
1185 self.last_content.size,
1186 self.last_content.display_offset,
1187 );
1188
1189 let selection_type = match e.click_count {
1190 0 => return, //This is a release
1191 1 => Some(SelectionType::Simple),
1192 2 => Some(SelectionType::Semantic),
1193 3 => Some(SelectionType::Lines),
1194 _ => None,
1195 };
1196
1197 let selection =
1198 selection_type.map(|selection_type| Selection::new(selection_type, point, side));
1199
1200 if let Some(sel) = selection {
1201 self.events
1202 .push_back(InternalEvent::SetSelection(Some((sel, point))));
1203 }
1204 }
1205 }
1206
1207 pub fn mouse_up(
1208 &mut self,
1209 e: &MouseUpEvent,
1210 origin: Point<Pixels>,
1211 cx: &mut ModelContext<Self>,
1212 ) {
1213 let setting = TerminalSettings::get_global(cx);
1214
1215 let position = e.position - origin;
1216 if self.mouse_mode(e.modifiers.shift) {
1217 let point = grid_point(
1218 position,
1219 self.last_content.size,
1220 self.last_content.display_offset,
1221 );
1222
1223 if let Some(bytes) =
1224 mouse_button_report(point, e.button, e.modifiers, false, self.last_content.mode)
1225 {
1226 self.pty_tx.notify(bytes);
1227 }
1228 } else {
1229 if e.button == MouseButton::Left && setting.copy_on_select {
1230 self.copy();
1231 }
1232
1233 //Hyperlinks
1234 if self.selection_phase == SelectionPhase::Ended {
1235 let mouse_cell_index = content_index_for_mouse(position, &self.last_content.size);
1236 if let Some(link) = self.last_content.cells[mouse_cell_index].hyperlink() {
1237 cx.open_url(link.uri());
1238 } else if self.cmd_pressed {
1239 self.events
1240 .push_back(InternalEvent::FindHyperlink(position, true));
1241 }
1242 }
1243 }
1244
1245 self.selection_phase = SelectionPhase::Ended;
1246 self.last_mouse = None;
1247 }
1248
1249 ///Scroll the terminal
1250 pub fn scroll_wheel(&mut self, e: &ScrollWheelEvent, origin: Point<Pixels>) {
1251 let mouse_mode = self.mouse_mode(e.shift);
1252
1253 if let Some(scroll_lines) = self.determine_scroll_lines(e, mouse_mode) {
1254 if mouse_mode {
1255 let point = grid_point(
1256 e.position - origin,
1257 self.last_content.size,
1258 self.last_content.display_offset,
1259 );
1260
1261 if let Some(scrolls) = scroll_report(point, scroll_lines, e, self.last_content.mode)
1262 {
1263 for scroll in scrolls {
1264 self.pty_tx.notify(scroll);
1265 }
1266 };
1267 } else if self
1268 .last_content
1269 .mode
1270 .contains(TermMode::ALT_SCREEN | TermMode::ALTERNATE_SCROLL)
1271 && !e.shift
1272 {
1273 self.pty_tx.notify(alt_scroll(scroll_lines))
1274 } else {
1275 if scroll_lines != 0 {
1276 let scroll = AlacScroll::Delta(scroll_lines);
1277
1278 self.events.push_back(InternalEvent::Scroll(scroll));
1279 }
1280 }
1281 }
1282 }
1283
1284 fn refresh_hovered_word(&mut self) {
1285 self.word_from_position(self.last_mouse_position);
1286 }
1287
1288 fn determine_scroll_lines(&mut self, e: &ScrollWheelEvent, mouse_mode: bool) -> Option<i32> {
1289 let scroll_multiplier = if mouse_mode { 1. } else { SCROLL_MULTIPLIER };
1290 let line_height = self.last_content.size.line_height;
1291 match e.touch_phase {
1292 /* Reset scroll state on started */
1293 TouchPhase::Started => {
1294 self.scroll_px = px(0.);
1295 None
1296 }
1297 /* Calculate the appropriate scroll lines */
1298 TouchPhase::Moved => {
1299 let old_offset = (self.scroll_px / line_height) as i32;
1300
1301 self.scroll_px += e.delta.pixel_delta(line_height).y * scroll_multiplier;
1302
1303 let new_offset = (self.scroll_px / line_height) as i32;
1304
1305 // Whenever we hit the edges, reset our stored scroll to 0
1306 // so we can respond to changes in direction quickly
1307 self.scroll_px %= self.last_content.size.height();
1308
1309 Some(new_offset - old_offset)
1310 }
1311 TouchPhase::Ended => None,
1312 }
1313 }
1314
1315 pub fn find_matches(
1316 &mut self,
1317 mut searcher: RegexSearch,
1318 cx: &mut ModelContext<Self>,
1319 ) -> Task<Vec<RangeInclusive<AlacPoint>>> {
1320 let term = self.term.clone();
1321 cx.background_executor().spawn(async move {
1322 let term = term.lock();
1323
1324 all_search_matches(&term, &mut searcher).collect()
1325 })
1326 }
1327
1328 pub fn title(&self, truncate: bool) -> String {
1329 const MAX_CHARS: usize = 25;
1330 match &self.task {
1331 Some(task_state) => {
1332 if truncate {
1333 truncate_and_trailoff(&task_state.label, MAX_CHARS)
1334 } else {
1335 task_state.label.clone()
1336 }
1337 }
1338 None => self
1339 .pty_info
1340 .current
1341 .as_ref()
1342 .map(|fpi| {
1343 let process_file = fpi
1344 .cwd
1345 .file_name()
1346 .map(|name| name.to_string_lossy().to_string())
1347 .unwrap_or_default();
1348
1349 let argv = fpi.argv.clone();
1350 let process_name = format!(
1351 "{}{}",
1352 fpi.name,
1353 if argv.len() >= 1 {
1354 format!(" {}", (argv[1..]).join(" "))
1355 } else {
1356 "".to_string()
1357 }
1358 );
1359 let (process_file, process_name) = if truncate {
1360 (
1361 truncate_and_trailoff(&process_file, MAX_CHARS),
1362 truncate_and_trailoff(&process_name, MAX_CHARS),
1363 )
1364 } else {
1365 (process_file, process_name)
1366 };
1367 format!("{process_file} — {process_name}")
1368 })
1369 .unwrap_or_else(|| "Terminal".to_string()),
1370 }
1371 }
1372
1373 pub fn can_navigate_to_selected_word(&self) -> bool {
1374 self.cmd_pressed && self.hovered_word
1375 }
1376
1377 pub fn task(&self) -> Option<&TaskState> {
1378 self.task.as_ref()
1379 }
1380
1381 pub fn wait_for_completed_task(&self, cx: &mut AppContext) -> Task<()> {
1382 match self.task() {
1383 Some(task) => {
1384 if task.completed {
1385 Task::ready(())
1386 } else {
1387 let mut completion_receiver = task.completion_rx.clone();
1388 cx.spawn(|_| async move {
1389 completion_receiver.next().await;
1390 })
1391 }
1392 }
1393 None => Task::ready(()),
1394 }
1395 }
1396}
1397
1398impl Drop for Terminal {
1399 fn drop(&mut self) {
1400 self.pty_tx.0.send(Msg::Shutdown).ok();
1401 }
1402}
1403
1404impl EventEmitter<Event> for Terminal {}
1405
1406/// Based on alacritty/src/display/hint.rs > regex_match_at
1407/// Retrieve the match, if the specified point is inside the content matching the regex.
1408fn regex_match_at<T>(term: &Term<T>, point: AlacPoint, regex: &mut RegexSearch) -> Option<Match> {
1409 visible_regex_match_iter(term, regex).find(|rm| rm.contains(&point))
1410}
1411
1412/// Copied from alacritty/src/display/hint.rs:
1413/// Iterate over all visible regex matches.
1414pub fn visible_regex_match_iter<'a, T>(
1415 term: &'a Term<T>,
1416 regex: &'a mut RegexSearch,
1417) -> impl Iterator<Item = Match> + 'a {
1418 let viewport_start = Line(-(term.grid().display_offset() as i32));
1419 let viewport_end = viewport_start + term.bottommost_line();
1420 let mut start = term.line_search_left(AlacPoint::new(viewport_start, Column(0)));
1421 let mut end = term.line_search_right(AlacPoint::new(viewport_end, Column(0)));
1422 start.line = start.line.max(viewport_start - MAX_SEARCH_LINES);
1423 end.line = end.line.min(viewport_end + MAX_SEARCH_LINES);
1424
1425 RegexIter::new(start, end, AlacDirection::Right, term, regex)
1426 .skip_while(move |rm| rm.end().line < viewport_start)
1427 .take_while(move |rm| rm.start().line <= viewport_end)
1428}
1429
1430fn make_selection(range: &RangeInclusive<AlacPoint>) -> Selection {
1431 let mut selection = Selection::new(SelectionType::Simple, *range.start(), AlacDirection::Left);
1432 selection.update(*range.end(), AlacDirection::Right);
1433 selection
1434}
1435
1436fn all_search_matches<'a, T>(
1437 term: &'a Term<T>,
1438 regex: &'a mut RegexSearch,
1439) -> impl Iterator<Item = Match> + 'a {
1440 let start = AlacPoint::new(term.grid().topmost_line(), Column(0));
1441 let end = AlacPoint::new(term.grid().bottommost_line(), term.grid().last_column());
1442 RegexIter::new(start, end, AlacDirection::Right, term, regex)
1443}
1444
1445fn content_index_for_mouse(pos: Point<Pixels>, size: &TerminalSize) -> usize {
1446 let col = (pos.x / size.cell_width()).round() as usize;
1447 let clamped_col = min(col, size.columns() - 1);
1448 let row = (pos.y / size.line_height()).round() as usize;
1449 let clamped_row = min(row, size.screen_lines() - 1);
1450 clamped_row * size.columns() + clamped_col
1451}
1452
1453/// Converts an 8 bit ANSI color to its GPUI equivalent.
1454/// Accepts `usize` for compatibility with the `alacritty::Colors` interface,
1455/// Other than that use case, should only be called with values in the [0,255] range
1456pub fn get_color_at_index(index: usize, theme: &Theme) -> Hsla {
1457 let colors = theme.colors();
1458
1459 match index {
1460 // 0-15 are the same as the named colors above
1461 0 => colors.terminal_ansi_black,
1462 1 => colors.terminal_ansi_red,
1463 2 => colors.terminal_ansi_green,
1464 3 => colors.terminal_ansi_yellow,
1465 4 => colors.terminal_ansi_blue,
1466 5 => colors.terminal_ansi_magenta,
1467 6 => colors.terminal_ansi_cyan,
1468 7 => colors.terminal_ansi_white,
1469 8 => colors.terminal_ansi_bright_black,
1470 9 => colors.terminal_ansi_bright_red,
1471 10 => colors.terminal_ansi_bright_green,
1472 11 => colors.terminal_ansi_bright_yellow,
1473 12 => colors.terminal_ansi_bright_blue,
1474 13 => colors.terminal_ansi_bright_magenta,
1475 14 => colors.terminal_ansi_bright_cyan,
1476 15 => colors.terminal_ansi_bright_white,
1477 // 16-231 are mapped to their RGB colors on a 0-5 range per channel
1478 16..=231 => {
1479 let (r, g, b) = rgb_for_index(index as u8); // Split the index into its ANSI-RGB components
1480 let step = (u8::MAX as f32 / 5.).floor() as u8; // Split the RGB range into 5 chunks, with floor so no overflow
1481 rgba_color(r * step, g * step, b * step) // Map the ANSI-RGB components to an RGB color
1482 }
1483 // 232-255 are a 24 step grayscale from black to white
1484 232..=255 => {
1485 let i = index as u8 - 232; // Align index to 0..24
1486 let step = (u8::MAX as f32 / 24.).floor() as u8; // Split the RGB grayscale values into 24 chunks
1487 rgba_color(i * step, i * step, i * step) // Map the ANSI-grayscale components to the RGB-grayscale
1488 }
1489 // For compatibility with the alacritty::Colors interface
1490 256 => colors.text,
1491 257 => colors.background,
1492 258 => theme.players().local().cursor,
1493 259 => colors.terminal_ansi_dim_black,
1494 260 => colors.terminal_ansi_dim_red,
1495 261 => colors.terminal_ansi_dim_green,
1496 262 => colors.terminal_ansi_dim_yellow,
1497 263 => colors.terminal_ansi_dim_blue,
1498 264 => colors.terminal_ansi_dim_magenta,
1499 265 => colors.terminal_ansi_dim_cyan,
1500 266 => colors.terminal_ansi_dim_white,
1501 267 => colors.terminal_bright_foreground,
1502 268 => colors.terminal_ansi_black, // 'Dim Background', non-standard color
1503
1504 _ => black(),
1505 }
1506}
1507
1508/// Generates the RGB channels in [0, 5] for a given index into the 6x6x6 ANSI color cube.
1509/// See: [8 bit ANSI color](https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit).
1510///
1511/// Wikipedia gives a formula for calculating the index for a given color:
1512///
1513/// ```
1514/// index = 16 + 36 × r + 6 × g + b (0 ≤ r, g, b ≤ 5)
1515/// ```
1516///
1517/// This function does the reverse, calculating the `r`, `g`, and `b` components from a given index.
1518fn rgb_for_index(i: u8) -> (u8, u8, u8) {
1519 debug_assert!((16..=231).contains(&i));
1520 let i = i - 16;
1521 let r = (i - (i % 36)) / 36;
1522 let g = ((i % 36) - (i % 6)) / 6;
1523 let b = (i % 36) % 6;
1524 (r, g, b)
1525}
1526
1527pub fn rgba_color(r: u8, g: u8, b: u8) -> Hsla {
1528 Rgba {
1529 r: (r as f32 / 255.),
1530 g: (g as f32 / 255.),
1531 b: (b as f32 / 255.),
1532 a: 1.,
1533 }
1534 .into()
1535}
1536
1537#[cfg(test)]
1538mod tests {
1539 use alacritty_terminal::{
1540 index::{Column, Line, Point as AlacPoint},
1541 term::cell::Cell,
1542 };
1543 use gpui::{point, size, Pixels};
1544 use rand::{distributions::Alphanumeric, rngs::ThreadRng, thread_rng, Rng};
1545
1546 use crate::{
1547 content_index_for_mouse, rgb_for_index, IndexedCell, TerminalContent, TerminalSize,
1548 };
1549
1550 #[test]
1551 fn test_rgb_for_index() {
1552 // Test every possible value in the color cube.
1553 for i in 16..=231 {
1554 let (r, g, b) = rgb_for_index(i);
1555 assert_eq!(i, 16 + 36 * r + 6 * g + b);
1556 }
1557 }
1558
1559 #[test]
1560 fn test_mouse_to_cell_test() {
1561 let mut rng = thread_rng();
1562 const ITERATIONS: usize = 10;
1563 const PRECISION: usize = 1000;
1564
1565 for _ in 0..ITERATIONS {
1566 let viewport_cells = rng.gen_range(15..20);
1567 let cell_size = rng.gen_range(5 * PRECISION..20 * PRECISION) as f32 / PRECISION as f32;
1568
1569 let size = crate::TerminalSize {
1570 cell_width: Pixels::from(cell_size),
1571 line_height: Pixels::from(cell_size),
1572 size: size(
1573 Pixels::from(cell_size * (viewport_cells as f32)),
1574 Pixels::from(cell_size * (viewport_cells as f32)),
1575 ),
1576 };
1577
1578 let cells = get_cells(size, &mut rng);
1579 let content = convert_cells_to_content(size, &cells);
1580
1581 for row in 0..(viewport_cells - 1) {
1582 let row = row as usize;
1583 for col in 0..(viewport_cells - 1) {
1584 let col = col as usize;
1585
1586 let row_offset = rng.gen_range(0..PRECISION) as f32 / PRECISION as f32;
1587 let col_offset = rng.gen_range(0..PRECISION) as f32 / PRECISION as f32;
1588
1589 let mouse_pos = point(
1590 Pixels::from(col as f32 * cell_size + col_offset),
1591 Pixels::from(row as f32 * cell_size + row_offset),
1592 );
1593
1594 let content_index = content_index_for_mouse(mouse_pos, &content.size);
1595 let mouse_cell = content.cells[content_index].c;
1596 let real_cell = cells[row][col];
1597
1598 assert_eq!(mouse_cell, real_cell);
1599 }
1600 }
1601 }
1602 }
1603
1604 #[test]
1605 fn test_mouse_to_cell_clamp() {
1606 let mut rng = thread_rng();
1607
1608 let size = crate::TerminalSize {
1609 cell_width: Pixels::from(10.),
1610 line_height: Pixels::from(10.),
1611 size: size(Pixels::from(100.), Pixels::from(100.)),
1612 };
1613
1614 let cells = get_cells(size, &mut rng);
1615 let content = convert_cells_to_content(size, &cells);
1616
1617 assert_eq!(
1618 content.cells[content_index_for_mouse(
1619 point(Pixels::from(-10.), Pixels::from(-10.)),
1620 &content.size,
1621 )]
1622 .c,
1623 cells[0][0]
1624 );
1625 assert_eq!(
1626 content.cells[content_index_for_mouse(
1627 point(Pixels::from(1000.), Pixels::from(1000.)),
1628 &content.size,
1629 )]
1630 .c,
1631 cells[9][9]
1632 );
1633 }
1634
1635 fn get_cells(size: TerminalSize, rng: &mut ThreadRng) -> Vec<Vec<char>> {
1636 let mut cells = Vec::new();
1637
1638 for _ in 0..((size.height() / size.line_height()) as usize) {
1639 let mut row_vec = Vec::new();
1640 for _ in 0..((size.width() / size.cell_width()) as usize) {
1641 let cell_char = rng.sample(Alphanumeric) as char;
1642 row_vec.push(cell_char)
1643 }
1644 cells.push(row_vec)
1645 }
1646
1647 cells
1648 }
1649
1650 fn convert_cells_to_content(size: TerminalSize, cells: &Vec<Vec<char>>) -> TerminalContent {
1651 let mut ic = Vec::new();
1652
1653 for row in 0..cells.len() {
1654 for col in 0..cells[row].len() {
1655 let cell_char = cells[row][col];
1656 ic.push(IndexedCell {
1657 point: AlacPoint::new(Line(row as i32), Column(col)),
1658 cell: Cell {
1659 c: cell_char,
1660 ..Default::default()
1661 },
1662 });
1663 }
1664 }
1665
1666 TerminalContent {
1667 cells: ic,
1668 size,
1669 ..Default::default()
1670 }
1671 }
1672}