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