1pub mod mappings;
2
3pub use alacritty_terminal;
4
5mod pty_info;
6pub mod terminal_settings;
7
8use alacritty_terminal::{
9 event::{Event as AlacTermEvent, EventListener, Notify, WindowSize},
10 event_loop::{EventLoop, Msg, Notifier},
11 grid::{Dimensions, Scroll as AlacScroll},
12 index::{Boundary, Column, Direction as AlacDirection, Line, Point as AlacPoint},
13 selection::{Selection, SelectionRange, SelectionType},
14 sync::FairMutex,
15 term::{
16 cell::Cell,
17 search::{Match, RegexIter, RegexSearch},
18 Config, RenderableCursor, TermMode,
19 },
20 tty::{self, setup_env},
21 vte::ansi::{ClearMode, Handler, NamedPrivateMode, PrivateMode, Rgb},
22 Term,
23};
24use anyhow::{bail, Result};
25
26use futures::{
27 channel::mpsc::{unbounded, UnboundedReceiver, UnboundedSender},
28 FutureExt,
29};
30
31use mappings::mouse::{
32 alt_scroll, grid_point, grid_point_and_side, mouse_button_report, mouse_moved_report,
33 scroll_report,
34};
35
36use collections::{HashMap, VecDeque};
37use futures::StreamExt;
38use pty_info::PtyProcessInfo;
39use serde::{Deserialize, Serialize};
40use settings::Settings;
41use smol::channel::{Receiver, Sender};
42use task::{RevealStrategy, TaskId};
43use terminal_settings::{AlternateScroll, Shell, TerminalBlink, TerminalSettings};
44use theme::{ActiveTheme, Theme};
45use util::truncate_and_trailoff;
46
47use std::{
48 cmp::{self, min},
49 fmt::Display,
50 ops::{Deref, Index, RangeInclusive},
51 path::PathBuf,
52 sync::Arc,
53 time::Duration,
54};
55use thiserror::Error;
56
57use gpui::{
58 actions, black, px, AnyWindowHandle, AppContext, Bounds, ClipboardItem, EventEmitter, Hsla,
59 Keystroke, ModelContext, Modifiers, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent,
60 Pixels, Point, Rgba, ScrollWheelEvent, Size, Task, TouchPhase,
61};
62
63use crate::mappings::{colors::to_alac_rgb, keys::to_esc_str};
64
65actions!(
66 terminal,
67 [Clear, Copy, Paste, ShowCharacterPalette, SearchTest,]
68);
69
70///Scrolling is unbearably sluggish by default. Alacritty supports a configurable
71///Scroll multiplier that is set to 3 by default. This will be removed when I
72///Implement scroll bars.
73#[cfg(target_os = "macos")]
74const SCROLL_MULTIPLIER: f32 = 4.;
75#[cfg(not(target_os = "macos"))]
76const SCROLL_MULTIPLIER: f32 = 1.;
77const MAX_SEARCH_LINES: usize = 100;
78const DEBUG_TERMINAL_WIDTH: Pixels = px(500.);
79const DEBUG_TERMINAL_HEIGHT: Pixels = px(30.);
80const DEBUG_CELL_WIDTH: Pixels = px(5.);
81const DEBUG_LINE_HEIGHT: Pixels = px(5.);
82
83///Upward flowing events, for changing the title and such
84#[derive(Clone, Debug)]
85pub enum Event {
86 TitleChanged,
87 BreadcrumbsChanged,
88 CloseTerminal,
89 Bell,
90 Wakeup,
91 BlinkChanged,
92 SelectionsChanged,
93 NewNavigationTarget(Option<MaybeNavigationTarget>),
94 Open(MaybeNavigationTarget),
95}
96
97#[derive(Clone, Debug)]
98pub struct PathLikeTarget {
99 /// File system path, absolute or relative, existing or not.
100 /// Might have line and column number(s) attached as `file.rs:1:23`
101 pub maybe_path: String,
102 /// Current working directory of the terminal
103 pub terminal_dir: Option<PathBuf>,
104}
105
106/// A string inside terminal, potentially useful as a URI that can be opened.
107#[derive(Clone, Debug)]
108pub enum MaybeNavigationTarget {
109 /// HTTP, git, etc. string determined by the [`URL_REGEX`] regex.
110 Url(String),
111 /// File system path, absolute or relative, existing or not.
112 /// Might have line and column number(s) attached as `file.rs:1:23`
113 PathLike(PathLikeTarget),
114}
115
116#[derive(Clone)]
117enum InternalEvent {
118 ColorRequest(usize, Arc<dyn Fn(Rgb) -> String + Sync + Send + 'static>),
119 Resize(TerminalSize),
120 Clear,
121 // FocusNextMatch,
122 Scroll(AlacScroll),
123 ScrollToAlacPoint(AlacPoint),
124 SetSelection(Option<(Selection, AlacPoint)>),
125 UpdateSelection(Point<Pixels>),
126 // Adjusted mouse position, should open
127 FindHyperlink(Point<Pixels>, bool),
128 Copy,
129}
130
131///A translation struct for Alacritty to communicate with us from their event loop
132#[derive(Clone)]
133pub struct ZedListener(UnboundedSender<AlacTermEvent>);
134
135impl EventListener for ZedListener {
136 fn send_event(&self, event: AlacTermEvent) {
137 self.0.unbounded_send(event).ok();
138 }
139}
140
141pub fn init(cx: &mut AppContext) {
142 TerminalSettings::register(cx);
143}
144
145#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
146pub struct TerminalSize {
147 pub cell_width: Pixels,
148 pub line_height: Pixels,
149 pub size: Size<Pixels>,
150}
151
152impl TerminalSize {
153 pub fn new(line_height: Pixels, cell_width: Pixels, size: Size<Pixels>) -> Self {
154 TerminalSize {
155 cell_width,
156 line_height,
157 size,
158 }
159 }
160
161 pub fn num_lines(&self) -> usize {
162 (self.size.height / self.line_height).floor() as usize
163 }
164
165 pub fn num_columns(&self) -> usize {
166 (self.size.width / self.cell_width).floor() as usize
167 }
168
169 pub fn height(&self) -> Pixels {
170 self.size.height
171 }
172
173 pub fn width(&self) -> Pixels {
174 self.size.width
175 }
176
177 pub fn cell_width(&self) -> Pixels {
178 self.cell_width
179 }
180
181 pub fn line_height(&self) -> Pixels {
182 self.line_height
183 }
184}
185
186impl Default for TerminalSize {
187 fn default() -> Self {
188 TerminalSize::new(
189 DEBUG_LINE_HEIGHT,
190 DEBUG_CELL_WIDTH,
191 Size {
192 width: DEBUG_TERMINAL_WIDTH,
193 height: DEBUG_TERMINAL_HEIGHT,
194 },
195 )
196 }
197}
198
199impl From<TerminalSize> for WindowSize {
200 fn from(val: TerminalSize) -> Self {
201 WindowSize {
202 num_lines: val.num_lines() as u16,
203 num_cols: val.num_columns() as u16,
204 cell_width: f32::from(val.cell_width()) as u16,
205 cell_height: f32::from(val.line_height()) as u16,
206 }
207 }
208}
209
210impl Dimensions for TerminalSize {
211 /// Note: this is supposed to be for the back buffer's length,
212 /// but we exclusively use it to resize the terminal, which does not
213 /// use this method. We still have to implement it for the trait though,
214 /// hence, this comment.
215 fn total_lines(&self) -> usize {
216 self.screen_lines()
217 }
218
219 fn screen_lines(&self) -> usize {
220 self.num_lines()
221 }
222
223 fn columns(&self) -> usize {
224 self.num_columns()
225 }
226}
227
228#[derive(Error, Debug)]
229pub struct TerminalError {
230 pub directory: Option<PathBuf>,
231 pub shell: Shell,
232 pub source: std::io::Error,
233}
234
235impl TerminalError {
236 pub fn fmt_directory(&self) -> String {
237 self.directory
238 .clone()
239 .map(|path| {
240 match path
241 .into_os_string()
242 .into_string()
243 .map_err(|os_str| format!("<non-utf8 path> {}", os_str.to_string_lossy()))
244 {
245 Ok(s) => s,
246 Err(s) => s,
247 }
248 })
249 .unwrap_or_else(|| {
250 let default_dir =
251 dirs::home_dir().map(|buf| buf.into_os_string().to_string_lossy().to_string());
252 match default_dir {
253 Some(dir) => format!("<none specified, using home directory> {}", dir),
254 None => "<none specified, could not find home directory>".to_string(),
255 }
256 })
257 }
258
259 pub fn shell_to_string(&self) -> String {
260 match &self.shell {
261 Shell::System => "<system shell>".to_string(),
262 Shell::Program(p) => p.to_string(),
263 Shell::WithArguments { program, args } => format!("{} {}", program, args.join(" ")),
264 }
265 }
266
267 pub fn fmt_shell(&self) -> String {
268 match &self.shell {
269 Shell::System => "<system defined shell>".to_string(),
270 Shell::Program(s) => s.to_string(),
271 Shell::WithArguments { program, args } => format!("{} {}", program, args.join(" ")),
272 }
273 }
274}
275
276impl Display for TerminalError {
277 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
278 let dir_string: String = self.fmt_directory();
279 let shell = self.fmt_shell();
280
281 write!(
282 f,
283 "Working directory: {} Shell command: `{}`, IOError: {}",
284 dir_string, shell, self.source
285 )
286 }
287}
288
289pub struct SpawnTask {
290 pub id: TaskId,
291 pub full_label: String,
292 pub label: String,
293 pub command: String,
294 pub args: Vec<String>,
295 pub env: HashMap<String, String>,
296 pub reveal: RevealStrategy,
297}
298
299// https://github.com/alacritty/alacritty/blob/cb3a79dbf6472740daca8440d5166c1d4af5029e/extra/man/alacritty.5.scd?plain=1#L207-L213
300const DEFAULT_SCROLL_HISTORY_LINES: usize = 10_000;
301const MAX_SCROLL_HISTORY_LINES: usize = 100_000;
302
303pub struct TerminalBuilder {
304 terminal: Terminal,
305 events_rx: UnboundedReceiver<AlacTermEvent>,
306}
307
308impl TerminalBuilder {
309 #[allow(clippy::too_many_arguments)]
310 pub fn new(
311 working_directory: Option<PathBuf>,
312 task: Option<TaskState>,
313 shell: Shell,
314 mut env: HashMap<String, String>,
315 blink_settings: Option<TerminalBlink>,
316 alternate_scroll: AlternateScroll,
317 max_scroll_history_lines: Option<usize>,
318 window: AnyWindowHandle,
319 completion_tx: Sender<()>,
320 ) -> Result<TerminalBuilder> {
321 // TODO: Properly set the current locale,
322 env.entry("LC_ALL".to_string())
323 .or_insert_with(|| "en_US.UTF-8".to_string());
324
325 env.insert("ZED_TERM".to_string(), "true".to_string());
326
327 let pty_options = {
328 let alac_shell = match shell.clone() {
329 Shell::System => None,
330 Shell::Program(program) => {
331 Some(alacritty_terminal::tty::Shell::new(program, Vec::new()))
332 }
333 Shell::WithArguments { program, args } => {
334 Some(alacritty_terminal::tty::Shell::new(program, args))
335 }
336 };
337
338 alacritty_terminal::tty::Options {
339 shell: alac_shell,
340 working_directory: working_directory.clone(),
341 hold: false,
342 env: env.into_iter().collect(),
343 }
344 };
345
346 // Setup Alacritty's env
347 setup_env();
348
349 let scrolling_history = if task.is_some() {
350 // Tasks like `cargo build --all` may produce a lot of output, ergo allow maximum scrolling.
351 // After the task finishes, we do not allow appending to that terminal, so small tasks output should not
352 // cause excessive memory usage over time.
353 MAX_SCROLL_HISTORY_LINES
354 } else {
355 max_scroll_history_lines
356 .unwrap_or(DEFAULT_SCROLL_HISTORY_LINES)
357 .min(MAX_SCROLL_HISTORY_LINES)
358 };
359 let config = Config {
360 scrolling_history,
361 ..Config::default()
362 };
363
364 //Spawn a task so the Alacritty EventLoop can communicate with us in a view context
365 //TODO: Remove with a bounded sender which can be dispatched on &self
366 let (events_tx, events_rx) = unbounded();
367 //Set up the terminal...
368 let mut term = Term::new(
369 config,
370 &TerminalSize::default(),
371 ZedListener(events_tx.clone()),
372 );
373
374 //Start off blinking if we need to
375 if let Some(TerminalBlink::On) = blink_settings {
376 term.set_private_mode(PrivateMode::Named(NamedPrivateMode::BlinkingCursor));
377 }
378
379 //Alacritty defaults to alternate scrolling being on, so we just need to turn it off.
380 if let AlternateScroll::Off = alternate_scroll {
381 term.unset_private_mode(PrivateMode::Named(NamedPrivateMode::AlternateScroll));
382 }
383
384 let term = Arc::new(FairMutex::new(term));
385
386 //Setup the pty...
387 let pty = match tty::new(
388 &pty_options,
389 TerminalSize::default().into(),
390 window.window_id().as_u64(),
391 ) {
392 Ok(pty) => pty,
393 Err(error) => {
394 bail!(TerminalError {
395 directory: working_directory,
396 shell,
397 source: error,
398 });
399 }
400 };
401
402 let pty_info = PtyProcessInfo::new(&pty);
403
404 //And connect them together
405 let event_loop = EventLoop::new(
406 term.clone(),
407 ZedListener(events_tx.clone()),
408 pty,
409 pty_options.hold,
410 false,
411 )?;
412
413 //Kick things off
414 let pty_tx = event_loop.channel();
415 let _io_thread = event_loop.spawn(); // DANGER
416
417 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();
418 let word_regex = RegexSearch::new(r#"[\$\+\w.\[\]:/@\-~]+"#).unwrap();
419
420 let terminal = Terminal {
421 task,
422 pty_tx: Notifier(pty_tx),
423 completion_tx,
424 term,
425 events: VecDeque::with_capacity(10), //Should never get this high.
426 last_content: Default::default(),
427 last_mouse: None,
428 matches: Vec::new(),
429 selection_head: None,
430 pty_info,
431 breadcrumb_text: String::new(),
432 scroll_px: px(0.),
433 last_mouse_position: None,
434 next_link_id: 0,
435 selection_phase: SelectionPhase::Ended,
436 secondary_pressed: false,
437 hovered_word: false,
438 url_regex,
439 word_regex,
440 };
441
442 Ok(TerminalBuilder {
443 terminal,
444 events_rx,
445 })
446 }
447
448 pub fn subscribe(mut self, cx: &mut ModelContext<Terminal>) -> Terminal {
449 //Event loop
450 cx.spawn(|terminal, mut cx| async move {
451 while let Some(event) = self.events_rx.next().await {
452 terminal.update(&mut cx, |terminal, cx| {
453 //Process the first event immediately for lowered latency
454 terminal.process_event(&event, cx);
455 })?;
456
457 'outer: loop {
458 let mut events = Vec::new();
459 let mut timer = cx
460 .background_executor()
461 .timer(Duration::from_millis(4))
462 .fuse();
463 let mut wakeup = false;
464 loop {
465 futures::select_biased! {
466 _ = timer => break,
467 event = self.events_rx.next() => {
468 if let Some(event) = event {
469 if matches!(event, AlacTermEvent::Wakeup) {
470 wakeup = true;
471 } else {
472 events.push(event);
473 }
474
475 if events.len() > 100 {
476 break;
477 }
478 } else {
479 break;
480 }
481 },
482 }
483 }
484
485 if events.is_empty() && !wakeup {
486 smol::future::yield_now().await;
487 break 'outer;
488 }
489
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 anyhow::Ok(())
504 })
505 .detach();
506
507 self.terminal
508 }
509}
510
511#[derive(Debug, Clone, Deserialize, Serialize)]
512pub struct IndexedCell {
513 pub point: AlacPoint,
514 pub cell: Cell,
515}
516
517impl Deref for IndexedCell {
518 type Target = Cell;
519
520 #[inline]
521 fn deref(&self) -> &Cell {
522 &self.cell
523 }
524}
525
526// TODO: Un-pub
527#[derive(Clone)]
528pub struct TerminalContent {
529 pub cells: Vec<IndexedCell>,
530 pub mode: TermMode,
531 pub display_offset: usize,
532 pub selection_text: Option<String>,
533 pub selection: Option<SelectionRange>,
534 pub cursor: RenderableCursor,
535 pub cursor_char: char,
536 pub size: TerminalSize,
537 pub last_hovered_word: Option<HoveredWord>,
538}
539
540#[derive(Clone)]
541pub struct HoveredWord {
542 pub word: String,
543 pub word_match: RangeInclusive<AlacPoint>,
544 pub id: usize,
545}
546
547impl Default for TerminalContent {
548 fn default() -> Self {
549 TerminalContent {
550 cells: Default::default(),
551 mode: Default::default(),
552 display_offset: Default::default(),
553 selection_text: Default::default(),
554 selection: Default::default(),
555 cursor: RenderableCursor {
556 shape: alacritty_terminal::vte::ansi::CursorShape::Block,
557 point: AlacPoint::new(Line(0), Column(0)),
558 },
559 cursor_char: Default::default(),
560 size: Default::default(),
561 last_hovered_word: None,
562 }
563 }
564}
565
566#[derive(PartialEq, Eq)]
567pub enum SelectionPhase {
568 Selecting,
569 Ended,
570}
571
572pub struct Terminal {
573 pty_tx: Notifier,
574 completion_tx: Sender<()>,
575 term: Arc<FairMutex<Term<ZedListener>>>,
576 events: VecDeque<InternalEvent>,
577 /// This is only used for mouse mode cell change detection
578 last_mouse: Option<(AlacPoint, AlacDirection)>,
579 /// This is only used for terminal hovered word checking
580 last_mouse_position: Option<Point<Pixels>>,
581 pub matches: Vec<RangeInclusive<AlacPoint>>,
582 pub last_content: TerminalContent,
583 pub selection_head: Option<AlacPoint>,
584 pub breadcrumb_text: String,
585 pub pty_info: PtyProcessInfo,
586 scroll_px: Pixels,
587 next_link_id: usize,
588 selection_phase: SelectionPhase,
589 secondary_pressed: bool,
590 hovered_word: bool,
591 url_regex: RegexSearch,
592 word_regex: RegexSearch,
593 task: Option<TaskState>,
594}
595
596pub struct TaskState {
597 pub id: TaskId,
598 pub full_label: String,
599 pub label: String,
600 pub status: TaskStatus,
601 pub completion_rx: Receiver<()>,
602}
603
604/// A status of the current terminal tab's task.
605#[derive(Debug, Clone, Copy, PartialEq, Eq)]
606pub enum TaskStatus {
607 /// The task had been started, but got cancelled or somehow otherwise it did not
608 /// report its exit code before the terminal event loop was shut down.
609 Unknown,
610 /// The task is started and running currently.
611 Running,
612 /// After the start, the task stopped running and reported its error code back.
613 Completed { success: bool },
614}
615
616impl TaskStatus {
617 fn register_terminal_exit(&mut self) {
618 if self == &Self::Running {
619 *self = Self::Unknown;
620 }
621 }
622
623 fn register_task_exit(&mut self, error_code: i32) {
624 *self = TaskStatus::Completed {
625 success: error_code == 0,
626 };
627 }
628}
629
630impl Terminal {
631 fn process_event(&mut self, event: &AlacTermEvent, cx: &mut ModelContext<Self>) {
632 match event {
633 AlacTermEvent::Title(title) => {
634 self.breadcrumb_text = title.to_string();
635 cx.emit(Event::BreadcrumbsChanged);
636 }
637 AlacTermEvent::ResetTitle => {
638 self.breadcrumb_text = String::new();
639 cx.emit(Event::BreadcrumbsChanged);
640 }
641 AlacTermEvent::ClipboardStore(_, data) => {
642 cx.write_to_clipboard(ClipboardItem::new(data.to_string()))
643 }
644 AlacTermEvent::ClipboardLoad(_, format) => self.write_to_pty(format(
645 &cx.read_from_clipboard()
646 .map(|ci| ci.text().to_string())
647 .unwrap_or_else(|| "".to_string()),
648 )),
649 AlacTermEvent::PtyWrite(out) => self.write_to_pty(out.clone()),
650 AlacTermEvent::TextAreaSizeRequest(format) => {
651 self.write_to_pty(format(self.last_content.size.into()))
652 }
653 AlacTermEvent::CursorBlinkingChange => {
654 cx.emit(Event::BlinkChanged);
655 }
656 AlacTermEvent::Bell => {
657 cx.emit(Event::Bell);
658 }
659 AlacTermEvent::Exit => match &mut self.task {
660 Some(task) => {
661 task.status.register_terminal_exit();
662 self.completion_tx.try_send(()).ok();
663 }
664 None => cx.emit(Event::CloseTerminal),
665 },
666 AlacTermEvent::MouseCursorDirty => {
667 //NOOP, Handled in render
668 }
669 AlacTermEvent::Wakeup => {
670 cx.emit(Event::Wakeup);
671
672 if self.pty_info.has_changed() {
673 cx.emit(Event::TitleChanged);
674 }
675 }
676 AlacTermEvent::ColorRequest(idx, fun_ptr) => {
677 self.events
678 .push_back(InternalEvent::ColorRequest(*idx, fun_ptr.clone()));
679 }
680 AlacTermEvent::ChildExit(error_code) => {
681 if let Some(task) = &mut self.task {
682 task.status.register_task_exit(*error_code);
683 self.completion_tx.try_send(()).ok();
684 }
685 }
686 }
687 }
688
689 pub fn selection_started(&self) -> bool {
690 self.selection_phase == SelectionPhase::Selecting
691 }
692
693 pub fn get_cwd(&self) -> Option<PathBuf> {
694 self.pty_info.current.as_ref().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;
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 == sanitized_match
853 } else {
854 url_match.start() == sanitized_match.start()
855 && url_match.end() == original_match.end()
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: &[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.secondary_pressed != modifiers.secondary();
1035 if !self.secondary_pressed && modifiers.secondary() {
1036 self.refresh_hovered_word();
1037 }
1038 self.secondary_pressed = modifiers.secondary();
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.secondary_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.secondary_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) = scroll_report(point, scroll_lines, e, self.last_content.mode)
1295 {
1296 for scroll in scrolls {
1297 self.pty_tx.notify(scroll);
1298 }
1299 };
1300 } else if self
1301 .last_content
1302 .mode
1303 .contains(TermMode::ALT_SCREEN | TermMode::ALTERNATE_SCROLL)
1304 && !e.shift
1305 {
1306 self.pty_tx.notify(alt_scroll(scroll_lines))
1307 } else {
1308 if scroll_lines != 0 {
1309 let scroll = AlacScroll::Delta(scroll_lines);
1310
1311 self.events.push_back(InternalEvent::Scroll(scroll));
1312 }
1313 }
1314 }
1315 }
1316
1317 fn refresh_hovered_word(&mut self) {
1318 self.word_from_position(self.last_mouse_position);
1319 }
1320
1321 fn determine_scroll_lines(&mut self, e: &ScrollWheelEvent, mouse_mode: bool) -> Option<i32> {
1322 let scroll_multiplier = if mouse_mode { 1. } else { SCROLL_MULTIPLIER };
1323 let line_height = self.last_content.size.line_height;
1324 match e.touch_phase {
1325 /* Reset scroll state on started */
1326 TouchPhase::Started => {
1327 self.scroll_px = px(0.);
1328 None
1329 }
1330 /* Calculate the appropriate scroll lines */
1331 TouchPhase::Moved => {
1332 let old_offset = (self.scroll_px / line_height) as i32;
1333
1334 self.scroll_px += e.delta.pixel_delta(line_height).y * scroll_multiplier;
1335
1336 let new_offset = (self.scroll_px / line_height) as i32;
1337
1338 // Whenever we hit the edges, reset our stored scroll to 0
1339 // so we can respond to changes in direction quickly
1340 self.scroll_px %= self.last_content.size.height();
1341
1342 Some(new_offset - old_offset)
1343 }
1344 TouchPhase::Ended => None,
1345 }
1346 }
1347
1348 pub fn find_matches(
1349 &mut self,
1350 mut searcher: RegexSearch,
1351 cx: &mut ModelContext<Self>,
1352 ) -> Task<Vec<RangeInclusive<AlacPoint>>> {
1353 let term = self.term.clone();
1354 cx.background_executor().spawn(async move {
1355 let term = term.lock();
1356
1357 all_search_matches(&term, &mut searcher).collect()
1358 })
1359 }
1360
1361 pub fn title(&self, truncate: bool) -> String {
1362 const MAX_CHARS: usize = 25;
1363 match &self.task {
1364 Some(task_state) => {
1365 if truncate {
1366 truncate_and_trailoff(&task_state.label, MAX_CHARS)
1367 } else {
1368 task_state.full_label.clone()
1369 }
1370 }
1371 None => self
1372 .pty_info
1373 .current
1374 .as_ref()
1375 .map(|fpi| {
1376 let process_file = fpi
1377 .cwd
1378 .file_name()
1379 .map(|name| name.to_string_lossy().to_string())
1380 .unwrap_or_default();
1381
1382 let argv = fpi.argv.clone();
1383 let process_name = format!(
1384 "{}{}",
1385 fpi.name,
1386 if argv.len() >= 1 {
1387 format!(" {}", (argv[1..]).join(" "))
1388 } else {
1389 "".to_string()
1390 }
1391 );
1392 let (process_file, process_name) = if truncate {
1393 (
1394 truncate_and_trailoff(&process_file, MAX_CHARS),
1395 truncate_and_trailoff(&process_name, MAX_CHARS),
1396 )
1397 } else {
1398 (process_file, process_name)
1399 };
1400 format!("{process_file} — {process_name}")
1401 })
1402 .unwrap_or_else(|| "Terminal".to_string()),
1403 }
1404 }
1405
1406 pub fn can_navigate_to_selected_word(&self) -> bool {
1407 self.secondary_pressed && self.hovered_word
1408 }
1409
1410 pub fn task(&self) -> Option<&TaskState> {
1411 self.task.as_ref()
1412 }
1413
1414 pub fn wait_for_completed_task(&self, cx: &mut AppContext) -> Task<()> {
1415 if let Some(task) = self.task() {
1416 if task.status == TaskStatus::Running {
1417 let mut completion_receiver = task.completion_rx.clone();
1418 return cx.spawn(|_| async move {
1419 completion_receiver.next().await;
1420 });
1421 }
1422 }
1423 Task::ready(())
1424 }
1425}
1426
1427impl Drop for Terminal {
1428 fn drop(&mut self) {
1429 self.pty_tx.0.send(Msg::Shutdown).ok();
1430 }
1431}
1432
1433impl EventEmitter<Event> for Terminal {}
1434
1435/// Based on alacritty/src/display/hint.rs > regex_match_at
1436/// Retrieve the match, if the specified point is inside the content matching the regex.
1437fn regex_match_at<T>(term: &Term<T>, point: AlacPoint, regex: &mut RegexSearch) -> Option<Match> {
1438 visible_regex_match_iter(term, regex).find(|rm| rm.contains(&point))
1439}
1440
1441/// Copied from alacritty/src/display/hint.rs:
1442/// Iterate over all visible regex matches.
1443pub fn visible_regex_match_iter<'a, T>(
1444 term: &'a Term<T>,
1445 regex: &'a mut RegexSearch,
1446) -> impl Iterator<Item = Match> + 'a {
1447 let viewport_start = Line(-(term.grid().display_offset() as i32));
1448 let viewport_end = viewport_start + term.bottommost_line();
1449 let mut start = term.line_search_left(AlacPoint::new(viewport_start, Column(0)));
1450 let mut end = term.line_search_right(AlacPoint::new(viewport_end, Column(0)));
1451 start.line = start.line.max(viewport_start - MAX_SEARCH_LINES);
1452 end.line = end.line.min(viewport_end + MAX_SEARCH_LINES);
1453
1454 RegexIter::new(start, end, AlacDirection::Right, term, regex)
1455 .skip_while(move |rm| rm.end().line < viewport_start)
1456 .take_while(move |rm| rm.start().line <= viewport_end)
1457}
1458
1459fn make_selection(range: &RangeInclusive<AlacPoint>) -> Selection {
1460 let mut selection = Selection::new(SelectionType::Simple, *range.start(), AlacDirection::Left);
1461 selection.update(*range.end(), AlacDirection::Right);
1462 selection
1463}
1464
1465fn all_search_matches<'a, T>(
1466 term: &'a Term<T>,
1467 regex: &'a mut RegexSearch,
1468) -> impl Iterator<Item = Match> + 'a {
1469 let start = AlacPoint::new(term.grid().topmost_line(), Column(0));
1470 let end = AlacPoint::new(term.grid().bottommost_line(), term.grid().last_column());
1471 RegexIter::new(start, end, AlacDirection::Right, term, regex)
1472}
1473
1474fn content_index_for_mouse(pos: Point<Pixels>, size: &TerminalSize) -> usize {
1475 let col = (pos.x / size.cell_width()).round() as usize;
1476 let clamped_col = min(col, size.columns() - 1);
1477 let row = (pos.y / size.line_height()).round() as usize;
1478 let clamped_row = min(row, size.screen_lines() - 1);
1479 clamped_row * size.columns() + clamped_col
1480}
1481
1482/// Converts an 8 bit ANSI color to its GPUI equivalent.
1483/// Accepts `usize` for compatibility with the `alacritty::Colors` interface,
1484/// Other than that use case, should only be called with values in the [0,255] range
1485pub fn get_color_at_index(index: usize, theme: &Theme) -> Hsla {
1486 let colors = theme.colors();
1487
1488 match index {
1489 // 0-15 are the same as the named colors above
1490 0 => colors.terminal_ansi_black,
1491 1 => colors.terminal_ansi_red,
1492 2 => colors.terminal_ansi_green,
1493 3 => colors.terminal_ansi_yellow,
1494 4 => colors.terminal_ansi_blue,
1495 5 => colors.terminal_ansi_magenta,
1496 6 => colors.terminal_ansi_cyan,
1497 7 => colors.terminal_ansi_white,
1498 8 => colors.terminal_ansi_bright_black,
1499 9 => colors.terminal_ansi_bright_red,
1500 10 => colors.terminal_ansi_bright_green,
1501 11 => colors.terminal_ansi_bright_yellow,
1502 12 => colors.terminal_ansi_bright_blue,
1503 13 => colors.terminal_ansi_bright_magenta,
1504 14 => colors.terminal_ansi_bright_cyan,
1505 15 => colors.terminal_ansi_bright_white,
1506 // 16-231 are mapped to their RGB colors on a 0-5 range per channel
1507 16..=231 => {
1508 let (r, g, b) = rgb_for_index(index as u8); // Split the index into its ANSI-RGB components
1509 let step = (u8::MAX as f32 / 5.).floor() as u8; // Split the RGB range into 5 chunks, with floor so no overflow
1510 rgba_color(r * step, g * step, b * step) // Map the ANSI-RGB components to an RGB color
1511 }
1512 // 232-255 are a 24 step grayscale from black to white
1513 232..=255 => {
1514 let i = index as u8 - 232; // Align index to 0..24
1515 let step = (u8::MAX as f32 / 24.).floor() as u8; // Split the RGB grayscale values into 24 chunks
1516 rgba_color(i * step, i * step, i * step) // Map the ANSI-grayscale components to the RGB-grayscale
1517 }
1518 // For compatibility with the alacritty::Colors interface
1519 256 => colors.text,
1520 257 => colors.background,
1521 258 => theme.players().local().cursor,
1522 259 => colors.terminal_ansi_dim_black,
1523 260 => colors.terminal_ansi_dim_red,
1524 261 => colors.terminal_ansi_dim_green,
1525 262 => colors.terminal_ansi_dim_yellow,
1526 263 => colors.terminal_ansi_dim_blue,
1527 264 => colors.terminal_ansi_dim_magenta,
1528 265 => colors.terminal_ansi_dim_cyan,
1529 266 => colors.terminal_ansi_dim_white,
1530 267 => colors.terminal_bright_foreground,
1531 268 => colors.terminal_ansi_black, // 'Dim Background', non-standard color
1532
1533 _ => black(),
1534 }
1535}
1536
1537/// Generates the RGB channels in [0, 5] for a given index into the 6x6x6 ANSI color cube.
1538/// See: [8 bit ANSI color](https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit).
1539///
1540/// Wikipedia gives a formula for calculating the index for a given color:
1541///
1542/// ```
1543/// index = 16 + 36 × r + 6 × g + b (0 ≤ r, g, b ≤ 5)
1544/// ```
1545///
1546/// This function does the reverse, calculating the `r`, `g`, and `b` components from a given index.
1547fn rgb_for_index(i: u8) -> (u8, u8, u8) {
1548 debug_assert!((16..=231).contains(&i));
1549 let i = i - 16;
1550 let r = (i - (i % 36)) / 36;
1551 let g = ((i % 36) - (i % 6)) / 6;
1552 let b = (i % 36) % 6;
1553 (r, g, b)
1554}
1555
1556pub fn rgba_color(r: u8, g: u8, b: u8) -> Hsla {
1557 Rgba {
1558 r: (r as f32 / 255.),
1559 g: (g as f32 / 255.),
1560 b: (b as f32 / 255.),
1561 a: 1.,
1562 }
1563 .into()
1564}
1565
1566#[cfg(test)]
1567mod tests {
1568 use alacritty_terminal::{
1569 index::{Column, Line, Point as AlacPoint},
1570 term::cell::Cell,
1571 };
1572 use gpui::{point, size, Pixels};
1573 use rand::{distributions::Alphanumeric, rngs::ThreadRng, thread_rng, Rng};
1574
1575 use crate::{
1576 content_index_for_mouse, rgb_for_index, IndexedCell, TerminalContent, TerminalSize,
1577 };
1578
1579 #[test]
1580 fn test_rgb_for_index() {
1581 // Test every possible value in the color cube.
1582 for i in 16..=231 {
1583 let (r, g, b) = rgb_for_index(i);
1584 assert_eq!(i, 16 + 36 * r + 6 * g + b);
1585 }
1586 }
1587
1588 #[test]
1589 fn test_mouse_to_cell_test() {
1590 let mut rng = thread_rng();
1591 const ITERATIONS: usize = 10;
1592 const PRECISION: usize = 1000;
1593
1594 for _ in 0..ITERATIONS {
1595 let viewport_cells = rng.gen_range(15..20);
1596 let cell_size = rng.gen_range(5 * PRECISION..20 * PRECISION) as f32 / PRECISION as f32;
1597
1598 let size = crate::TerminalSize {
1599 cell_width: Pixels::from(cell_size),
1600 line_height: Pixels::from(cell_size),
1601 size: size(
1602 Pixels::from(cell_size * (viewport_cells as f32)),
1603 Pixels::from(cell_size * (viewport_cells as f32)),
1604 ),
1605 };
1606
1607 let cells = get_cells(size, &mut rng);
1608 let content = convert_cells_to_content(size, &cells);
1609
1610 for row in 0..(viewport_cells - 1) {
1611 let row = row as usize;
1612 for col in 0..(viewport_cells - 1) {
1613 let col = col as usize;
1614
1615 let row_offset = rng.gen_range(0..PRECISION) as f32 / PRECISION as f32;
1616 let col_offset = rng.gen_range(0..PRECISION) as f32 / PRECISION as f32;
1617
1618 let mouse_pos = point(
1619 Pixels::from(col as f32 * cell_size + col_offset),
1620 Pixels::from(row as f32 * cell_size + row_offset),
1621 );
1622
1623 let content_index = content_index_for_mouse(mouse_pos, &content.size);
1624 let mouse_cell = content.cells[content_index].c;
1625 let real_cell = cells[row][col];
1626
1627 assert_eq!(mouse_cell, real_cell);
1628 }
1629 }
1630 }
1631 }
1632
1633 #[test]
1634 fn test_mouse_to_cell_clamp() {
1635 let mut rng = thread_rng();
1636
1637 let size = crate::TerminalSize {
1638 cell_width: Pixels::from(10.),
1639 line_height: Pixels::from(10.),
1640 size: size(Pixels::from(100.), Pixels::from(100.)),
1641 };
1642
1643 let cells = get_cells(size, &mut rng);
1644 let content = convert_cells_to_content(size, &cells);
1645
1646 assert_eq!(
1647 content.cells[content_index_for_mouse(
1648 point(Pixels::from(-10.), Pixels::from(-10.)),
1649 &content.size,
1650 )]
1651 .c,
1652 cells[0][0]
1653 );
1654 assert_eq!(
1655 content.cells[content_index_for_mouse(
1656 point(Pixels::from(1000.), Pixels::from(1000.)),
1657 &content.size,
1658 )]
1659 .c,
1660 cells[9][9]
1661 );
1662 }
1663
1664 fn get_cells(size: TerminalSize, rng: &mut ThreadRng) -> Vec<Vec<char>> {
1665 let mut cells = Vec::new();
1666
1667 for _ in 0..((size.height() / size.line_height()) as usize) {
1668 let mut row_vec = Vec::new();
1669 for _ in 0..((size.width() / size.cell_width()) as usize) {
1670 let cell_char = rng.sample(Alphanumeric) as char;
1671 row_vec.push(cell_char)
1672 }
1673 cells.push(row_vec)
1674 }
1675
1676 cells
1677 }
1678
1679 fn convert_cells_to_content(size: TerminalSize, cells: &Vec<Vec<char>>) -> TerminalContent {
1680 let mut ic = Vec::new();
1681
1682 for row in 0..cells.len() {
1683 for col in 0..cells[row].len() {
1684 let cell_char = cells[row][col];
1685 ic.push(IndexedCell {
1686 point: AlacPoint::new(Line(row as i32), Column(col)),
1687 cell: Cell {
1688 c: cell_char,
1689 ..Default::default()
1690 },
1691 });
1692 }
1693 }
1694
1695 TerminalContent {
1696 cells: ic,
1697 size,
1698 ..Default::default()
1699 }
1700 }
1701}