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