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