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