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