1pub mod mappings;
2
3pub use alacritty_terminal;
4
5mod pty_info;
6mod terminal_hyperlinks;
7pub mod terminal_settings;
8
9use alacritty_terminal::{
10 Term,
11 event::{Event as AlacTermEvent, EventListener, Notify, WindowSize},
12 event_loop::{EventLoop, Msg, Notifier},
13 grid::{Dimensions, Grid, Row, Scroll as AlacScroll},
14 index::{Boundary, Column, Direction as AlacDirection, Line, Point as AlacPoint},
15 selection::{Selection, SelectionRange, SelectionType},
16 sync::FairMutex,
17 term::{
18 Config, RenderableCursor, TermMode,
19 cell::{Cell, Flags},
20 search::{Match, RegexIter, RegexSearch},
21 },
22 tty::{self},
23 vi_mode::{ViModeCursor, ViMotion},
24 vte::ansi::{
25 ClearMode, CursorStyle as AlacCursorStyle, Handler, NamedPrivateMode, PrivateMode,
26 },
27};
28use anyhow::{Result, bail};
29
30use futures::{
31 FutureExt,
32 channel::mpsc::{UnboundedReceiver, UnboundedSender, unbounded},
33};
34
35use mappings::mouse::{
36 alt_scroll, grid_point, grid_point_and_side, mouse_button_report, mouse_moved_report,
37 scroll_report,
38};
39
40use collections::{HashMap, VecDeque};
41use futures::StreamExt;
42use pty_info::PtyProcessInfo;
43use serde::{Deserialize, Serialize};
44use settings::Settings;
45use smol::channel::{Receiver, Sender};
46use task::{HideStrategy, Shell, TaskId};
47use terminal_hyperlinks::RegexSearches;
48use terminal_settings::{AlternateScroll, CursorShape, TerminalSettings};
49use theme::{ActiveTheme, Theme};
50use urlencoding;
51use util::{paths::home_dir, truncate_and_trailoff};
52
53use std::{
54 borrow::Cow,
55 cmp::{self, min},
56 fmt::Display,
57 ops::{Deref, RangeInclusive},
58 path::PathBuf,
59 process::ExitStatus,
60 sync::Arc,
61 time::{Duration, Instant},
62};
63use thiserror::Error;
64
65use gpui::{
66 AnyWindowHandle, App, AppContext as _, Bounds, ClipboardItem, Context, EventEmitter, Hsla,
67 Keystroke, Modifiers, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, Pixels, Point,
68 Rgba, ScrollWheelEvent, SharedString, Size, Task, TouchPhase, Window, actions, black, px,
69};
70
71use crate::mappings::{colors::to_alac_rgb, keys::to_esc_str};
72
73actions!(
74 terminal,
75 [
76 /// Clears the terminal screen.
77 Clear,
78 /// Copies selected text to the clipboard.
79 Copy,
80 /// Pastes from the clipboard.
81 Paste,
82 /// Shows the character palette for special characters.
83 ShowCharacterPalette,
84 /// Searches for text in the terminal.
85 SearchTest,
86 /// Scrolls up by one line.
87 ScrollLineUp,
88 /// Scrolls down by one line.
89 ScrollLineDown,
90 /// Scrolls up by one page.
91 ScrollPageUp,
92 /// Scrolls down by one page.
93 ScrollPageDown,
94 /// Scrolls up by half a page.
95 ScrollHalfPageUp,
96 /// Scrolls down by half a page.
97 ScrollHalfPageDown,
98 /// Scrolls to the top of the terminal buffer.
99 ScrollToTop,
100 /// Scrolls to the bottom of the terminal buffer.
101 ScrollToBottom,
102 /// Toggles vi mode in the terminal.
103 ToggleViMode,
104 /// Selects all text in the terminal.
105 SelectAll,
106 ]
107);
108
109///Scrolling is unbearably sluggish by default. Alacritty supports a configurable
110///Scroll multiplier that is set to 3 by default. This will be removed when I
111///Implement scroll bars.
112#[cfg(target_os = "macos")]
113const SCROLL_MULTIPLIER: f32 = 4.;
114#[cfg(not(target_os = "macos"))]
115const SCROLL_MULTIPLIER: f32 = 1.;
116const DEBUG_TERMINAL_WIDTH: Pixels = px(500.);
117const DEBUG_TERMINAL_HEIGHT: Pixels = px(30.);
118const DEBUG_CELL_WIDTH: Pixels = px(5.);
119const DEBUG_LINE_HEIGHT: Pixels = px(5.);
120
121///Upward flowing events, for changing the title and such
122#[derive(Clone, Debug)]
123pub enum Event {
124 TitleChanged,
125 BreadcrumbsChanged,
126 CloseTerminal,
127 Bell,
128 Wakeup,
129 BlinkChanged(bool),
130 SelectionsChanged,
131 NewNavigationTarget(Option<MaybeNavigationTarget>),
132 Open(MaybeNavigationTarget),
133}
134
135#[derive(Clone, Debug)]
136pub struct PathLikeTarget {
137 /// File system path, absolute or relative, existing or not.
138 /// Might have line and column number(s) attached as `file.rs:1:23`
139 pub maybe_path: String,
140 /// Current working directory of the terminal
141 pub terminal_dir: Option<PathBuf>,
142}
143
144/// A string inside terminal, potentially useful as a URI that can be opened.
145#[derive(Clone, Debug)]
146pub enum MaybeNavigationTarget {
147 /// HTTP, git, etc. string determined by the `URL_REGEX` regex.
148 Url(String),
149 /// File system path, absolute or relative, existing or not.
150 /// Might have line and column number(s) attached as `file.rs:1:23`
151 PathLike(PathLikeTarget),
152}
153
154#[derive(Clone)]
155enum InternalEvent {
156 Resize(TerminalBounds),
157 Clear,
158 // FocusNextMatch,
159 Scroll(AlacScroll),
160 ScrollToAlacPoint(AlacPoint),
161 SetSelection(Option<(Selection, AlacPoint)>),
162 UpdateSelection(Point<Pixels>),
163 // Adjusted mouse position, should open
164 FindHyperlink(Point<Pixels>, bool),
165 Copy,
166 // Vi mode events
167 ToggleViMode,
168 ViMotion(ViMotion),
169}
170
171///A translation struct for Alacritty to communicate with us from their event loop
172#[derive(Clone)]
173pub struct ZedListener(pub UnboundedSender<AlacTermEvent>);
174
175impl EventListener for ZedListener {
176 fn send_event(&self, event: AlacTermEvent) {
177 self.0.unbounded_send(event).ok();
178 }
179}
180
181pub fn init(cx: &mut App) {
182 TerminalSettings::register(cx);
183}
184
185#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
186pub struct TerminalBounds {
187 pub cell_width: Pixels,
188 pub line_height: Pixels,
189 pub bounds: Bounds<Pixels>,
190}
191
192impl TerminalBounds {
193 pub fn new(line_height: Pixels, cell_width: Pixels, bounds: Bounds<Pixels>) -> Self {
194 TerminalBounds {
195 cell_width,
196 line_height,
197 bounds,
198 }
199 }
200
201 pub fn num_lines(&self) -> usize {
202 (self.bounds.size.height / self.line_height).floor() as usize
203 }
204
205 pub fn num_columns(&self) -> usize {
206 (self.bounds.size.width / self.cell_width).floor() as usize
207 }
208
209 pub fn height(&self) -> Pixels {
210 self.bounds.size.height
211 }
212
213 pub fn width(&self) -> Pixels {
214 self.bounds.size.width
215 }
216
217 pub fn cell_width(&self) -> Pixels {
218 self.cell_width
219 }
220
221 pub fn line_height(&self) -> Pixels {
222 self.line_height
223 }
224}
225
226impl Default for TerminalBounds {
227 fn default() -> Self {
228 TerminalBounds::new(
229 DEBUG_LINE_HEIGHT,
230 DEBUG_CELL_WIDTH,
231 Bounds {
232 origin: Point::default(),
233 size: Size {
234 width: DEBUG_TERMINAL_WIDTH,
235 height: DEBUG_TERMINAL_HEIGHT,
236 },
237 },
238 )
239 }
240}
241
242impl From<TerminalBounds> for WindowSize {
243 fn from(val: TerminalBounds) -> Self {
244 WindowSize {
245 num_lines: val.num_lines() as u16,
246 num_cols: val.num_columns() as u16,
247 cell_width: f32::from(val.cell_width()) as u16,
248 cell_height: f32::from(val.line_height()) as u16,
249 }
250 }
251}
252
253impl Dimensions for TerminalBounds {
254 /// Note: this is supposed to be for the back buffer's length,
255 /// but we exclusively use it to resize the terminal, which does not
256 /// use this method. We still have to implement it for the trait though,
257 /// hence, this comment.
258 fn total_lines(&self) -> usize {
259 self.screen_lines()
260 }
261
262 fn screen_lines(&self) -> usize {
263 self.num_lines()
264 }
265
266 fn columns(&self) -> usize {
267 self.num_columns()
268 }
269}
270
271#[derive(Error, Debug)]
272pub struct TerminalError {
273 pub directory: Option<PathBuf>,
274 pub shell: Shell,
275 pub source: std::io::Error,
276}
277
278impl TerminalError {
279 pub fn fmt_directory(&self) -> String {
280 self.directory
281 .clone()
282 .map(|path| {
283 match path
284 .into_os_string()
285 .into_string()
286 .map_err(|os_str| format!("<non-utf8 path> {}", os_str.to_string_lossy()))
287 {
288 Ok(s) => s,
289 Err(s) => s,
290 }
291 })
292 .unwrap_or_else(|| match dirs::home_dir() {
293 Some(dir) => format!(
294 "<none specified, using home directory> {}",
295 dir.into_os_string().to_string_lossy()
296 ),
297 None => "<none specified, could not find home directory>".to_string(),
298 })
299 }
300
301 pub fn fmt_shell(&self) -> String {
302 match &self.shell {
303 Shell::System => "<system defined shell>".to_string(),
304 Shell::Program(s) => s.to_string(),
305 Shell::WithArguments {
306 program,
307 args,
308 title_override,
309 } => {
310 if let Some(title_override) = title_override {
311 format!("{} {} ({})", program, args.join(" "), title_override)
312 } else {
313 format!("{} {}", program, args.join(" "))
314 }
315 }
316 }
317 }
318}
319
320impl Display for TerminalError {
321 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
322 let dir_string: String = self.fmt_directory();
323 let shell = self.fmt_shell();
324
325 write!(
326 f,
327 "Working directory: {} Shell command: `{}`, IOError: {}",
328 dir_string, shell, self.source
329 )
330 }
331}
332
333// https://github.com/alacritty/alacritty/blob/cb3a79dbf6472740daca8440d5166c1d4af5029e/extra/man/alacritty.5.scd?plain=1#L207-L213
334const DEFAULT_SCROLL_HISTORY_LINES: usize = 10_000;
335pub const MAX_SCROLL_HISTORY_LINES: usize = 100_000;
336
337pub struct TerminalBuilder {
338 terminal: Terminal,
339 events_rx: UnboundedReceiver<AlacTermEvent>,
340}
341
342impl TerminalBuilder {
343 pub fn new(
344 working_directory: Option<PathBuf>,
345 python_venv_directory: Option<PathBuf>,
346 task: Option<TaskState>,
347 shell: Shell,
348 mut env: HashMap<String, String>,
349 cursor_shape: CursorShape,
350 alternate_scroll: AlternateScroll,
351 max_scroll_history_lines: Option<usize>,
352 is_ssh_terminal: bool,
353 window: AnyWindowHandle,
354 completion_tx: Sender<Option<ExitStatus>>,
355 cx: &App,
356 ) -> Result<TerminalBuilder> {
357 // If the parent environment doesn't have a locale set
358 // (As is the case when launched from a .app on MacOS),
359 // and the Project doesn't have a locale set, then
360 // set a fallback for our child environment to use.
361 if std::env::var("LANG").is_err() {
362 env.entry("LANG".to_string())
363 .or_insert_with(|| "en_US.UTF-8".to_string());
364 }
365
366 env.insert("ZED_TERM".to_string(), "true".to_string());
367 env.insert("TERM_PROGRAM".to_string(), "zed".to_string());
368 env.insert("TERM".to_string(), "xterm-256color".to_string());
369 env.insert(
370 "TERM_PROGRAM_VERSION".to_string(),
371 release_channel::AppVersion::global(cx).to_string(),
372 );
373
374 let mut terminal_title_override = None;
375
376 let pty_options = {
377 let alac_shell = match shell.clone() {
378 Shell::System => {
379 #[cfg(target_os = "windows")]
380 {
381 Some(alacritty_terminal::tty::Shell::new(
382 util::get_windows_system_shell(),
383 Vec::new(),
384 ))
385 }
386 #[cfg(not(target_os = "windows"))]
387 {
388 None
389 }
390 }
391 Shell::Program(program) => {
392 Some(alacritty_terminal::tty::Shell::new(program, Vec::new()))
393 }
394 Shell::WithArguments {
395 program,
396 args,
397 title_override,
398 } => {
399 terminal_title_override = title_override;
400 Some(alacritty_terminal::tty::Shell::new(program, args))
401 }
402 };
403
404 alacritty_terminal::tty::Options {
405 shell: alac_shell,
406 working_directory: working_directory
407 .clone()
408 .or_else(|| Some(home_dir().to_path_buf())),
409 drain_on_exit: true,
410 env: env.into_iter().collect(),
411 }
412 };
413
414 // Setup Alacritty's env, which modifies the current process's environment
415 alacritty_terminal::tty::setup_env();
416
417 let default_cursor_style = AlacCursorStyle::from(cursor_shape);
418 let scrolling_history = if task.is_some() {
419 // Tasks like `cargo build --all` may produce a lot of output, ergo allow maximum scrolling.
420 // After the task finishes, we do not allow appending to that terminal, so small tasks output should not
421 // cause excessive memory usage over time.
422 MAX_SCROLL_HISTORY_LINES
423 } else {
424 max_scroll_history_lines
425 .unwrap_or(DEFAULT_SCROLL_HISTORY_LINES)
426 .min(MAX_SCROLL_HISTORY_LINES)
427 };
428 let config = Config {
429 scrolling_history,
430 default_cursor_style,
431 ..Config::default()
432 };
433
434 //Spawn a task so the Alacritty EventLoop can communicate with us
435 //TODO: Remove with a bounded sender which can be dispatched on &self
436 let (events_tx, events_rx) = unbounded();
437 //Set up the terminal...
438 let mut term = Term::new(
439 config.clone(),
440 &TerminalBounds::default(),
441 ZedListener(events_tx.clone()),
442 );
443
444 //Alacritty defaults to alternate scrolling being on, so we just need to turn it off.
445 if let AlternateScroll::Off = alternate_scroll {
446 term.unset_private_mode(PrivateMode::Named(NamedPrivateMode::AlternateScroll));
447 }
448
449 let term = Arc::new(FairMutex::new(term));
450
451 //Setup the pty...
452 let pty = match tty::new(
453 &pty_options,
454 TerminalBounds::default().into(),
455 window.window_id().as_u64(),
456 ) {
457 Ok(pty) => pty,
458 Err(error) => {
459 bail!(TerminalError {
460 directory: working_directory,
461 shell,
462 source: error,
463 });
464 }
465 };
466
467 let pty_info = PtyProcessInfo::new(&pty);
468
469 //And connect them together
470 let event_loop = EventLoop::new(
471 term.clone(),
472 ZedListener(events_tx.clone()),
473 pty,
474 pty_options.drain_on_exit,
475 false,
476 )?;
477
478 //Kick things off
479 let pty_tx = event_loop.channel();
480 let _io_thread = event_loop.spawn(); // DANGER
481
482 let terminal = Terminal {
483 task,
484 pty_tx: Notifier(pty_tx),
485 completion_tx,
486 term,
487 term_config: config,
488 title_override: terminal_title_override,
489 events: VecDeque::with_capacity(10), //Should never get this high.
490 last_content: Default::default(),
491 last_mouse: None,
492 matches: Vec::new(),
493 selection_head: None,
494 pty_info,
495 breadcrumb_text: String::new(),
496 scroll_px: px(0.),
497 next_link_id: 0,
498 selection_phase: SelectionPhase::Ended,
499 // hovered_word: false,
500 hyperlink_regex_searches: RegexSearches::new(),
501 vi_mode_enabled: false,
502 is_ssh_terminal,
503 python_venv_directory,
504 last_mouse_move_time: Instant::now(),
505 last_hyperlink_search_position: None,
506 };
507
508 Ok(TerminalBuilder {
509 terminal,
510 events_rx,
511 })
512 }
513
514 pub fn subscribe(mut self, cx: &Context<Terminal>) -> Terminal {
515 //Event loop
516 cx.spawn(async move |terminal, cx| {
517 while let Some(event) = self.events_rx.next().await {
518 terminal.update(cx, |terminal, cx| {
519 //Process the first event immediately for lowered latency
520 terminal.process_event(event, cx);
521 })?;
522
523 'outer: loop {
524 let mut events = Vec::new();
525 let mut timer = cx
526 .background_executor()
527 .timer(Duration::from_millis(4))
528 .fuse();
529 let mut wakeup = false;
530 loop {
531 futures::select_biased! {
532 _ = timer => break,
533 event = self.events_rx.next() => {
534 if let Some(event) = event {
535 if matches!(event, AlacTermEvent::Wakeup) {
536 wakeup = true;
537 } else {
538 events.push(event);
539 }
540
541 if events.len() > 100 {
542 break;
543 }
544 } else {
545 break;
546 }
547 },
548 }
549 }
550
551 if events.is_empty() && !wakeup {
552 smol::future::yield_now().await;
553 break 'outer;
554 }
555
556 terminal.update(cx, |this, cx| {
557 if wakeup {
558 this.process_event(AlacTermEvent::Wakeup, cx);
559 }
560
561 for event in events {
562 this.process_event(event, cx);
563 }
564 })?;
565 smol::future::yield_now().await;
566 }
567 }
568
569 anyhow::Ok(())
570 })
571 .detach();
572
573 self.terminal
574 }
575}
576
577#[derive(Debug, Clone, Deserialize, Serialize)]
578pub struct IndexedCell {
579 pub point: AlacPoint,
580 pub cell: Cell,
581}
582
583impl Deref for IndexedCell {
584 type Target = Cell;
585
586 #[inline]
587 fn deref(&self) -> &Cell {
588 &self.cell
589 }
590}
591
592// TODO: Un-pub
593#[derive(Clone)]
594pub struct TerminalContent {
595 pub cells: Vec<IndexedCell>,
596 pub mode: TermMode,
597 pub display_offset: usize,
598 pub selection_text: Option<String>,
599 pub selection: Option<SelectionRange>,
600 pub cursor: RenderableCursor,
601 pub cursor_char: char,
602 pub terminal_bounds: TerminalBounds,
603 pub last_hovered_word: Option<HoveredWord>,
604 pub scrolled_to_top: bool,
605 pub scrolled_to_bottom: bool,
606}
607
608#[derive(Debug, Clone, Eq, PartialEq)]
609pub struct HoveredWord {
610 pub word: String,
611 pub word_match: RangeInclusive<AlacPoint>,
612 pub id: usize,
613}
614
615impl Default for TerminalContent {
616 fn default() -> Self {
617 TerminalContent {
618 cells: Default::default(),
619 mode: Default::default(),
620 display_offset: Default::default(),
621 selection_text: Default::default(),
622 selection: Default::default(),
623 cursor: RenderableCursor {
624 shape: alacritty_terminal::vte::ansi::CursorShape::Block,
625 point: AlacPoint::new(Line(0), Column(0)),
626 },
627 cursor_char: Default::default(),
628 terminal_bounds: Default::default(),
629 last_hovered_word: None,
630 scrolled_to_top: false,
631 scrolled_to_bottom: false,
632 }
633 }
634}
635
636#[derive(PartialEq, Eq)]
637pub enum SelectionPhase {
638 Selecting,
639 Ended,
640}
641
642pub struct Terminal {
643 pty_tx: Notifier,
644 completion_tx: Sender<Option<ExitStatus>>,
645 term: Arc<FairMutex<Term<ZedListener>>>,
646 term_config: Config,
647 events: VecDeque<InternalEvent>,
648 /// This is only used for mouse mode cell change detection
649 last_mouse: Option<(AlacPoint, AlacDirection)>,
650 pub matches: Vec<RangeInclusive<AlacPoint>>,
651 pub last_content: TerminalContent,
652 pub selection_head: Option<AlacPoint>,
653 pub breadcrumb_text: String,
654 pub pty_info: PtyProcessInfo,
655 title_override: Option<SharedString>,
656 pub python_venv_directory: Option<PathBuf>,
657 scroll_px: Pixels,
658 next_link_id: usize,
659 selection_phase: SelectionPhase,
660 hyperlink_regex_searches: RegexSearches,
661 task: Option<TaskState>,
662 vi_mode_enabled: bool,
663 is_ssh_terminal: bool,
664 last_mouse_move_time: Instant,
665 last_hyperlink_search_position: Option<Point<Pixels>>,
666}
667
668pub struct TaskState {
669 pub id: TaskId,
670 pub full_label: String,
671 pub label: String,
672 pub command_label: String,
673 pub status: TaskStatus,
674 pub completion_rx: Receiver<Option<ExitStatus>>,
675 pub hide: HideStrategy,
676 pub show_summary: bool,
677 pub show_command: bool,
678 pub show_rerun: bool,
679}
680
681/// A status of the current terminal tab's task.
682#[derive(Debug, Clone, Copy, PartialEq, Eq)]
683pub enum TaskStatus {
684 /// The task had been started, but got cancelled or somehow otherwise it did not
685 /// report its exit code before the terminal event loop was shut down.
686 Unknown,
687 /// The task is started and running currently.
688 Running,
689 /// After the start, the task stopped running and reported its error code back.
690 Completed { success: bool },
691}
692
693impl TaskStatus {
694 fn register_terminal_exit(&mut self) {
695 if self == &Self::Running {
696 *self = Self::Unknown;
697 }
698 }
699
700 fn register_task_exit(&mut self, error_code: i32) {
701 *self = TaskStatus::Completed {
702 success: error_code == 0,
703 };
704 }
705}
706
707impl Terminal {
708 fn process_event(&mut self, event: AlacTermEvent, cx: &mut Context<Self>) {
709 match event {
710 AlacTermEvent::Title(title) => {
711 self.breadcrumb_text = title;
712 cx.emit(Event::BreadcrumbsChanged);
713 }
714 AlacTermEvent::ResetTitle => {
715 self.breadcrumb_text = String::new();
716 cx.emit(Event::BreadcrumbsChanged);
717 }
718 AlacTermEvent::ClipboardStore(_, data) => {
719 cx.write_to_clipboard(ClipboardItem::new_string(data))
720 }
721 AlacTermEvent::ClipboardLoad(_, format) => {
722 self.write_to_pty(
723 match &cx.read_from_clipboard().and_then(|item| item.text()) {
724 // The terminal only supports pasting strings, not images.
725 Some(text) => format(text),
726 _ => format(""),
727 }
728 .into_bytes(),
729 )
730 }
731 AlacTermEvent::PtyWrite(out) => self.write_to_pty(out.into_bytes()),
732 AlacTermEvent::TextAreaSizeRequest(format) => {
733 self.write_to_pty(format(self.last_content.terminal_bounds.into()).into_bytes())
734 }
735 AlacTermEvent::CursorBlinkingChange => {
736 let terminal = self.term.lock();
737 let blinking = terminal.cursor_style().blinking;
738 cx.emit(Event::BlinkChanged(blinking));
739 }
740 AlacTermEvent::Bell => {
741 cx.emit(Event::Bell);
742 }
743 AlacTermEvent::Exit => self.register_task_finished(None, cx),
744 AlacTermEvent::MouseCursorDirty => {
745 //NOOP, Handled in render
746 }
747 AlacTermEvent::Wakeup => {
748 cx.emit(Event::Wakeup);
749
750 if self.pty_info.has_changed() {
751 cx.emit(Event::TitleChanged);
752 }
753 }
754 AlacTermEvent::ColorRequest(index, format) => {
755 // It's important that the color request is processed here to retain relative order
756 // with other PTY writes. Otherwise applications might witness out-of-order
757 // responses to requests. For example: An application sending `OSC 11 ; ? ST`
758 // (color request) followed by `CSI c` (request device attributes) would receive
759 // the response to `CSI c` first.
760 // Instead of locking, we could store the colors in `self.last_content`. But then
761 // we might respond with out of date value if a "set color" sequence is immediately
762 // followed by a color request sequence.
763 let color = self.term.lock().colors()[index]
764 .unwrap_or_else(|| to_alac_rgb(get_color_at_index(index, cx.theme().as_ref())));
765 self.write_to_pty(format(color).into_bytes());
766 }
767 AlacTermEvent::ChildExit(error_code) => {
768 self.register_task_finished(Some(error_code), cx);
769 }
770 }
771 }
772
773 pub fn selection_started(&self) -> bool {
774 self.selection_phase == SelectionPhase::Selecting
775 }
776
777 fn process_terminal_event(
778 &mut self,
779 event: &InternalEvent,
780 term: &mut Term<ZedListener>,
781 window: &mut Window,
782 cx: &mut Context<Self>,
783 ) {
784 match event {
785 &InternalEvent::Resize(mut new_bounds) => {
786 new_bounds.bounds.size.height =
787 cmp::max(new_bounds.line_height, new_bounds.height());
788 new_bounds.bounds.size.width = cmp::max(new_bounds.cell_width, new_bounds.width());
789
790 self.last_content.terminal_bounds = new_bounds;
791
792 self.pty_tx.0.send(Msg::Resize(new_bounds.into())).ok();
793
794 term.resize(new_bounds);
795 }
796 InternalEvent::Clear => {
797 // Clear back buffer
798 term.clear_screen(ClearMode::Saved);
799
800 let cursor = term.grid().cursor.point;
801
802 // Clear the lines above
803 term.grid_mut().reset_region(..cursor.line);
804
805 // Copy the current line up
806 let line = term.grid()[cursor.line][..Column(term.grid().columns())]
807 .iter()
808 .cloned()
809 .enumerate()
810 .collect::<Vec<(usize, Cell)>>();
811
812 for (i, cell) in line {
813 term.grid_mut()[Line(0)][Column(i)] = cell;
814 }
815
816 // Reset the cursor
817 term.grid_mut().cursor.point =
818 AlacPoint::new(Line(0), term.grid_mut().cursor.point.column);
819 let new_cursor = term.grid().cursor.point;
820
821 // Clear the lines below the new cursor
822 if (new_cursor.line.0 as usize) < term.screen_lines() - 1 {
823 term.grid_mut().reset_region((new_cursor.line + 1)..);
824 }
825
826 cx.emit(Event::Wakeup);
827 }
828 InternalEvent::Scroll(scroll) => {
829 term.scroll_display(*scroll);
830 self.refresh_hovered_word(window);
831
832 if self.vi_mode_enabled {
833 match *scroll {
834 AlacScroll::Delta(delta) => {
835 term.vi_mode_cursor = term.vi_mode_cursor.scroll(&term, delta);
836 }
837 AlacScroll::PageUp => {
838 let lines = term.screen_lines() as i32;
839 term.vi_mode_cursor = term.vi_mode_cursor.scroll(&term, lines);
840 }
841 AlacScroll::PageDown => {
842 let lines = -(term.screen_lines() as i32);
843 term.vi_mode_cursor = term.vi_mode_cursor.scroll(&term, lines);
844 }
845 AlacScroll::Top => {
846 let point = AlacPoint::new(term.topmost_line(), Column(0));
847 term.vi_mode_cursor = ViModeCursor::new(point);
848 }
849 AlacScroll::Bottom => {
850 let point = AlacPoint::new(term.bottommost_line(), Column(0));
851 term.vi_mode_cursor = ViModeCursor::new(point);
852 }
853 }
854 if let Some(mut selection) = term.selection.take() {
855 let point = term.vi_mode_cursor.point;
856 selection.update(point, AlacDirection::Right);
857 term.selection = Some(selection);
858
859 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
860 if let Some(selection_text) = term.selection_to_string() {
861 cx.write_to_primary(ClipboardItem::new_string(selection_text));
862 }
863
864 self.selection_head = Some(point);
865 cx.emit(Event::SelectionsChanged)
866 }
867 }
868 }
869 InternalEvent::SetSelection(selection) => {
870 term.selection = selection.as_ref().map(|(sel, _)| sel.clone());
871
872 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
873 if let Some(selection_text) = term.selection_to_string() {
874 cx.write_to_primary(ClipboardItem::new_string(selection_text));
875 }
876
877 if let Some((_, head)) = selection {
878 self.selection_head = Some(*head);
879 }
880 cx.emit(Event::SelectionsChanged)
881 }
882 InternalEvent::UpdateSelection(position) => {
883 if let Some(mut selection) = term.selection.take() {
884 let (point, side) = grid_point_and_side(
885 *position,
886 self.last_content.terminal_bounds,
887 term.grid().display_offset(),
888 );
889
890 selection.update(point, side);
891 term.selection = Some(selection);
892
893 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
894 if let Some(selection_text) = term.selection_to_string() {
895 cx.write_to_primary(ClipboardItem::new_string(selection_text));
896 }
897
898 self.selection_head = Some(point);
899 cx.emit(Event::SelectionsChanged)
900 }
901 }
902
903 InternalEvent::Copy => {
904 if let Some(txt) = term.selection_to_string() {
905 cx.write_to_clipboard(ClipboardItem::new_string(txt));
906
907 let settings = TerminalSettings::get_global(cx);
908
909 if !settings.keep_selection_on_copy {
910 self.events.push_back(InternalEvent::SetSelection(None));
911 }
912 }
913 }
914 InternalEvent::ScrollToAlacPoint(point) => {
915 term.scroll_to_point(*point);
916 self.refresh_hovered_word(window);
917 }
918 InternalEvent::ToggleViMode => {
919 self.vi_mode_enabled = !self.vi_mode_enabled;
920 term.toggle_vi_mode();
921 }
922 InternalEvent::ViMotion(motion) => {
923 term.vi_motion(*motion);
924 }
925 InternalEvent::FindHyperlink(position, open) => {
926 let prev_hovered_word = self.last_content.last_hovered_word.take();
927
928 let point = grid_point(
929 *position,
930 self.last_content.terminal_bounds,
931 term.grid().display_offset(),
932 )
933 .grid_clamp(term, Boundary::Grid);
934
935 match terminal_hyperlinks::find_from_grid_point(
936 term,
937 point,
938 &mut self.hyperlink_regex_searches,
939 ) {
940 Some((maybe_url_or_path, is_url, url_match)) => {
941 let target = if is_url {
942 // Treat "file://" URLs like file paths to ensure
943 // that line numbers at the end of the path are
944 // handled correctly.
945 // file://{path} should be urldecoded, returning a urldecoded {path}
946 if let Some(path) = maybe_url_or_path.strip_prefix("file://") {
947 let decoded_path = urlencoding::decode(path)
948 .map(|decoded| decoded.into_owned())
949 .unwrap_or(path.to_owned());
950
951 MaybeNavigationTarget::PathLike(PathLikeTarget {
952 maybe_path: decoded_path,
953 terminal_dir: self.working_directory(),
954 })
955 } else {
956 MaybeNavigationTarget::Url(maybe_url_or_path.clone())
957 }
958 } else {
959 MaybeNavigationTarget::PathLike(PathLikeTarget {
960 maybe_path: maybe_url_or_path.clone(),
961 terminal_dir: self.working_directory(),
962 })
963 };
964 if *open {
965 cx.emit(Event::Open(target));
966 } else {
967 self.update_selected_word(
968 prev_hovered_word,
969 url_match,
970 maybe_url_or_path,
971 target,
972 cx,
973 );
974 }
975 }
976 None => {
977 cx.emit(Event::NewNavigationTarget(None));
978 }
979 }
980 }
981 }
982 }
983
984 fn update_selected_word(
985 &mut self,
986 prev_word: Option<HoveredWord>,
987 word_match: RangeInclusive<AlacPoint>,
988 word: String,
989 navigation_target: MaybeNavigationTarget,
990 cx: &mut Context<Self>,
991 ) {
992 if let Some(prev_word) = prev_word {
993 if prev_word.word == word && prev_word.word_match == word_match {
994 self.last_content.last_hovered_word = Some(HoveredWord {
995 word,
996 word_match,
997 id: prev_word.id,
998 });
999 return;
1000 }
1001 }
1002
1003 self.last_content.last_hovered_word = Some(HoveredWord {
1004 word,
1005 word_match,
1006 id: self.next_link_id(),
1007 });
1008 cx.emit(Event::NewNavigationTarget(Some(navigation_target)));
1009 cx.notify()
1010 }
1011
1012 fn next_link_id(&mut self) -> usize {
1013 let res = self.next_link_id;
1014 self.next_link_id = self.next_link_id.wrapping_add(1);
1015 res
1016 }
1017
1018 pub fn last_content(&self) -> &TerminalContent {
1019 &self.last_content
1020 }
1021
1022 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape) {
1023 self.term_config.default_cursor_style = cursor_shape.into();
1024 self.term.lock().set_options(self.term_config.clone());
1025 }
1026
1027 pub fn total_lines(&self) -> usize {
1028 let term = self.term.clone();
1029 let terminal = term.lock_unfair();
1030 terminal.total_lines()
1031 }
1032
1033 pub fn viewport_lines(&self) -> usize {
1034 let term = self.term.clone();
1035 let terminal = term.lock_unfair();
1036 terminal.screen_lines()
1037 }
1038
1039 //To test:
1040 //- Activate match on terminal (scrolling and selection)
1041 //- Editor search snapping behavior
1042
1043 pub fn activate_match(&mut self, index: usize) {
1044 if let Some(search_match) = self.matches.get(index).cloned() {
1045 self.set_selection(Some((make_selection(&search_match), *search_match.end())));
1046
1047 self.events
1048 .push_back(InternalEvent::ScrollToAlacPoint(*search_match.start()));
1049 }
1050 }
1051
1052 pub fn select_matches(&mut self, matches: &[RangeInclusive<AlacPoint>]) {
1053 let matches_to_select = self
1054 .matches
1055 .iter()
1056 .filter(|self_match| matches.contains(self_match))
1057 .cloned()
1058 .collect::<Vec<_>>();
1059 for match_to_select in matches_to_select {
1060 self.set_selection(Some((
1061 make_selection(&match_to_select),
1062 *match_to_select.end(),
1063 )));
1064 }
1065 }
1066
1067 pub fn select_all(&mut self) {
1068 let term = self.term.lock();
1069 let start = AlacPoint::new(term.topmost_line(), Column(0));
1070 let end = AlacPoint::new(term.bottommost_line(), term.last_column());
1071 drop(term);
1072 self.set_selection(Some((make_selection(&(start..=end)), end)));
1073 }
1074
1075 fn set_selection(&mut self, selection: Option<(Selection, AlacPoint)>) {
1076 self.events
1077 .push_back(InternalEvent::SetSelection(selection));
1078 }
1079
1080 pub fn copy(&mut self) {
1081 self.events.push_back(InternalEvent::Copy);
1082 }
1083
1084 pub fn clear(&mut self) {
1085 self.events.push_back(InternalEvent::Clear)
1086 }
1087
1088 pub fn scroll_line_up(&mut self) {
1089 self.events
1090 .push_back(InternalEvent::Scroll(AlacScroll::Delta(1)));
1091 }
1092
1093 pub fn scroll_up_by(&mut self, lines: usize) {
1094 self.events
1095 .push_back(InternalEvent::Scroll(AlacScroll::Delta(lines as i32)));
1096 }
1097
1098 pub fn scroll_line_down(&mut self) {
1099 self.events
1100 .push_back(InternalEvent::Scroll(AlacScroll::Delta(-1)));
1101 }
1102
1103 pub fn scroll_down_by(&mut self, lines: usize) {
1104 self.events
1105 .push_back(InternalEvent::Scroll(AlacScroll::Delta(-(lines as i32))));
1106 }
1107
1108 pub fn scroll_page_up(&mut self) {
1109 self.events
1110 .push_back(InternalEvent::Scroll(AlacScroll::PageUp));
1111 }
1112
1113 pub fn scroll_page_down(&mut self) {
1114 self.events
1115 .push_back(InternalEvent::Scroll(AlacScroll::PageDown));
1116 }
1117
1118 pub fn scroll_to_top(&mut self) {
1119 self.events
1120 .push_back(InternalEvent::Scroll(AlacScroll::Top));
1121 }
1122
1123 pub fn scroll_to_bottom(&mut self) {
1124 self.events
1125 .push_back(InternalEvent::Scroll(AlacScroll::Bottom));
1126 }
1127
1128 pub fn scrolled_to_top(&self) -> bool {
1129 self.last_content.scrolled_to_top
1130 }
1131
1132 pub fn scrolled_to_bottom(&self) -> bool {
1133 self.last_content.scrolled_to_bottom
1134 }
1135
1136 ///Resize the terminal and the PTY.
1137 pub fn set_size(&mut self, new_bounds: TerminalBounds) {
1138 if self.last_content.terminal_bounds != new_bounds {
1139 self.events.push_back(InternalEvent::Resize(new_bounds))
1140 }
1141 }
1142
1143 ///Write the Input payload to the tty.
1144 fn write_to_pty(&self, input: impl Into<Cow<'static, [u8]>>) {
1145 self.pty_tx.notify(input.into());
1146 }
1147
1148 pub fn input(&mut self, input: impl Into<Cow<'static, [u8]>>) {
1149 self.events
1150 .push_back(InternalEvent::Scroll(AlacScroll::Bottom));
1151 self.events.push_back(InternalEvent::SetSelection(None));
1152
1153 self.write_to_pty(input);
1154 }
1155
1156 pub fn toggle_vi_mode(&mut self) {
1157 self.events.push_back(InternalEvent::ToggleViMode);
1158 }
1159
1160 pub fn vi_motion(&mut self, keystroke: &Keystroke) {
1161 if !self.vi_mode_enabled {
1162 return;
1163 }
1164
1165 let key: Cow<'_, str> = if keystroke.modifiers.shift {
1166 Cow::Owned(keystroke.key.to_uppercase())
1167 } else {
1168 Cow::Borrowed(keystroke.key.as_str())
1169 };
1170
1171 let motion: Option<ViMotion> = match key.as_ref() {
1172 "h" | "left" => Some(ViMotion::Left),
1173 "j" | "down" => Some(ViMotion::Down),
1174 "k" | "up" => Some(ViMotion::Up),
1175 "l" | "right" => Some(ViMotion::Right),
1176 "w" => Some(ViMotion::WordRight),
1177 "b" if !keystroke.modifiers.control => Some(ViMotion::WordLeft),
1178 "e" => Some(ViMotion::WordRightEnd),
1179 "%" => Some(ViMotion::Bracket),
1180 "$" => Some(ViMotion::Last),
1181 "0" => Some(ViMotion::First),
1182 "^" => Some(ViMotion::FirstOccupied),
1183 "H" => Some(ViMotion::High),
1184 "M" => Some(ViMotion::Middle),
1185 "L" => Some(ViMotion::Low),
1186 _ => None,
1187 };
1188
1189 if let Some(motion) = motion {
1190 let cursor = self.last_content.cursor.point;
1191 let cursor_pos = Point {
1192 x: cursor.column.0 as f32 * self.last_content.terminal_bounds.cell_width,
1193 y: cursor.line.0 as f32 * self.last_content.terminal_bounds.line_height,
1194 };
1195 self.events
1196 .push_back(InternalEvent::UpdateSelection(cursor_pos));
1197 self.events.push_back(InternalEvent::ViMotion(motion));
1198 return;
1199 }
1200
1201 let scroll_motion = match key.as_ref() {
1202 "g" => Some(AlacScroll::Top),
1203 "G" => Some(AlacScroll::Bottom),
1204 "b" if keystroke.modifiers.control => Some(AlacScroll::PageUp),
1205 "f" if keystroke.modifiers.control => Some(AlacScroll::PageDown),
1206 "d" if keystroke.modifiers.control => {
1207 let amount = self.last_content.terminal_bounds.line_height().to_f64() as i32 / 2;
1208 Some(AlacScroll::Delta(-amount))
1209 }
1210 "u" if keystroke.modifiers.control => {
1211 let amount = self.last_content.terminal_bounds.line_height().to_f64() as i32 / 2;
1212 Some(AlacScroll::Delta(amount))
1213 }
1214 _ => None,
1215 };
1216
1217 if let Some(scroll_motion) = scroll_motion {
1218 self.events.push_back(InternalEvent::Scroll(scroll_motion));
1219 return;
1220 }
1221
1222 match key.as_ref() {
1223 "v" => {
1224 let point = self.last_content.cursor.point;
1225 let selection_type = SelectionType::Simple;
1226 let side = AlacDirection::Right;
1227 let selection = Selection::new(selection_type, point, side);
1228 self.events
1229 .push_back(InternalEvent::SetSelection(Some((selection, point))));
1230 return;
1231 }
1232
1233 "escape" => {
1234 self.events.push_back(InternalEvent::SetSelection(None));
1235 return;
1236 }
1237
1238 "y" => {
1239 self.events.push_back(InternalEvent::Copy);
1240 self.events.push_back(InternalEvent::SetSelection(None));
1241 return;
1242 }
1243
1244 "i" => {
1245 self.scroll_to_bottom();
1246 self.toggle_vi_mode();
1247 return;
1248 }
1249 _ => {}
1250 }
1251 }
1252
1253 pub fn try_keystroke(&mut self, keystroke: &Keystroke, alt_is_meta: bool) -> bool {
1254 if self.vi_mode_enabled {
1255 self.vi_motion(keystroke);
1256 return true;
1257 }
1258
1259 // Keep default terminal behavior
1260 let esc = to_esc_str(keystroke, &self.last_content.mode, alt_is_meta);
1261 if let Some(esc) = esc {
1262 match esc {
1263 Cow::Borrowed(string) => self.input(string.as_bytes()),
1264 Cow::Owned(string) => self.input(string.into_bytes()),
1265 };
1266 true
1267 } else {
1268 false
1269 }
1270 }
1271
1272 pub fn try_modifiers_change(
1273 &mut self,
1274 modifiers: &Modifiers,
1275 window: &Window,
1276 cx: &mut Context<Self>,
1277 ) {
1278 if self
1279 .last_content
1280 .terminal_bounds
1281 .bounds
1282 .contains(&window.mouse_position())
1283 && modifiers.secondary()
1284 {
1285 self.refresh_hovered_word(window);
1286 }
1287 cx.notify();
1288 }
1289
1290 ///Paste text into the terminal
1291 pub fn paste(&mut self, text: &str) {
1292 let paste_text = if self.last_content.mode.contains(TermMode::BRACKETED_PASTE) {
1293 format!("{}{}{}", "\x1b[200~", text.replace('\x1b', ""), "\x1b[201~")
1294 } else {
1295 text.replace("\r\n", "\r").replace('\n', "\r")
1296 };
1297
1298 self.input(paste_text.into_bytes());
1299 }
1300
1301 pub fn sync(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1302 let term = self.term.clone();
1303 let mut terminal = term.lock_unfair();
1304 //Note that the ordering of events matters for event processing
1305 while let Some(e) = self.events.pop_front() {
1306 self.process_terminal_event(&e, &mut terminal, window, cx)
1307 }
1308
1309 self.last_content = Self::make_content(&terminal, &self.last_content);
1310 }
1311
1312 fn make_content(term: &Term<ZedListener>, last_content: &TerminalContent) -> TerminalContent {
1313 let content = term.renderable_content();
1314
1315 // Pre-allocate with estimated size to reduce reallocations
1316 let estimated_size = content.display_iter.size_hint().0;
1317 let mut cells = Vec::with_capacity(estimated_size);
1318
1319 cells.extend(content.display_iter.map(|ic| IndexedCell {
1320 point: ic.point,
1321 cell: ic.cell.clone(),
1322 }));
1323
1324 let selection_text = if content.selection.is_some() {
1325 term.selection_to_string()
1326 } else {
1327 None
1328 };
1329
1330 TerminalContent {
1331 cells,
1332 mode: content.mode,
1333 display_offset: content.display_offset,
1334 selection_text,
1335 selection: content.selection,
1336 cursor: content.cursor,
1337 cursor_char: term.grid()[content.cursor.point].c,
1338 terminal_bounds: last_content.terminal_bounds,
1339 last_hovered_word: last_content.last_hovered_word.clone(),
1340 scrolled_to_top: content.display_offset == term.history_size(),
1341 scrolled_to_bottom: content.display_offset == 0,
1342 }
1343 }
1344
1345 pub fn get_content(&self) -> String {
1346 let term = self.term.lock_unfair();
1347 let start = AlacPoint::new(term.topmost_line(), Column(0));
1348 let end = AlacPoint::new(term.bottommost_line(), term.last_column());
1349 term.bounds_to_string(start, end)
1350 }
1351
1352 pub fn last_n_non_empty_lines(&self, n: usize) -> Vec<String> {
1353 let term = self.term.clone();
1354 let terminal = term.lock_unfair();
1355 let grid = terminal.grid();
1356 let mut lines = Vec::new();
1357
1358 let mut current_line = grid.bottommost_line().0;
1359 let topmost_line = grid.topmost_line().0;
1360
1361 while current_line >= topmost_line && lines.len() < n {
1362 let logical_line_start = self.find_logical_line_start(grid, current_line, topmost_line);
1363 let logical_line = self.construct_logical_line(grid, logical_line_start, current_line);
1364
1365 if let Some(line) = self.process_line(logical_line) {
1366 lines.push(line);
1367 }
1368
1369 // Move to the line above the start of the current logical line
1370 current_line = logical_line_start - 1;
1371 }
1372
1373 lines.reverse();
1374 lines
1375 }
1376
1377 fn find_logical_line_start(&self, grid: &Grid<Cell>, current: i32, topmost: i32) -> i32 {
1378 let mut line_start = current;
1379 while line_start > topmost {
1380 let prev_line = Line(line_start - 1);
1381 let last_cell = &grid[prev_line][Column(grid.columns() - 1)];
1382 if !last_cell.flags.contains(Flags::WRAPLINE) {
1383 break;
1384 }
1385 line_start -= 1;
1386 }
1387 line_start
1388 }
1389
1390 fn construct_logical_line(&self, grid: &Grid<Cell>, start: i32, end: i32) -> String {
1391 let mut logical_line = String::new();
1392 for row in start..=end {
1393 let grid_row = &grid[Line(row)];
1394 logical_line.push_str(&row_to_string(grid_row));
1395 }
1396 logical_line
1397 }
1398
1399 fn process_line(&self, line: String) -> Option<String> {
1400 let trimmed = line.trim_end().to_string();
1401 if !trimmed.is_empty() {
1402 Some(trimmed)
1403 } else {
1404 None
1405 }
1406 }
1407
1408 pub fn focus_in(&self) {
1409 if self.last_content.mode.contains(TermMode::FOCUS_IN_OUT) {
1410 self.write_to_pty("\x1b[I".as_bytes());
1411 }
1412 }
1413
1414 pub fn focus_out(&mut self) {
1415 if self.last_content.mode.contains(TermMode::FOCUS_IN_OUT) {
1416 self.write_to_pty("\x1b[O".as_bytes());
1417 }
1418 }
1419
1420 pub fn mouse_changed(&mut self, point: AlacPoint, side: AlacDirection) -> bool {
1421 match self.last_mouse {
1422 Some((old_point, old_side)) => {
1423 if old_point == point && old_side == side {
1424 false
1425 } else {
1426 self.last_mouse = Some((point, side));
1427 true
1428 }
1429 }
1430 None => {
1431 self.last_mouse = Some((point, side));
1432 true
1433 }
1434 }
1435 }
1436
1437 pub fn mouse_mode(&self, shift: bool) -> bool {
1438 self.last_content.mode.intersects(TermMode::MOUSE_MODE) && !shift
1439 }
1440
1441 pub fn mouse_move(&mut self, e: &MouseMoveEvent, cx: &mut Context<Self>) {
1442 let position = e.position - self.last_content.terminal_bounds.bounds.origin;
1443 if self.mouse_mode(e.modifiers.shift) {
1444 let (point, side) = grid_point_and_side(
1445 position,
1446 self.last_content.terminal_bounds,
1447 self.last_content.display_offset,
1448 );
1449
1450 if self.mouse_changed(point, side) {
1451 if let Some(bytes) =
1452 mouse_moved_report(point, e.pressed_button, e.modifiers, self.last_content.mode)
1453 {
1454 self.pty_tx.notify(bytes);
1455 }
1456 }
1457 } else if e.modifiers.secondary() {
1458 self.word_from_position(e.position);
1459 }
1460 cx.notify();
1461 }
1462
1463 fn word_from_position(&mut self, position: Point<Pixels>) {
1464 if self.selection_phase == SelectionPhase::Selecting {
1465 self.last_content.last_hovered_word = None;
1466 } else if self.last_content.terminal_bounds.bounds.contains(&position) {
1467 // Throttle hyperlink searches to avoid excessive processing
1468 let now = Instant::now();
1469 let should_search = if let Some(last_pos) = self.last_hyperlink_search_position {
1470 // Only search if mouse moved significantly or enough time passed
1471 let distance_moved =
1472 ((position.x - last_pos.x).abs() + (position.y - last_pos.y).abs()) > px(5.0);
1473 let time_elapsed = now.duration_since(self.last_mouse_move_time).as_millis() > 100;
1474 distance_moved || time_elapsed
1475 } else {
1476 true
1477 };
1478
1479 if should_search {
1480 self.last_mouse_move_time = now;
1481 self.last_hyperlink_search_position = Some(position);
1482 self.events.push_back(InternalEvent::FindHyperlink(
1483 position - self.last_content.terminal_bounds.bounds.origin,
1484 false,
1485 ));
1486 }
1487 } else {
1488 self.last_content.last_hovered_word = None;
1489 }
1490 }
1491
1492 pub fn select_word_at_event_position(&mut self, e: &MouseDownEvent) {
1493 let position = e.position - self.last_content.terminal_bounds.bounds.origin;
1494 let (point, side) = grid_point_and_side(
1495 position,
1496 self.last_content.terminal_bounds,
1497 self.last_content.display_offset,
1498 );
1499 let selection = Selection::new(SelectionType::Semantic, point, side);
1500 self.events
1501 .push_back(InternalEvent::SetSelection(Some((selection, point))));
1502 }
1503
1504 pub fn mouse_drag(
1505 &mut self,
1506 e: &MouseMoveEvent,
1507 region: Bounds<Pixels>,
1508 cx: &mut Context<Self>,
1509 ) {
1510 let position = e.position - self.last_content.terminal_bounds.bounds.origin;
1511 if !self.mouse_mode(e.modifiers.shift) {
1512 self.selection_phase = SelectionPhase::Selecting;
1513 // Alacritty has the same ordering, of first updating the selection
1514 // then scrolling 15ms later
1515 self.events
1516 .push_back(InternalEvent::UpdateSelection(position));
1517
1518 // Doesn't make sense to scroll the alt screen
1519 if !self.last_content.mode.contains(TermMode::ALT_SCREEN) {
1520 let scroll_lines = match self.drag_line_delta(e, region) {
1521 Some(value) => value,
1522 None => return,
1523 };
1524
1525 self.events
1526 .push_back(InternalEvent::Scroll(AlacScroll::Delta(scroll_lines)));
1527 }
1528
1529 cx.notify();
1530 }
1531 }
1532
1533 fn drag_line_delta(&self, e: &MouseMoveEvent, region: Bounds<Pixels>) -> Option<i32> {
1534 let top = region.origin.y;
1535 let bottom = region.bottom_left().y;
1536
1537 let scroll_lines = if e.position.y < top {
1538 let scroll_delta = (top - e.position.y).pow(1.1);
1539 (scroll_delta / self.last_content.terminal_bounds.line_height).ceil() as i32
1540 } else if e.position.y > bottom {
1541 let scroll_delta = -((e.position.y - bottom).pow(1.1));
1542 (scroll_delta / self.last_content.terminal_bounds.line_height).floor() as i32
1543 } else {
1544 return None;
1545 };
1546
1547 Some(scroll_lines.clamp(-3, 3))
1548 }
1549
1550 pub fn mouse_down(&mut self, e: &MouseDownEvent, _cx: &mut Context<Self>) {
1551 let position = e.position - self.last_content.terminal_bounds.bounds.origin;
1552 let point = grid_point(
1553 position,
1554 self.last_content.terminal_bounds,
1555 self.last_content.display_offset,
1556 );
1557
1558 if self.mouse_mode(e.modifiers.shift) {
1559 if let Some(bytes) =
1560 mouse_button_report(point, e.button, e.modifiers, true, self.last_content.mode)
1561 {
1562 self.pty_tx.notify(bytes);
1563 }
1564 } else {
1565 match e.button {
1566 MouseButton::Left => {
1567 let (point, side) = grid_point_and_side(
1568 position,
1569 self.last_content.terminal_bounds,
1570 self.last_content.display_offset,
1571 );
1572
1573 let selection_type = match e.click_count {
1574 0 => return, //This is a release
1575 1 => Some(SelectionType::Simple),
1576 2 => Some(SelectionType::Semantic),
1577 3 => Some(SelectionType::Lines),
1578 _ => None,
1579 };
1580
1581 if selection_type == Some(SelectionType::Simple) && e.modifiers.shift {
1582 self.events
1583 .push_back(InternalEvent::UpdateSelection(position));
1584 return;
1585 }
1586
1587 let selection = selection_type
1588 .map(|selection_type| Selection::new(selection_type, point, side));
1589
1590 if let Some(sel) = selection {
1591 self.events
1592 .push_back(InternalEvent::SetSelection(Some((sel, point))));
1593 }
1594 }
1595 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1596 MouseButton::Middle => {
1597 if let Some(item) = _cx.read_from_primary() {
1598 let text = item.text().unwrap_or_default().to_string();
1599 self.input(text.into_bytes());
1600 }
1601 }
1602 _ => {}
1603 }
1604 }
1605 }
1606
1607 pub fn mouse_up(&mut self, e: &MouseUpEvent, cx: &Context<Self>) {
1608 let setting = TerminalSettings::get_global(cx);
1609
1610 let position = e.position - self.last_content.terminal_bounds.bounds.origin;
1611 if self.mouse_mode(e.modifiers.shift) {
1612 let point = grid_point(
1613 position,
1614 self.last_content.terminal_bounds,
1615 self.last_content.display_offset,
1616 );
1617
1618 if let Some(bytes) =
1619 mouse_button_report(point, e.button, e.modifiers, false, self.last_content.mode)
1620 {
1621 self.pty_tx.notify(bytes);
1622 }
1623 } else {
1624 if e.button == MouseButton::Left && setting.copy_on_select {
1625 self.copy();
1626 }
1627
1628 //Hyperlinks
1629 if self.selection_phase == SelectionPhase::Ended {
1630 let mouse_cell_index =
1631 content_index_for_mouse(position, &self.last_content.terminal_bounds);
1632 if let Some(link) = self.last_content.cells[mouse_cell_index].hyperlink() {
1633 cx.open_url(link.uri());
1634 } else if e.modifiers.secondary() {
1635 self.events
1636 .push_back(InternalEvent::FindHyperlink(position, true));
1637 }
1638 }
1639 }
1640
1641 self.selection_phase = SelectionPhase::Ended;
1642 self.last_mouse = None;
1643 }
1644
1645 ///Scroll the terminal
1646 pub fn scroll_wheel(&mut self, e: &ScrollWheelEvent) {
1647 let mouse_mode = self.mouse_mode(e.shift);
1648
1649 if let Some(scroll_lines) = self.determine_scroll_lines(e, mouse_mode) {
1650 if mouse_mode {
1651 let point = grid_point(
1652 e.position - self.last_content.terminal_bounds.bounds.origin,
1653 self.last_content.terminal_bounds,
1654 self.last_content.display_offset,
1655 );
1656
1657 if let Some(scrolls) = scroll_report(point, scroll_lines, e, self.last_content.mode)
1658 {
1659 for scroll in scrolls {
1660 self.pty_tx.notify(scroll);
1661 }
1662 };
1663 } else if self
1664 .last_content
1665 .mode
1666 .contains(TermMode::ALT_SCREEN | TermMode::ALTERNATE_SCROLL)
1667 && !e.shift
1668 {
1669 self.pty_tx.notify(alt_scroll(scroll_lines))
1670 } else if scroll_lines != 0 {
1671 let scroll = AlacScroll::Delta(scroll_lines);
1672
1673 self.events.push_back(InternalEvent::Scroll(scroll));
1674 }
1675 }
1676 }
1677
1678 fn refresh_hovered_word(&mut self, window: &Window) {
1679 self.word_from_position(window.mouse_position());
1680 }
1681
1682 fn determine_scroll_lines(&mut self, e: &ScrollWheelEvent, mouse_mode: bool) -> Option<i32> {
1683 let scroll_multiplier = if mouse_mode { 1. } else { SCROLL_MULTIPLIER };
1684 let line_height = self.last_content.terminal_bounds.line_height;
1685 match e.touch_phase {
1686 /* Reset scroll state on started */
1687 TouchPhase::Started => {
1688 self.scroll_px = px(0.);
1689 None
1690 }
1691 /* Calculate the appropriate scroll lines */
1692 TouchPhase::Moved => {
1693 let old_offset = (self.scroll_px / line_height) as i32;
1694
1695 self.scroll_px += e.delta.pixel_delta(line_height).y * scroll_multiplier;
1696
1697 let new_offset = (self.scroll_px / line_height) as i32;
1698
1699 // Whenever we hit the edges, reset our stored scroll to 0
1700 // so we can respond to changes in direction quickly
1701 self.scroll_px %= self.last_content.terminal_bounds.height();
1702
1703 Some(new_offset - old_offset)
1704 }
1705 TouchPhase::Ended => None,
1706 }
1707 }
1708
1709 pub fn find_matches(
1710 &self,
1711 mut searcher: RegexSearch,
1712 cx: &Context<Self>,
1713 ) -> Task<Vec<RangeInclusive<AlacPoint>>> {
1714 let term = self.term.clone();
1715 cx.background_spawn(async move {
1716 let term = term.lock();
1717
1718 all_search_matches(&term, &mut searcher).collect()
1719 })
1720 }
1721
1722 pub fn working_directory(&self) -> Option<PathBuf> {
1723 if self.is_ssh_terminal {
1724 // We can't yet reliably detect the working directory of a shell on the
1725 // SSH host. Until we can do that, it doesn't make sense to display
1726 // the working directory on the client and persist that.
1727 None
1728 } else {
1729 self.client_side_working_directory()
1730 }
1731 }
1732
1733 /// Returns the working directory of the process that's connected to the PTY.
1734 /// That means it returns the working directory of the local shell or program
1735 /// that's running inside the terminal.
1736 ///
1737 /// This does *not* return the working directory of the shell that runs on the
1738 /// remote host, in case Zed is connected to a remote host.
1739 fn client_side_working_directory(&self) -> Option<PathBuf> {
1740 self.pty_info
1741 .current
1742 .as_ref()
1743 .map(|process| process.cwd.clone())
1744 }
1745
1746 pub fn title(&self, truncate: bool) -> String {
1747 const MAX_CHARS: usize = 25;
1748 match &self.task {
1749 Some(task_state) => {
1750 if truncate {
1751 truncate_and_trailoff(&task_state.label, MAX_CHARS)
1752 } else {
1753 task_state.full_label.clone()
1754 }
1755 }
1756 None => self
1757 .title_override
1758 .as_ref()
1759 .map(|title_override| title_override.to_string())
1760 .unwrap_or_else(|| {
1761 self.pty_info
1762 .current
1763 .as_ref()
1764 .map(|fpi| {
1765 let process_file = fpi
1766 .cwd
1767 .file_name()
1768 .map(|name| name.to_string_lossy().to_string())
1769 .unwrap_or_default();
1770
1771 let argv = fpi.argv.as_slice();
1772 let process_name = format!(
1773 "{}{}",
1774 fpi.name,
1775 if !argv.is_empty() {
1776 format!(" {}", (argv[1..]).join(" "))
1777 } else {
1778 "".to_string()
1779 }
1780 );
1781 let (process_file, process_name) = if truncate {
1782 (
1783 truncate_and_trailoff(&process_file, MAX_CHARS),
1784 truncate_and_trailoff(&process_name, MAX_CHARS),
1785 )
1786 } else {
1787 (process_file, process_name)
1788 };
1789 format!("{process_file} — {process_name}")
1790 })
1791 .unwrap_or_else(|| "Terminal".to_string())
1792 }),
1793 }
1794 }
1795
1796 pub fn task(&self) -> Option<&TaskState> {
1797 self.task.as_ref()
1798 }
1799
1800 pub fn wait_for_completed_task(&self, cx: &App) -> Task<Option<ExitStatus>> {
1801 if let Some(task) = self.task() {
1802 if task.status == TaskStatus::Running {
1803 let completion_receiver = task.completion_rx.clone();
1804 return cx.spawn(async move |_| completion_receiver.recv().await.ok().flatten());
1805 } else if let Ok(status) = task.completion_rx.try_recv() {
1806 return Task::ready(status);
1807 }
1808 }
1809 Task::ready(None)
1810 }
1811
1812 fn register_task_finished(&mut self, error_code: Option<i32>, cx: &mut Context<Terminal>) {
1813 let e: Option<ExitStatus> = error_code.map(|code| {
1814 #[cfg(unix)]
1815 {
1816 return std::os::unix::process::ExitStatusExt::from_raw(code);
1817 }
1818 #[cfg(windows)]
1819 {
1820 return std::os::windows::process::ExitStatusExt::from_raw(code as u32);
1821 }
1822 });
1823
1824 self.completion_tx.try_send(e).ok();
1825 let task = match &mut self.task {
1826 Some(task) => task,
1827 None => {
1828 if error_code.is_none() {
1829 cx.emit(Event::CloseTerminal);
1830 }
1831 return;
1832 }
1833 };
1834 if task.status != TaskStatus::Running {
1835 return;
1836 }
1837 match error_code {
1838 Some(error_code) => {
1839 task.status.register_task_exit(error_code);
1840 }
1841 None => {
1842 task.status.register_terminal_exit();
1843 }
1844 };
1845
1846 let (finished_successfully, task_line, command_line) = task_summary(task, error_code);
1847 let mut lines_to_show = Vec::new();
1848 if task.show_summary {
1849 lines_to_show.push(task_line.as_str());
1850 }
1851 if task.show_command {
1852 lines_to_show.push(command_line.as_str());
1853 }
1854
1855 if !lines_to_show.is_empty() {
1856 // SAFETY: the invocation happens on non `TaskStatus::Running` tasks, once,
1857 // after either `AlacTermEvent::Exit` or `AlacTermEvent::ChildExit` events that are spawned
1858 // when Zed task finishes and no more output is made.
1859 // After the task summary is output once, no more text is appended to the terminal.
1860 unsafe { append_text_to_term(&mut self.term.lock(), &lines_to_show) };
1861 }
1862
1863 match task.hide {
1864 HideStrategy::Never => {}
1865 HideStrategy::Always => {
1866 cx.emit(Event::CloseTerminal);
1867 }
1868 HideStrategy::OnSuccess => {
1869 if finished_successfully {
1870 cx.emit(Event::CloseTerminal);
1871 }
1872 }
1873 }
1874 }
1875
1876 pub fn vi_mode_enabled(&self) -> bool {
1877 self.vi_mode_enabled
1878 }
1879}
1880
1881// Helper function to convert a grid row to a string
1882pub fn row_to_string(row: &Row<Cell>) -> String {
1883 row[..Column(row.len())]
1884 .iter()
1885 .map(|cell| cell.c)
1886 .collect::<String>()
1887}
1888
1889const TASK_DELIMITER: &str = "⏵ ";
1890fn task_summary(task: &TaskState, error_code: Option<i32>) -> (bool, String, String) {
1891 let escaped_full_label = task.full_label.replace("\r\n", "\r").replace('\n', "\r");
1892 let (success, task_line) = match error_code {
1893 Some(0) => (
1894 true,
1895 format!("{TASK_DELIMITER}Task `{escaped_full_label}` finished successfully"),
1896 ),
1897 Some(error_code) => (
1898 false,
1899 format!(
1900 "{TASK_DELIMITER}Task `{escaped_full_label}` finished with non-zero error code: {error_code}"
1901 ),
1902 ),
1903 None => (
1904 false,
1905 format!("{TASK_DELIMITER}Task `{escaped_full_label}` finished"),
1906 ),
1907 };
1908 let escaped_command_label = task.command_label.replace("\r\n", "\r").replace('\n', "\r");
1909 let command_line = format!("{TASK_DELIMITER}Command: {escaped_command_label}");
1910 (success, task_line, command_line)
1911}
1912
1913/// Appends a stringified task summary to the terminal, after its output.
1914///
1915/// SAFETY: This function should only be called after terminal's PTY is no longer alive.
1916/// New text being added to the terminal here, uses "less public" APIs,
1917/// which are not maintaining the entire terminal state intact.
1918///
1919///
1920/// The library
1921///
1922/// * does not increment inner grid cursor's _lines_ on `input` calls
1923/// (but displaying the lines correctly and incrementing cursor's columns)
1924///
1925/// * ignores `\n` and \r` character input, requiring the `newline` call instead
1926///
1927/// * does not alter grid state after `newline` call
1928/// so its `bottommost_line` is always the same additions, and
1929/// the cursor's `point` is not updated to the new line and column values
1930///
1931/// * ??? there could be more consequences, and any further "proper" streaming from the PTY might bug and/or panic.
1932/// Still, subsequent `append_text_to_term` invocations are possible and display the contents correctly.
1933///
1934/// Despite the quirks, this is the simplest approach to appending text to the terminal: its alternative, `grid_mut` manipulations,
1935/// do not properly set the scrolling state and display odd text after appending; also those manipulations are more tedious and error-prone.
1936/// The function achieves proper display and scrolling capabilities, at a cost of grid state not properly synchronized.
1937/// This is enough for printing moderately-sized texts like task summaries, but might break or perform poorly for larger texts.
1938unsafe fn append_text_to_term(term: &mut Term<ZedListener>, text_lines: &[&str]) {
1939 term.newline();
1940 term.grid_mut().cursor.point.column = Column(0);
1941 for line in text_lines {
1942 for c in line.chars() {
1943 term.input(c);
1944 }
1945 term.newline();
1946 term.grid_mut().cursor.point.column = Column(0);
1947 }
1948}
1949
1950impl Drop for Terminal {
1951 fn drop(&mut self) {
1952 self.pty_tx.0.send(Msg::Shutdown).ok();
1953 }
1954}
1955
1956impl EventEmitter<Event> for Terminal {}
1957
1958fn make_selection(range: &RangeInclusive<AlacPoint>) -> Selection {
1959 let mut selection = Selection::new(SelectionType::Simple, *range.start(), AlacDirection::Left);
1960 selection.update(*range.end(), AlacDirection::Right);
1961 selection
1962}
1963
1964fn all_search_matches<'a, T>(
1965 term: &'a Term<T>,
1966 regex: &'a mut RegexSearch,
1967) -> impl Iterator<Item = Match> + 'a {
1968 let start = AlacPoint::new(term.grid().topmost_line(), Column(0));
1969 let end = AlacPoint::new(term.grid().bottommost_line(), term.grid().last_column());
1970 RegexIter::new(start, end, AlacDirection::Right, term, regex)
1971}
1972
1973fn content_index_for_mouse(pos: Point<Pixels>, terminal_bounds: &TerminalBounds) -> usize {
1974 let col = (pos.x / terminal_bounds.cell_width()).round() as usize;
1975 let clamped_col = min(col, terminal_bounds.columns() - 1);
1976 let row = (pos.y / terminal_bounds.line_height()).round() as usize;
1977 let clamped_row = min(row, terminal_bounds.screen_lines() - 1);
1978 clamped_row * terminal_bounds.columns() + clamped_col
1979}
1980
1981/// Converts an 8 bit ANSI color to its GPUI equivalent.
1982/// Accepts `usize` for compatibility with the `alacritty::Colors` interface,
1983/// Other than that use case, should only be called with values in the `[0,255]` range
1984pub fn get_color_at_index(index: usize, theme: &Theme) -> Hsla {
1985 let colors = theme.colors();
1986
1987 match index {
1988 // 0-15 are the same as the named colors above
1989 0 => colors.terminal_ansi_black,
1990 1 => colors.terminal_ansi_red,
1991 2 => colors.terminal_ansi_green,
1992 3 => colors.terminal_ansi_yellow,
1993 4 => colors.terminal_ansi_blue,
1994 5 => colors.terminal_ansi_magenta,
1995 6 => colors.terminal_ansi_cyan,
1996 7 => colors.terminal_ansi_white,
1997 8 => colors.terminal_ansi_bright_black,
1998 9 => colors.terminal_ansi_bright_red,
1999 10 => colors.terminal_ansi_bright_green,
2000 11 => colors.terminal_ansi_bright_yellow,
2001 12 => colors.terminal_ansi_bright_blue,
2002 13 => colors.terminal_ansi_bright_magenta,
2003 14 => colors.terminal_ansi_bright_cyan,
2004 15 => colors.terminal_ansi_bright_white,
2005 // 16-231 are a 6x6x6 RGB color cube, mapped to 0-255 using steps defined by XTerm.
2006 // See: https://github.com/xterm-x11/xterm-snapshots/blob/master/256colres.pl
2007 16..=231 => {
2008 let (r, g, b) = rgb_for_index(index as u8);
2009 rgba_color(
2010 if r == 0 { 0 } else { r * 40 + 55 },
2011 if g == 0 { 0 } else { g * 40 + 55 },
2012 if b == 0 { 0 } else { b * 40 + 55 },
2013 )
2014 }
2015 // 232-255 are a 24-step grayscale ramp from (8, 8, 8) to (238, 238, 238).
2016 232..=255 => {
2017 let i = index as u8 - 232; // Align index to 0..24
2018 let value = i * 10 + 8;
2019 rgba_color(value, value, value)
2020 }
2021 // For compatibility with the alacritty::Colors interface
2022 // See: https://github.com/alacritty/alacritty/blob/master/alacritty_terminal/src/term/color.rs
2023 256 => colors.terminal_foreground,
2024 257 => colors.terminal_background,
2025 258 => theme.players().local().cursor,
2026 259 => colors.terminal_ansi_dim_black,
2027 260 => colors.terminal_ansi_dim_red,
2028 261 => colors.terminal_ansi_dim_green,
2029 262 => colors.terminal_ansi_dim_yellow,
2030 263 => colors.terminal_ansi_dim_blue,
2031 264 => colors.terminal_ansi_dim_magenta,
2032 265 => colors.terminal_ansi_dim_cyan,
2033 266 => colors.terminal_ansi_dim_white,
2034 267 => colors.terminal_bright_foreground,
2035 268 => colors.terminal_ansi_black, // 'Dim Background', non-standard color
2036
2037 _ => black(),
2038 }
2039}
2040
2041/// Generates the RGB channels in [0, 5] for a given index into the 6x6x6 ANSI color cube.
2042/// See: [8 bit ANSI color](https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit).
2043///
2044/// Wikipedia gives a formula for calculating the index for a given color:
2045///
2046/// ```
2047/// index = 16 + 36 × r + 6 × g + b (0 ≤ r, g, b ≤ 5)
2048/// ```
2049///
2050/// This function does the reverse, calculating the `r`, `g`, and `b` components from a given index.
2051fn rgb_for_index(i: u8) -> (u8, u8, u8) {
2052 debug_assert!((16..=231).contains(&i));
2053 let i = i - 16;
2054 let r = (i - (i % 36)) / 36;
2055 let g = ((i % 36) - (i % 6)) / 6;
2056 let b = (i % 36) % 6;
2057 (r, g, b)
2058}
2059
2060pub fn rgba_color(r: u8, g: u8, b: u8) -> Hsla {
2061 Rgba {
2062 r: (r as f32 / 255.),
2063 g: (g as f32 / 255.),
2064 b: (b as f32 / 255.),
2065 a: 1.,
2066 }
2067 .into()
2068}
2069
2070#[cfg(test)]
2071mod tests {
2072 use alacritty_terminal::{
2073 index::{Column, Line, Point as AlacPoint},
2074 term::cell::Cell,
2075 };
2076 use gpui::{Pixels, Point, bounds, point, size};
2077 use rand::{Rng, distributions::Alphanumeric, rngs::ThreadRng, thread_rng};
2078
2079 use crate::{
2080 IndexedCell, TerminalBounds, TerminalContent, content_index_for_mouse, rgb_for_index,
2081 };
2082
2083 #[test]
2084 fn test_rgb_for_index() {
2085 // Test every possible value in the color cube.
2086 for i in 16..=231 {
2087 let (r, g, b) = rgb_for_index(i);
2088 assert_eq!(i, 16 + 36 * r + 6 * g + b);
2089 }
2090 }
2091
2092 #[test]
2093 fn test_mouse_to_cell_test() {
2094 let mut rng = thread_rng();
2095 const ITERATIONS: usize = 10;
2096 const PRECISION: usize = 1000;
2097
2098 for _ in 0..ITERATIONS {
2099 let viewport_cells = rng.gen_range(15..20);
2100 let cell_size = rng.gen_range(5 * PRECISION..20 * PRECISION) as f32 / PRECISION as f32;
2101
2102 let size = crate::TerminalBounds {
2103 cell_width: Pixels::from(cell_size),
2104 line_height: Pixels::from(cell_size),
2105 bounds: bounds(
2106 Point::default(),
2107 size(
2108 Pixels::from(cell_size * (viewport_cells as f32)),
2109 Pixels::from(cell_size * (viewport_cells as f32)),
2110 ),
2111 ),
2112 };
2113
2114 let cells = get_cells(size, &mut rng);
2115 let content = convert_cells_to_content(size, &cells);
2116
2117 for row in 0..(viewport_cells - 1) {
2118 let row = row as usize;
2119 for col in 0..(viewport_cells - 1) {
2120 let col = col as usize;
2121
2122 let row_offset = rng.gen_range(0..PRECISION) as f32 / PRECISION as f32;
2123 let col_offset = rng.gen_range(0..PRECISION) as f32 / PRECISION as f32;
2124
2125 let mouse_pos = point(
2126 Pixels::from(col as f32 * cell_size + col_offset),
2127 Pixels::from(row as f32 * cell_size + row_offset),
2128 );
2129
2130 let content_index =
2131 content_index_for_mouse(mouse_pos, &content.terminal_bounds);
2132 let mouse_cell = content.cells[content_index].c;
2133 let real_cell = cells[row][col];
2134
2135 assert_eq!(mouse_cell, real_cell);
2136 }
2137 }
2138 }
2139 }
2140
2141 #[test]
2142 fn test_mouse_to_cell_clamp() {
2143 let mut rng = thread_rng();
2144
2145 let size = crate::TerminalBounds {
2146 cell_width: Pixels::from(10.),
2147 line_height: Pixels::from(10.),
2148 bounds: bounds(
2149 Point::default(),
2150 size(Pixels::from(100.), Pixels::from(100.)),
2151 ),
2152 };
2153
2154 let cells = get_cells(size, &mut rng);
2155 let content = convert_cells_to_content(size, &cells);
2156
2157 assert_eq!(
2158 content.cells[content_index_for_mouse(
2159 point(Pixels::from(-10.), Pixels::from(-10.)),
2160 &content.terminal_bounds,
2161 )]
2162 .c,
2163 cells[0][0]
2164 );
2165 assert_eq!(
2166 content.cells[content_index_for_mouse(
2167 point(Pixels::from(1000.), Pixels::from(1000.)),
2168 &content.terminal_bounds,
2169 )]
2170 .c,
2171 cells[9][9]
2172 );
2173 }
2174
2175 fn get_cells(size: TerminalBounds, rng: &mut ThreadRng) -> Vec<Vec<char>> {
2176 let mut cells = Vec::new();
2177
2178 for _ in 0..((size.height() / size.line_height()) as usize) {
2179 let mut row_vec = Vec::new();
2180 for _ in 0..((size.width() / size.cell_width()) as usize) {
2181 let cell_char = rng.sample(Alphanumeric) as char;
2182 row_vec.push(cell_char)
2183 }
2184 cells.push(row_vec)
2185 }
2186
2187 cells
2188 }
2189
2190 fn convert_cells_to_content(
2191 terminal_bounds: TerminalBounds,
2192 cells: &[Vec<char>],
2193 ) -> TerminalContent {
2194 let mut ic = Vec::new();
2195
2196 for (index, row) in cells.iter().enumerate() {
2197 for (cell_index, cell_char) in row.iter().enumerate() {
2198 ic.push(IndexedCell {
2199 point: AlacPoint::new(Line(index as i32), Column(cell_index)),
2200 cell: Cell {
2201 c: *cell_char,
2202 ..Default::default()
2203 },
2204 });
2205 }
2206 }
2207
2208 TerminalContent {
2209 cells: ic,
2210 terminal_bounds,
2211 ..Default::default()
2212 }
2213 }
2214}