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