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