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