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