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