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 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
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(|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
418 .background_executor()
419 .timer(Duration::from_millis(4))
420 .fuse();
421 let mut wakeup = false;
422 loop {
423 futures::select_biased! {
424 _ = timer => break,
425 event = self.events_rx.next() => {
426 if let Some(event) = event {
427 if matches!(event, AlacTermEvent::Wakeup) {
428 wakeup = true;
429 } else {
430 events.push(event);
431 }
432
433 if events.len() > 100 {
434 break;
435 }
436 } else {
437 break;
438 }
439 },
440 }
441 }
442
443 if events.is_empty() && wakeup == false {
444 smol::future::yield_now().await;
445 break 'outer;
446 } else {
447 this.update(&mut cx, |this, cx| {
448 if wakeup {
449 this.process_event(&AlacTermEvent::Wakeup, cx);
450 }
451
452 for event in events {
453 this.process_event(&event, cx);
454 }
455 })?;
456 smol::future::yield_now().await;
457 }
458 }
459 }
460
461 anyhow::Ok(())
462 })
463 .detach();
464
465 self.terminal
466 }
467}
468
469#[derive(Debug, Clone, Deserialize, Serialize)]
470pub struct IndexedCell {
471 pub point: AlacPoint,
472 pub cell: Cell,
473}
474
475impl Deref for IndexedCell {
476 type Target = Cell;
477
478 #[inline]
479 fn deref(&self) -> &Cell {
480 &self.cell
481 }
482}
483
484// TODO: Un-pub
485#[derive(Clone)]
486pub struct TerminalContent {
487 pub cells: Vec<IndexedCell>,
488 pub mode: TermMode,
489 pub display_offset: usize,
490 pub selection_text: Option<String>,
491 pub selection: Option<SelectionRange>,
492 pub cursor: RenderableCursor,
493 pub cursor_char: char,
494 pub size: TerminalSize,
495 pub last_hovered_word: Option<HoveredWord>,
496}
497
498#[derive(Clone)]
499pub struct HoveredWord {
500 pub word: String,
501 pub word_match: RangeInclusive<AlacPoint>,
502 pub id: usize,
503}
504
505impl Default for TerminalContent {
506 fn default() -> Self {
507 TerminalContent {
508 cells: Default::default(),
509 mode: Default::default(),
510 display_offset: Default::default(),
511 selection_text: Default::default(),
512 selection: Default::default(),
513 cursor: RenderableCursor {
514 shape: alacritty_terminal::ansi::CursorShape::Block,
515 point: AlacPoint::new(Line(0), Column(0)),
516 },
517 cursor_char: Default::default(),
518 size: Default::default(),
519 last_hovered_word: None,
520 }
521 }
522}
523
524#[derive(PartialEq, Eq)]
525pub enum SelectionPhase {
526 Selecting,
527 Ended,
528}
529
530pub struct Terminal {
531 pty_tx: Notifier,
532 term: Arc<FairMutex<Term<ZedListener>>>,
533 events: VecDeque<InternalEvent>,
534 /// This is only used for mouse mode cell change detection
535 last_mouse: Option<(AlacPoint, AlacDirection)>,
536 /// This is only used for terminal hovered word checking
537 last_mouse_position: Option<Point<Pixels>>,
538 pub matches: Vec<RangeInclusive<AlacPoint>>,
539 pub last_content: TerminalContent,
540 last_synced: Instant,
541 sync_task: Option<Task<()>>,
542 pub selection_head: Option<AlacPoint>,
543 pub breadcrumb_text: String,
544 shell_pid: u32,
545 shell_fd: u32,
546 pub foreground_process_info: Option<LocalProcessInfo>,
547 scroll_px: Pixels,
548 next_link_id: usize,
549 selection_phase: SelectionPhase,
550 cmd_pressed: bool,
551 hovered_word: bool,
552 // An implementation of the 8 bit ANSI color palette
553 color_for_index: Box<dyn Fn(usize, &mut AppContext) -> Hsla + Send + Sync + 'static>,
554}
555
556impl Terminal {
557 fn process_event(&mut self, event: &AlacTermEvent, cx: &mut ModelContext<Self>) {
558 match event {
559 AlacTermEvent::Title(title) => {
560 self.breadcrumb_text = title.to_string();
561 cx.emit(Event::BreadcrumbsChanged);
562 }
563 AlacTermEvent::ResetTitle => {
564 self.breadcrumb_text = String::new();
565 cx.emit(Event::BreadcrumbsChanged);
566 }
567 AlacTermEvent::ClipboardStore(_, data) => {
568 cx.write_to_clipboard(ClipboardItem::new(data.to_string()))
569 }
570 AlacTermEvent::ClipboardLoad(_, format) => self.write_to_pty(format(
571 &cx.read_from_clipboard()
572 .map(|ci| ci.text().to_string())
573 .unwrap_or_else(|| "".to_string()),
574 )),
575 AlacTermEvent::PtyWrite(out) => self.write_to_pty(out.clone()),
576 AlacTermEvent::TextAreaSizeRequest(format) => {
577 self.write_to_pty(format(self.last_content.size.into()))
578 }
579 AlacTermEvent::CursorBlinkingChange => {
580 cx.emit(Event::BlinkChanged);
581 }
582 AlacTermEvent::Bell => {
583 cx.emit(Event::Bell);
584 }
585 AlacTermEvent::Exit => cx.emit(Event::CloseTerminal),
586 AlacTermEvent::MouseCursorDirty => {
587 //NOOP, Handled in render
588 }
589 AlacTermEvent::Wakeup => {
590 cx.emit(Event::Wakeup);
591
592 if self.update_process_info() {
593 cx.emit(Event::TitleChanged);
594 }
595 }
596 AlacTermEvent::ColorRequest(idx, fun_ptr) => {
597 self.events
598 .push_back(InternalEvent::ColorRequest(*idx, fun_ptr.clone()));
599 }
600 }
601 }
602
603 /// Update the cached process info, returns whether the Zed-relevant info has changed
604 fn update_process_info(&mut self) -> bool {
605 let mut pid = unsafe { libc::tcgetpgrp(self.shell_fd as i32) };
606 if pid < 0 {
607 pid = self.shell_pid as i32;
608 }
609
610 if let Some(process_info) = LocalProcessInfo::with_root_pid(pid as u32) {
611 let res = self
612 .foreground_process_info
613 .as_ref()
614 .map(|old_info| {
615 process_info.cwd != old_info.cwd || process_info.name != old_info.name
616 })
617 .unwrap_or(true);
618
619 self.foreground_process_info = Some(process_info.clone());
620
621 res
622 } else {
623 false
624 }
625 }
626
627 ///Takes events from Alacritty and translates them to behavior on this view
628 fn process_terminal_event(
629 &mut self,
630 event: &InternalEvent,
631 term: &mut Term<ZedListener>,
632 cx: &mut ModelContext<Self>,
633 ) {
634 match event {
635 InternalEvent::ColorRequest(index, format) => {
636 let color = term.colors()[*index]
637 .unwrap_or_else(|| to_alac_rgb((self.color_for_index)(*index, cx)));
638 self.write_to_pty(format(color))
639 }
640 InternalEvent::Resize(mut new_size) => {
641 new_size.size.height = cmp::max(new_size.line_height, new_size.height());
642 new_size.size.width = cmp::max(new_size.cell_width, new_size.width());
643
644 self.last_content.size = new_size.clone();
645
646 self.pty_tx.0.send(Msg::Resize(new_size.into())).ok();
647
648 term.resize(new_size);
649 }
650 InternalEvent::Clear => {
651 // Clear back buffer
652 term.clear_screen(ClearMode::Saved);
653
654 let cursor = term.grid().cursor.point;
655
656 // Clear the lines above
657 term.grid_mut().reset_region(..cursor.line);
658
659 // Copy the current line up
660 let line = term.grid()[cursor.line][..Column(term.grid().columns())]
661 .iter()
662 .cloned()
663 .enumerate()
664 .collect::<Vec<(usize, Cell)>>();
665
666 for (i, cell) in line {
667 term.grid_mut()[Line(0)][Column(i)] = cell;
668 }
669
670 // Reset the cursor
671 term.grid_mut().cursor.point =
672 AlacPoint::new(Line(0), term.grid_mut().cursor.point.column);
673 let new_cursor = term.grid().cursor.point;
674
675 // Clear the lines below the new cursor
676 if (new_cursor.line.0 as usize) < term.screen_lines() - 1 {
677 term.grid_mut().reset_region((new_cursor.line + 1)..);
678 }
679
680 cx.emit(Event::Wakeup);
681 }
682 InternalEvent::Scroll(scroll) => {
683 term.scroll_display(*scroll);
684 self.refresh_hovered_word();
685 }
686 InternalEvent::SetSelection(selection) => {
687 term.selection = selection.as_ref().map(|(sel, _)| sel.clone());
688
689 if let Some((_, head)) = selection {
690 self.selection_head = Some(*head);
691 }
692 cx.emit(Event::SelectionsChanged)
693 }
694 InternalEvent::UpdateSelection(position) => {
695 if let Some(mut selection) = term.selection.take() {
696 let point = grid_point(
697 *position,
698 self.last_content.size,
699 term.grid().display_offset(),
700 );
701
702 let side = mouse_side(*position, self.last_content.size);
703
704 selection.update(point, side);
705 term.selection = Some(selection);
706
707 self.selection_head = Some(point);
708 cx.emit(Event::SelectionsChanged)
709 }
710 }
711
712 InternalEvent::Copy => {
713 if let Some(txt) = term.selection_to_string() {
714 cx.write_to_clipboard(ClipboardItem::new(txt))
715 }
716 }
717 InternalEvent::ScrollToAlacPoint(point) => {
718 term.scroll_to_point(*point);
719 self.refresh_hovered_word();
720 }
721 InternalEvent::FindHyperlink(position, open) => {
722 let prev_hovered_word = self.last_content.last_hovered_word.take();
723
724 let point = grid_point(
725 *position,
726 self.last_content.size,
727 term.grid().display_offset(),
728 )
729 .grid_clamp(term, Boundary::Grid);
730
731 let link = term.grid().index(point).hyperlink();
732 let found_word = if link.is_some() {
733 let mut min_index = point;
734 loop {
735 let new_min_index = min_index.sub(term, Boundary::Cursor, 1);
736 if new_min_index == min_index {
737 break;
738 } else if term.grid().index(new_min_index).hyperlink() != link {
739 break;
740 } else {
741 min_index = new_min_index
742 }
743 }
744
745 let mut max_index = point;
746 loop {
747 let new_max_index = max_index.add(term, Boundary::Cursor, 1);
748 if new_max_index == max_index {
749 break;
750 } else if term.grid().index(new_max_index).hyperlink() != link {
751 break;
752 } else {
753 max_index = new_max_index
754 }
755 }
756
757 let url = link.unwrap().uri().to_owned();
758 let url_match = min_index..=max_index;
759
760 Some((url, true, url_match))
761 } else if let Some(word_match) = regex_match_at(term, point, &WORD_REGEX) {
762 let maybe_url_or_path =
763 term.bounds_to_string(*word_match.start(), *word_match.end());
764 let original_match = word_match.clone();
765 let (sanitized_match, sanitized_word) =
766 if maybe_url_or_path.starts_with('[') && maybe_url_or_path.ends_with(']') {
767 (
768 Match::new(
769 word_match.start().add(term, Boundary::Cursor, 1),
770 word_match.end().sub(term, Boundary::Cursor, 1),
771 ),
772 maybe_url_or_path[1..maybe_url_or_path.len() - 1].to_owned(),
773 )
774 } else {
775 (word_match, maybe_url_or_path)
776 };
777
778 let is_url = match regex_match_at(term, point, &URL_REGEX) {
779 Some(url_match) => {
780 // `]` is a valid symbol in the `file://` URL, so the regex match will include it
781 // consider that when ensuring that the URL match is the same as the original word
782 if sanitized_match != original_match {
783 url_match.start() == sanitized_match.start()
784 && url_match.end() == original_match.end()
785 } else {
786 url_match == sanitized_match
787 }
788 }
789 None => false,
790 };
791 Some((sanitized_word, is_url, sanitized_match))
792 } else {
793 None
794 };
795
796 match found_word {
797 Some((maybe_url_or_path, is_url, url_match)) => {
798 if *open {
799 let target = if is_url {
800 MaybeNavigationTarget::Url(maybe_url_or_path)
801 } else {
802 MaybeNavigationTarget::PathLike(maybe_url_or_path)
803 };
804 cx.emit(Event::Open(target));
805 } else {
806 self.update_selected_word(
807 prev_hovered_word,
808 url_match,
809 maybe_url_or_path,
810 is_url,
811 cx,
812 );
813 }
814 self.hovered_word = true;
815 }
816 None => {
817 if self.hovered_word {
818 cx.emit(Event::NewNavigationTarget(None));
819 }
820 self.hovered_word = false;
821 }
822 }
823 }
824 }
825 }
826
827 fn update_selected_word(
828 &mut self,
829 prev_word: Option<HoveredWord>,
830 word_match: RangeInclusive<AlacPoint>,
831 word: String,
832 is_url: bool,
833 cx: &mut ModelContext<Self>,
834 ) {
835 if let Some(prev_word) = prev_word {
836 if prev_word.word == word && prev_word.word_match == word_match {
837 self.last_content.last_hovered_word = Some(HoveredWord {
838 word,
839 word_match,
840 id: prev_word.id,
841 });
842 return;
843 }
844 }
845
846 self.last_content.last_hovered_word = Some(HoveredWord {
847 word: word.clone(),
848 word_match,
849 id: self.next_link_id(),
850 });
851 let navigation_target = if is_url {
852 MaybeNavigationTarget::Url(word)
853 } else {
854 MaybeNavigationTarget::PathLike(word)
855 };
856 cx.emit(Event::NewNavigationTarget(Some(navigation_target)));
857 }
858
859 fn next_link_id(&mut self) -> usize {
860 let res = self.next_link_id;
861 self.next_link_id = self.next_link_id.wrapping_add(1);
862 res
863 }
864
865 pub fn last_content(&self) -> &TerminalContent {
866 &self.last_content
867 }
868
869 //To test:
870 //- Activate match on terminal (scrolling and selection)
871 //- Editor search snapping behavior
872
873 pub fn activate_match(&mut self, index: usize) {
874 if let Some(search_match) = self.matches.get(index).cloned() {
875 self.set_selection(Some((make_selection(&search_match), *search_match.end())));
876
877 self.events
878 .push_back(InternalEvent::ScrollToAlacPoint(*search_match.start()));
879 }
880 }
881
882 pub fn select_matches(&mut self, matches: Vec<RangeInclusive<AlacPoint>>) {
883 let matches_to_select = self
884 .matches
885 .iter()
886 .filter(|self_match| matches.contains(self_match))
887 .cloned()
888 .collect::<Vec<_>>();
889 for match_to_select in matches_to_select {
890 self.set_selection(Some((
891 make_selection(&match_to_select),
892 *match_to_select.end(),
893 )));
894 }
895 }
896
897 pub fn select_all(&mut self) {
898 let term = self.term.lock();
899 let start = AlacPoint::new(term.topmost_line(), Column(0));
900 let end = AlacPoint::new(term.bottommost_line(), term.last_column());
901 drop(term);
902 self.set_selection(Some((make_selection(&(start..=end)), end)));
903 }
904
905 fn set_selection(&mut self, selection: Option<(Selection, AlacPoint)>) {
906 self.events
907 .push_back(InternalEvent::SetSelection(selection));
908 }
909
910 pub fn copy(&mut self) {
911 self.events.push_back(InternalEvent::Copy);
912 }
913
914 pub fn clear(&mut self) {
915 self.events.push_back(InternalEvent::Clear)
916 }
917
918 ///Resize the terminal and the PTY.
919 pub fn set_size(&mut self, new_size: TerminalSize) {
920 self.events.push_back(InternalEvent::Resize(new_size))
921 }
922
923 ///Write the Input payload to the tty.
924 fn write_to_pty(&self, input: String) {
925 self.pty_tx.notify(input.into_bytes());
926 }
927
928 fn write_bytes_to_pty(&self, input: Vec<u8>) {
929 self.pty_tx.notify(input);
930 }
931
932 pub fn input(&mut self, input: String) {
933 self.events
934 .push_back(InternalEvent::Scroll(AlacScroll::Bottom));
935 self.events.push_back(InternalEvent::SetSelection(None));
936
937 self.write_to_pty(input);
938 }
939
940 pub fn input_bytes(&mut self, input: Vec<u8>) {
941 self.events
942 .push_back(InternalEvent::Scroll(AlacScroll::Bottom));
943 self.events.push_back(InternalEvent::SetSelection(None));
944
945 self.write_bytes_to_pty(input);
946 }
947
948 pub fn try_keystroke(&mut self, keystroke: &Keystroke, alt_is_meta: bool) -> bool {
949 let esc = to_esc_str(keystroke, &self.last_content.mode, alt_is_meta);
950 if let Some(esc) = esc {
951 self.input(esc);
952 true
953 } else {
954 false
955 }
956 }
957
958 pub fn try_modifiers_change(&mut self, modifiers: &Modifiers) -> bool {
959 let changed = self.cmd_pressed != modifiers.command;
960 if !self.cmd_pressed && modifiers.command {
961 self.refresh_hovered_word();
962 }
963 self.cmd_pressed = modifiers.command;
964 changed
965 }
966
967 ///Paste text into the terminal
968 pub fn paste(&mut self, text: &str) {
969 let paste_text = if self.last_content.mode.contains(TermMode::BRACKETED_PASTE) {
970 format!("{}{}{}", "\x1b[200~", text.replace('\x1b', ""), "\x1b[201~")
971 } else {
972 text.replace("\r\n", "\r").replace('\n', "\r")
973 };
974
975 self.input(paste_text);
976 }
977
978 pub fn try_sync(&mut self, cx: &mut ModelContext<Self>) {
979 let term = self.term.clone();
980
981 let mut terminal = if let Some(term) = term.try_lock_unfair() {
982 term
983 } else if self.last_synced.elapsed().as_secs_f32() > 0.25 {
984 term.lock_unfair() //It's been too long, force block
985 } else if let None = self.sync_task {
986 //Skip this frame
987 let delay = cx.background_executor().timer(Duration::from_millis(16));
988 self.sync_task = Some(cx.spawn(|weak_handle, mut cx| async move {
989 delay.await;
990 if let Some(handle) = weak_handle.upgrade() {
991 handle
992 .update(&mut cx, |terminal, cx| {
993 terminal.sync_task.take();
994 cx.notify();
995 })
996 .ok();
997 }
998 }));
999 return;
1000 } else {
1001 //No lock and delayed rendering already scheduled, nothing to do
1002 return;
1003 };
1004
1005 //Note that the ordering of events matters for event processing
1006 while let Some(e) = self.events.pop_front() {
1007 self.process_terminal_event(&e, &mut terminal, cx)
1008 }
1009
1010 self.last_content = Self::make_content(&terminal, &self.last_content);
1011 self.last_synced = Instant::now();
1012 }
1013
1014 fn make_content(term: &Term<ZedListener>, last_content: &TerminalContent) -> TerminalContent {
1015 let content = term.renderable_content();
1016 TerminalContent {
1017 cells: content
1018 .display_iter
1019 //TODO: Add this once there's a way to retain empty lines
1020 // .filter(|ic| {
1021 // !ic.flags.contains(Flags::HIDDEN)
1022 // && !(ic.bg == Named(NamedColor::Background)
1023 // && ic.c == ' '
1024 // && !ic.flags.contains(Flags::INVERSE))
1025 // })
1026 .map(|ic| IndexedCell {
1027 point: ic.point,
1028 cell: ic.cell.clone(),
1029 })
1030 .collect::<Vec<IndexedCell>>(),
1031 mode: content.mode,
1032 display_offset: content.display_offset,
1033 selection_text: term.selection_to_string(),
1034 selection: content.selection,
1035 cursor: content.cursor,
1036 cursor_char: term.grid()[content.cursor.point].c,
1037 size: last_content.size,
1038 last_hovered_word: last_content.last_hovered_word.clone(),
1039 }
1040 }
1041
1042 pub fn focus_in(&self) {
1043 if self.last_content.mode.contains(TermMode::FOCUS_IN_OUT) {
1044 self.write_to_pty("\x1b[I".to_string());
1045 }
1046 }
1047
1048 pub fn focus_out(&mut self) {
1049 self.last_mouse_position = None;
1050 if self.last_content.mode.contains(TermMode::FOCUS_IN_OUT) {
1051 self.write_to_pty("\x1b[O".to_string());
1052 }
1053 }
1054
1055 pub fn mouse_changed(&mut self, point: AlacPoint, side: AlacDirection) -> bool {
1056 match self.last_mouse {
1057 Some((old_point, old_side)) => {
1058 if old_point == point && old_side == side {
1059 false
1060 } else {
1061 self.last_mouse = Some((point, side));
1062 true
1063 }
1064 }
1065 None => {
1066 self.last_mouse = Some((point, side));
1067 true
1068 }
1069 }
1070 }
1071
1072 pub fn mouse_mode(&self, shift: bool) -> bool {
1073 self.last_content.mode.intersects(TermMode::MOUSE_MODE) && !shift
1074 }
1075
1076 pub fn mouse_move(&mut self, e: &MouseMoveEvent, origin: Point<Pixels>) {
1077 let position = e.position - origin;
1078 self.last_mouse_position = Some(position);
1079 if self.mouse_mode(e.modifiers.shift) {
1080 let point = grid_point(
1081 position,
1082 self.last_content.size,
1083 self.last_content.display_offset,
1084 );
1085 let side = mouse_side(position, self.last_content.size);
1086
1087 if self.mouse_changed(point, side) {
1088 if let Some(bytes) = mouse_moved_report(point, e, self.last_content.mode) {
1089 self.pty_tx.notify(bytes);
1090 }
1091 }
1092 } else if self.cmd_pressed {
1093 self.word_from_position(Some(position));
1094 }
1095 }
1096
1097 fn word_from_position(&mut self, position: Option<Point<Pixels>>) {
1098 if self.selection_phase == SelectionPhase::Selecting {
1099 self.last_content.last_hovered_word = None;
1100 } else if let Some(position) = position {
1101 self.events
1102 .push_back(InternalEvent::FindHyperlink(position, false));
1103 }
1104 }
1105
1106 pub fn mouse_drag(&mut self, e: MouseMoveEvent, origin: Point<Pixels>, region: Bounds<Pixels>) {
1107 let position = e.position - origin;
1108 self.last_mouse_position = Some(position);
1109
1110 if !self.mouse_mode(e.modifiers.shift) {
1111 self.selection_phase = SelectionPhase::Selecting;
1112 // Alacritty has the same ordering, of first updating the selection
1113 // then scrolling 15ms later
1114 self.events
1115 .push_back(InternalEvent::UpdateSelection(position));
1116
1117 // Doesn't make sense to scroll the alt screen
1118 if !self.last_content.mode.contains(TermMode::ALT_SCREEN) {
1119 let scroll_delta = match self.drag_line_delta(e, region) {
1120 Some(value) => value,
1121 None => return,
1122 };
1123
1124 let scroll_lines = (scroll_delta / self.last_content.size.line_height) as i32;
1125
1126 self.events
1127 .push_back(InternalEvent::Scroll(AlacScroll::Delta(scroll_lines)));
1128 }
1129 }
1130 }
1131
1132 fn drag_line_delta(&mut self, e: MouseMoveEvent, region: Bounds<Pixels>) -> Option<Pixels> {
1133 //TODO: Why do these need to be doubled? Probably the same problem that the IME has
1134 let top = region.origin.y + (self.last_content.size.line_height * 2.);
1135 let bottom = region.lower_left().y - (self.last_content.size.line_height * 2.);
1136 let scroll_delta = if e.position.y < top {
1137 (top - e.position.y).pow(1.1)
1138 } else if e.position.y > bottom {
1139 -((e.position.y - bottom).pow(1.1))
1140 } else {
1141 return None; //Nothing to do
1142 };
1143 Some(scroll_delta)
1144 }
1145
1146 pub fn mouse_down(&mut self, e: &MouseDownEvent, origin: Point<Pixels>) {
1147 let position = e.position - origin;
1148 let point = grid_point(
1149 position,
1150 self.last_content.size,
1151 self.last_content.display_offset,
1152 );
1153
1154 if self.mouse_mode(e.modifiers.shift) {
1155 if let Some(bytes) =
1156 mouse_button_report(point, e.button, e.modifiers, true, self.last_content.mode)
1157 {
1158 self.pty_tx.notify(bytes);
1159 }
1160 } else if e.button == MouseButton::Left {
1161 let position = e.position - origin;
1162 let point = grid_point(
1163 position,
1164 self.last_content.size,
1165 self.last_content.display_offset,
1166 );
1167
1168 // Use .opposite so that selection is inclusive of the cell clicked.
1169 let side = mouse_side(position, self.last_content.size);
1170
1171 let selection_type = match e.click_count {
1172 0 => return, //This is a release
1173 1 => Some(SelectionType::Simple),
1174 2 => Some(SelectionType::Semantic),
1175 3 => Some(SelectionType::Lines),
1176 _ => None,
1177 };
1178
1179 let selection =
1180 selection_type.map(|selection_type| Selection::new(selection_type, point, side));
1181
1182 if let Some(sel) = selection {
1183 self.events
1184 .push_back(InternalEvent::SetSelection(Some((sel, point))));
1185 }
1186 }
1187 }
1188
1189 pub fn mouse_up(
1190 &mut self,
1191 e: &MouseUpEvent,
1192 origin: Point<Pixels>,
1193 cx: &mut ModelContext<Self>,
1194 ) {
1195 let setting = TerminalSettings::get_global(cx);
1196
1197 let position = e.position - origin;
1198 if self.mouse_mode(e.modifiers.shift) {
1199 let point = grid_point(
1200 position,
1201 self.last_content.size,
1202 self.last_content.display_offset,
1203 );
1204
1205 if let Some(bytes) =
1206 mouse_button_report(point, e.button, e.modifiers, false, self.last_content.mode)
1207 {
1208 self.pty_tx.notify(bytes);
1209 }
1210 } else {
1211 if e.button == MouseButton::Left && setting.copy_on_select {
1212 self.copy();
1213 }
1214
1215 //Hyperlinks
1216 if self.selection_phase == SelectionPhase::Ended {
1217 let mouse_cell_index = content_index_for_mouse(position, &self.last_content.size);
1218 if let Some(link) = self.last_content.cells[mouse_cell_index].hyperlink() {
1219 cx.open_url(link.uri());
1220 } else if self.cmd_pressed {
1221 self.events
1222 .push_back(InternalEvent::FindHyperlink(position, true));
1223 }
1224 }
1225 }
1226
1227 self.selection_phase = SelectionPhase::Ended;
1228 self.last_mouse = None;
1229 }
1230
1231 ///Scroll the terminal
1232 pub fn scroll_wheel(&mut self, e: ScrollWheelEvent, origin: Point<Pixels>) {
1233 let mouse_mode = self.mouse_mode(e.shift);
1234
1235 if let Some(scroll_lines) = self.determine_scroll_lines(&e, mouse_mode) {
1236 if mouse_mode {
1237 let point = grid_point(
1238 e.position - origin,
1239 self.last_content.size,
1240 self.last_content.display_offset,
1241 );
1242
1243 if let Some(scrolls) =
1244 scroll_report(point, scroll_lines as i32, &e, self.last_content.mode)
1245 {
1246 for scroll in scrolls {
1247 self.pty_tx.notify(scroll);
1248 }
1249 };
1250 } else if self
1251 .last_content
1252 .mode
1253 .contains(TermMode::ALT_SCREEN | TermMode::ALTERNATE_SCROLL)
1254 && !e.shift
1255 {
1256 self.pty_tx.notify(alt_scroll(scroll_lines))
1257 } else {
1258 if scroll_lines != 0 {
1259 let scroll = AlacScroll::Delta(scroll_lines);
1260
1261 self.events.push_back(InternalEvent::Scroll(scroll));
1262 }
1263 }
1264 }
1265 }
1266
1267 fn refresh_hovered_word(&mut self) {
1268 self.word_from_position(self.last_mouse_position);
1269 }
1270
1271 fn determine_scroll_lines(&mut self, e: &ScrollWheelEvent, mouse_mode: bool) -> Option<i32> {
1272 let scroll_multiplier = if mouse_mode { 1. } else { SCROLL_MULTIPLIER };
1273 let line_height = self.last_content.size.line_height;
1274 match e.touch_phase {
1275 /* Reset scroll state on started */
1276 TouchPhase::Started => {
1277 self.scroll_px = px(0.);
1278 None
1279 }
1280 /* Calculate the appropriate scroll lines */
1281 TouchPhase::Moved => {
1282 let old_offset = (self.scroll_px / line_height) as i32;
1283
1284 self.scroll_px += e.delta.pixel_delta(line_height).y * scroll_multiplier;
1285
1286 let new_offset = (self.scroll_px / line_height) as i32;
1287
1288 // Whenever we hit the edges, reset our stored scroll to 0
1289 // so we can respond to changes in direction quickly
1290 self.scroll_px %= self.last_content.size.height();
1291
1292 Some(new_offset - old_offset)
1293 }
1294 TouchPhase::Ended => None,
1295 }
1296 }
1297
1298 pub fn find_matches(
1299 &mut self,
1300 searcher: RegexSearch,
1301 cx: &mut ModelContext<Self>,
1302 ) -> Task<Vec<RangeInclusive<AlacPoint>>> {
1303 let term = self.term.clone();
1304 cx.background_executor().spawn(async move {
1305 let term = term.lock();
1306
1307 all_search_matches(&term, &searcher).collect()
1308 })
1309 }
1310
1311 pub fn title(&self) -> String {
1312 self.foreground_process_info
1313 .as_ref()
1314 .map(|fpi| {
1315 format!(
1316 "{} — {}",
1317 truncate_and_trailoff(
1318 &fpi.cwd
1319 .file_name()
1320 .map(|name| name.to_string_lossy().to_string())
1321 .unwrap_or_default(),
1322 25
1323 ),
1324 truncate_and_trailoff(
1325 &{
1326 format!(
1327 "{}{}",
1328 fpi.name,
1329 if fpi.argv.len() >= 1 {
1330 format!(" {}", (&fpi.argv[1..]).join(" "))
1331 } else {
1332 "".to_string()
1333 }
1334 )
1335 },
1336 25
1337 )
1338 )
1339 })
1340 .unwrap_or_else(|| "Terminal".to_string())
1341 }
1342
1343 pub fn can_navigate_to_selected_word(&self) -> bool {
1344 self.cmd_pressed && self.hovered_word
1345 }
1346}
1347
1348impl Drop for Terminal {
1349 fn drop(&mut self) {
1350 self.pty_tx.0.send(Msg::Shutdown).ok();
1351 }
1352}
1353
1354impl EventEmitter<Event> for Terminal {}
1355
1356/// Based on alacritty/src/display/hint.rs > regex_match_at
1357/// Retrieve the match, if the specified point is inside the content matching the regex.
1358fn regex_match_at<T>(term: &Term<T>, point: AlacPoint, regex: &RegexSearch) -> Option<Match> {
1359 visible_regex_match_iter(term, regex).find(|rm| rm.contains(&point))
1360}
1361
1362/// Copied from alacritty/src/display/hint.rs:
1363/// Iterate over all visible regex matches.
1364pub fn visible_regex_match_iter<'a, T>(
1365 term: &'a Term<T>,
1366 regex: &'a RegexSearch,
1367) -> impl Iterator<Item = Match> + 'a {
1368 let viewport_start = Line(-(term.grid().display_offset() as i32));
1369 let viewport_end = viewport_start + term.bottommost_line();
1370 let mut start = term.line_search_left(AlacPoint::new(viewport_start, Column(0)));
1371 let mut end = term.line_search_right(AlacPoint::new(viewport_end, Column(0)));
1372 start.line = start.line.max(viewport_start - MAX_SEARCH_LINES);
1373 end.line = end.line.min(viewport_end + MAX_SEARCH_LINES);
1374
1375 RegexIter::new(start, end, AlacDirection::Right, term, regex)
1376 .skip_while(move |rm| rm.end().line < viewport_start)
1377 .take_while(move |rm| rm.start().line <= viewport_end)
1378}
1379
1380fn make_selection(range: &RangeInclusive<AlacPoint>) -> Selection {
1381 let mut selection = Selection::new(SelectionType::Simple, *range.start(), AlacDirection::Left);
1382 selection.update(*range.end(), AlacDirection::Right);
1383 selection
1384}
1385
1386fn all_search_matches<'a, T>(
1387 term: &'a Term<T>,
1388 regex: &'a RegexSearch,
1389) -> impl Iterator<Item = Match> + 'a {
1390 let start = AlacPoint::new(term.grid().topmost_line(), Column(0));
1391 let end = AlacPoint::new(term.grid().bottommost_line(), term.grid().last_column());
1392 RegexIter::new(start, end, AlacDirection::Right, term, regex)
1393}
1394
1395fn content_index_for_mouse(pos: Point<Pixels>, size: &TerminalSize) -> usize {
1396 let col = (pos.x / size.cell_width()).round() as usize;
1397 let clamped_col = min(col, size.columns() - 1);
1398 let row = (pos.y / size.line_height()).round() as usize;
1399 let clamped_row = min(row, size.screen_lines() - 1);
1400 clamped_row * size.columns() + clamped_col
1401}
1402
1403#[cfg(test)]
1404mod tests {
1405 use alacritty_terminal::{
1406 index::{Column, Line, Point as AlacPoint},
1407 term::cell::Cell,
1408 };
1409 use gpui::{point, size, Pixels};
1410 use rand::{distributions::Alphanumeric, rngs::ThreadRng, thread_rng, Rng};
1411
1412 use crate::{content_index_for_mouse, IndexedCell, TerminalContent, TerminalSize};
1413
1414 #[test]
1415 fn test_mouse_to_cell_test() {
1416 let mut rng = thread_rng();
1417 const ITERATIONS: usize = 10;
1418 const PRECISION: usize = 1000;
1419
1420 for _ in 0..ITERATIONS {
1421 let viewport_cells = rng.gen_range(15..20);
1422 let cell_size = rng.gen_range(5 * PRECISION..20 * PRECISION) as f32 / PRECISION as f32;
1423
1424 let size = crate::TerminalSize {
1425 cell_width: Pixels::from(cell_size),
1426 line_height: Pixels::from(cell_size),
1427 size: size(
1428 Pixels::from(cell_size * (viewport_cells as f32)),
1429 Pixels::from(cell_size * (viewport_cells as f32)),
1430 ),
1431 };
1432
1433 let cells = get_cells(size, &mut rng);
1434 let content = convert_cells_to_content(size, &cells);
1435
1436 for row in 0..(viewport_cells - 1) {
1437 let row = row as usize;
1438 for col in 0..(viewport_cells - 1) {
1439 let col = col as usize;
1440
1441 let row_offset = rng.gen_range(0..PRECISION) as f32 / PRECISION as f32;
1442 let col_offset = rng.gen_range(0..PRECISION) as f32 / PRECISION as f32;
1443
1444 let mouse_pos = point(
1445 Pixels::from(col as f32 * cell_size + col_offset),
1446 Pixels::from(row as f32 * cell_size + row_offset),
1447 );
1448
1449 let content_index = content_index_for_mouse(mouse_pos, &content.size);
1450 let mouse_cell = content.cells[content_index].c;
1451 let real_cell = cells[row][col];
1452
1453 assert_eq!(mouse_cell, real_cell);
1454 }
1455 }
1456 }
1457 }
1458
1459 #[test]
1460 fn test_mouse_to_cell_clamp() {
1461 let mut rng = thread_rng();
1462
1463 let size = crate::TerminalSize {
1464 cell_width: Pixels::from(10.),
1465 line_height: Pixels::from(10.),
1466 size: size(Pixels::from(100.), Pixels::from(100.)),
1467 };
1468
1469 let cells = get_cells(size, &mut rng);
1470 let content = convert_cells_to_content(size, &cells);
1471
1472 assert_eq!(
1473 content.cells[content_index_for_mouse(
1474 point(Pixels::from(-10.), Pixels::from(-10.)),
1475 &content.size
1476 )]
1477 .c,
1478 cells[0][0]
1479 );
1480 assert_eq!(
1481 content.cells[content_index_for_mouse(
1482 point(Pixels::from(1000.), Pixels::from(1000.)),
1483 &content.size
1484 )]
1485 .c,
1486 cells[9][9]
1487 );
1488 }
1489
1490 fn get_cells(size: TerminalSize, rng: &mut ThreadRng) -> Vec<Vec<char>> {
1491 let mut cells = Vec::new();
1492
1493 for _ in 0..(f32::from(size.height() / size.line_height()) as usize) {
1494 let mut row_vec = Vec::new();
1495 for _ in 0..(f32::from(size.width() / size.cell_width()) as usize) {
1496 let cell_char = rng.sample(Alphanumeric) as char;
1497 row_vec.push(cell_char)
1498 }
1499 cells.push(row_vec)
1500 }
1501
1502 cells
1503 }
1504
1505 fn convert_cells_to_content(size: TerminalSize, cells: &Vec<Vec<char>>) -> TerminalContent {
1506 let mut ic = Vec::new();
1507
1508 for row in 0..cells.len() {
1509 for col in 0..cells[row].len() {
1510 let cell_char = cells[row][col];
1511 ic.push(IndexedCell {
1512 point: AlacPoint::new(Line(row as i32), Column(col)),
1513 cell: Cell {
1514 c: cell_char,
1515 ..Default::default()
1516 },
1517 });
1518 }
1519 }
1520
1521 TerminalContent {
1522 cells: ic,
1523 size,
1524 ..Default::default()
1525 }
1526 }
1527}