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