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