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::Cursor, 1),
939 word_match.end().sub(term, Boundary::Cursor, 1),
940 );
941 file_path = file_path[1..file_path.len() - 1].to_owned();
942 }
943
944 let mut colon_count = 0;
945 for c in file_path.chars() {
946 if c == ':' {
947 colon_count += 1;
948 }
949 }
950 // strip trailing comment after colon in case of
951 // file/at/path.rs:row:column:description or error message
952 // so that the file path is `file/at/path.rs:row:column`
953 if colon_count > 2 {
954 let last_index = file_path.rfind(':').unwrap();
955 let prev_is_digit = last_index > 0
956 && file_path
957 .chars()
958 .nth(last_index - 1)
959 .map_or(false, |c| c.is_ascii_digit());
960 let next_is_digit = last_index < file_path.len() - 1
961 && file_path
962 .chars()
963 .nth(last_index + 1)
964 .map_or(true, |c| c.is_ascii_digit());
965 if prev_is_digit && !next_is_digit {
966 let stripped_len = file_path.len() - last_index;
967 word_match = Match::new(
968 *word_match.start(),
969 word_match.end().sub(term, Boundary::Cursor, stripped_len),
970 );
971 file_path = file_path[0..last_index].to_owned();
972 }
973 }
974
975 break 'sanitize (word_match, file_path);
976 };
977
978 Some((sanitized_word, false, sanitized_match))
979 } else {
980 None
981 };
982
983 match found_word {
984 Some((maybe_url_or_path, is_url, url_match)) => {
985 let target = if is_url {
986 // Treat "file://" URLs like file paths to ensure
987 // that line numbers at the end of the path are
988 // handled correctly
989 if let Some(path) = maybe_url_or_path.strip_prefix("file://") {
990 MaybeNavigationTarget::PathLike(PathLikeTarget {
991 maybe_path: path.to_string(),
992 terminal_dir: self.working_directory(),
993 })
994 } else {
995 MaybeNavigationTarget::Url(maybe_url_or_path.clone())
996 }
997 } else {
998 MaybeNavigationTarget::PathLike(PathLikeTarget {
999 maybe_path: maybe_url_or_path.clone(),
1000 terminal_dir: self.working_directory(),
1001 })
1002 };
1003 if *open {
1004 cx.emit(Event::Open(target));
1005 } else {
1006 self.update_selected_word(
1007 prev_hovered_word,
1008 url_match,
1009 maybe_url_or_path,
1010 target,
1011 cx,
1012 );
1013 }
1014 }
1015 None => {
1016 cx.emit(Event::NewNavigationTarget(None));
1017 }
1018 }
1019 }
1020 }
1021 }
1022
1023 fn update_selected_word(
1024 &mut self,
1025 prev_word: Option<HoveredWord>,
1026 word_match: RangeInclusive<AlacPoint>,
1027 word: String,
1028 navigation_target: MaybeNavigationTarget,
1029 cx: &mut Context<Self>,
1030 ) {
1031 if let Some(prev_word) = prev_word {
1032 if prev_word.word == word && prev_word.word_match == word_match {
1033 self.last_content.last_hovered_word = Some(HoveredWord {
1034 word,
1035 word_match,
1036 id: prev_word.id,
1037 });
1038 return;
1039 }
1040 }
1041
1042 self.last_content.last_hovered_word = Some(HoveredWord {
1043 word: word.clone(),
1044 word_match,
1045 id: self.next_link_id(),
1046 });
1047 cx.emit(Event::NewNavigationTarget(Some(navigation_target)));
1048 cx.notify()
1049 }
1050
1051 fn next_link_id(&mut self) -> usize {
1052 let res = self.next_link_id;
1053 self.next_link_id = self.next_link_id.wrapping_add(1);
1054 res
1055 }
1056
1057 pub fn last_content(&self) -> &TerminalContent {
1058 &self.last_content
1059 }
1060
1061 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape) {
1062 self.term_config.default_cursor_style = cursor_shape.into();
1063 self.term.lock().set_options(self.term_config.clone());
1064 }
1065
1066 pub fn total_lines(&self) -> usize {
1067 let term = self.term.clone();
1068 let terminal = term.lock_unfair();
1069 terminal.total_lines()
1070 }
1071
1072 pub fn viewport_lines(&self) -> usize {
1073 let term = self.term.clone();
1074 let terminal = term.lock_unfair();
1075 terminal.screen_lines()
1076 }
1077
1078 //To test:
1079 //- Activate match on terminal (scrolling and selection)
1080 //- Editor search snapping behavior
1081
1082 pub fn activate_match(&mut self, index: usize) {
1083 if let Some(search_match) = self.matches.get(index).cloned() {
1084 self.set_selection(Some((make_selection(&search_match), *search_match.end())));
1085
1086 self.events
1087 .push_back(InternalEvent::ScrollToAlacPoint(*search_match.start()));
1088 }
1089 }
1090
1091 pub fn select_matches(&mut self, matches: &[RangeInclusive<AlacPoint>]) {
1092 let matches_to_select = self
1093 .matches
1094 .iter()
1095 .filter(|self_match| matches.contains(self_match))
1096 .cloned()
1097 .collect::<Vec<_>>();
1098 for match_to_select in matches_to_select {
1099 self.set_selection(Some((
1100 make_selection(&match_to_select),
1101 *match_to_select.end(),
1102 )));
1103 }
1104 }
1105
1106 pub fn select_all(&mut self) {
1107 let term = self.term.lock();
1108 let start = AlacPoint::new(term.topmost_line(), Column(0));
1109 let end = AlacPoint::new(term.bottommost_line(), term.last_column());
1110 drop(term);
1111 self.set_selection(Some((make_selection(&(start..=end)), end)));
1112 }
1113
1114 fn set_selection(&mut self, selection: Option<(Selection, AlacPoint)>) {
1115 self.events
1116 .push_back(InternalEvent::SetSelection(selection));
1117 }
1118
1119 pub fn copy(&mut self) {
1120 self.events.push_back(InternalEvent::Copy);
1121 }
1122
1123 pub fn clear(&mut self) {
1124 self.events.push_back(InternalEvent::Clear)
1125 }
1126
1127 pub fn scroll_line_up(&mut self) {
1128 self.events
1129 .push_back(InternalEvent::Scroll(AlacScroll::Delta(1)));
1130 }
1131
1132 pub fn scroll_up_by(&mut self, lines: usize) {
1133 self.events
1134 .push_back(InternalEvent::Scroll(AlacScroll::Delta(lines as i32)));
1135 }
1136
1137 pub fn scroll_line_down(&mut self) {
1138 self.events
1139 .push_back(InternalEvent::Scroll(AlacScroll::Delta(-1)));
1140 }
1141
1142 pub fn scroll_down_by(&mut self, lines: usize) {
1143 self.events
1144 .push_back(InternalEvent::Scroll(AlacScroll::Delta(-(lines as i32))));
1145 }
1146
1147 pub fn scroll_page_up(&mut self) {
1148 self.events
1149 .push_back(InternalEvent::Scroll(AlacScroll::PageUp));
1150 }
1151
1152 pub fn scroll_page_down(&mut self) {
1153 self.events
1154 .push_back(InternalEvent::Scroll(AlacScroll::PageDown));
1155 }
1156
1157 pub fn scroll_to_top(&mut self) {
1158 self.events
1159 .push_back(InternalEvent::Scroll(AlacScroll::Top));
1160 }
1161
1162 pub fn scroll_to_bottom(&mut self) {
1163 self.events
1164 .push_back(InternalEvent::Scroll(AlacScroll::Bottom));
1165 }
1166
1167 ///Resize the terminal and the PTY.
1168 pub fn set_size(&mut self, new_bounds: TerminalBounds) {
1169 if self.last_content.terminal_bounds != new_bounds {
1170 self.events.push_back(InternalEvent::Resize(new_bounds))
1171 }
1172 }
1173
1174 ///Write the Input payload to the tty.
1175 fn write_to_pty(&self, input: String) {
1176 self.pty_tx.notify(input.into_bytes());
1177 }
1178
1179 fn write_bytes_to_pty(&self, input: Vec<u8>) {
1180 self.pty_tx.notify(input);
1181 }
1182
1183 pub fn input(&mut self, input: String) {
1184 self.events
1185 .push_back(InternalEvent::Scroll(AlacScroll::Bottom));
1186 self.events.push_back(InternalEvent::SetSelection(None));
1187
1188 self.write_to_pty(input);
1189 }
1190
1191 pub fn input_bytes(&mut self, input: Vec<u8>) {
1192 self.events
1193 .push_back(InternalEvent::Scroll(AlacScroll::Bottom));
1194 self.events.push_back(InternalEvent::SetSelection(None));
1195
1196 self.write_bytes_to_pty(input);
1197 }
1198
1199 pub fn toggle_vi_mode(&mut self) {
1200 self.events.push_back(InternalEvent::ToggleViMode);
1201 }
1202
1203 pub fn vi_motion(&mut self, keystroke: &Keystroke) {
1204 if !self.vi_mode_enabled {
1205 return;
1206 }
1207
1208 let mut key = keystroke.key.clone();
1209 if keystroke.modifiers.shift {
1210 key = key.to_uppercase();
1211 }
1212
1213 let motion: Option<ViMotion> = match key.as_str() {
1214 "h" | "left" => Some(ViMotion::Left),
1215 "j" | "down" => Some(ViMotion::Down),
1216 "k" | "up" => Some(ViMotion::Up),
1217 "l" | "right" => Some(ViMotion::Right),
1218 "w" => Some(ViMotion::WordRight),
1219 "b" if !keystroke.modifiers.control => Some(ViMotion::WordLeft),
1220 "e" => Some(ViMotion::WordRightEnd),
1221 "%" => Some(ViMotion::Bracket),
1222 "$" => Some(ViMotion::Last),
1223 "0" => Some(ViMotion::First),
1224 "^" => Some(ViMotion::FirstOccupied),
1225 "H" => Some(ViMotion::High),
1226 "M" => Some(ViMotion::Middle),
1227 "L" => Some(ViMotion::Low),
1228 _ => None,
1229 };
1230
1231 if let Some(motion) = motion {
1232 let cursor = self.last_content.cursor.point;
1233 let cursor_pos = Point {
1234 x: cursor.column.0 as f32 * self.last_content.terminal_bounds.cell_width,
1235 y: cursor.line.0 as f32 * self.last_content.terminal_bounds.line_height,
1236 };
1237 self.events
1238 .push_back(InternalEvent::UpdateSelection(cursor_pos));
1239 self.events.push_back(InternalEvent::ViMotion(motion));
1240 return;
1241 }
1242
1243 let scroll_motion = match key.as_str() {
1244 "g" => Some(AlacScroll::Top),
1245 "G" => Some(AlacScroll::Bottom),
1246 "b" if keystroke.modifiers.control => Some(AlacScroll::PageUp),
1247 "f" if keystroke.modifiers.control => Some(AlacScroll::PageDown),
1248 "d" if keystroke.modifiers.control => {
1249 let amount = self.last_content.terminal_bounds.line_height().to_f64() as i32 / 2;
1250 Some(AlacScroll::Delta(-amount))
1251 }
1252 "u" if keystroke.modifiers.control => {
1253 let amount = self.last_content.terminal_bounds.line_height().to_f64() as i32 / 2;
1254 Some(AlacScroll::Delta(amount))
1255 }
1256 _ => None,
1257 };
1258
1259 if let Some(scroll_motion) = scroll_motion {
1260 self.events.push_back(InternalEvent::Scroll(scroll_motion));
1261 return;
1262 }
1263
1264 match key.as_str() {
1265 "v" => {
1266 let point = self.last_content.cursor.point;
1267 let selection_type = SelectionType::Simple;
1268 let side = AlacDirection::Right;
1269 let selection = Selection::new(selection_type, point, side);
1270 self.events
1271 .push_back(InternalEvent::SetSelection(Some((selection, point))));
1272 return;
1273 }
1274
1275 "escape" => {
1276 self.events.push_back(InternalEvent::SetSelection(None));
1277 return;
1278 }
1279
1280 "y" => {
1281 self.events.push_back(InternalEvent::Copy);
1282 self.events.push_back(InternalEvent::SetSelection(None));
1283 return;
1284 }
1285
1286 "i" => {
1287 self.scroll_to_bottom();
1288 self.toggle_vi_mode();
1289 return;
1290 }
1291 _ => {}
1292 }
1293 }
1294
1295 pub fn try_keystroke(&mut self, keystroke: &Keystroke, alt_is_meta: bool) -> bool {
1296 if self.vi_mode_enabled {
1297 self.vi_motion(keystroke);
1298 return true;
1299 }
1300
1301 // Keep default terminal behavior
1302 let esc = to_esc_str(keystroke, &self.last_content.mode, alt_is_meta);
1303 if let Some(esc) = esc {
1304 self.input(esc);
1305 true
1306 } else {
1307 false
1308 }
1309 }
1310
1311 pub fn try_modifiers_change(
1312 &mut self,
1313 modifiers: &Modifiers,
1314 window: &Window,
1315 cx: &mut Context<Self>,
1316 ) {
1317 if self
1318 .last_content
1319 .terminal_bounds
1320 .bounds
1321 .contains(&window.mouse_position())
1322 && modifiers.secondary()
1323 {
1324 self.refresh_hovered_word(window);
1325 }
1326 cx.notify();
1327 }
1328
1329 ///Paste text into the terminal
1330 pub fn paste(&mut self, text: &str) {
1331 let paste_text = if self.last_content.mode.contains(TermMode::BRACKETED_PASTE) {
1332 format!("{}{}{}", "\x1b[200~", text.replace('\x1b', ""), "\x1b[201~")
1333 } else {
1334 text.replace("\r\n", "\r").replace('\n', "\r")
1335 };
1336
1337 self.input(paste_text);
1338 }
1339
1340 pub fn sync(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1341 let term = self.term.clone();
1342 let mut terminal = term.lock_unfair();
1343 //Note that the ordering of events matters for event processing
1344 while let Some(e) = self.events.pop_front() {
1345 self.process_terminal_event(&e, &mut terminal, window, cx)
1346 }
1347
1348 self.last_content = Self::make_content(&terminal, &self.last_content);
1349 }
1350
1351 fn make_content(term: &Term<ZedListener>, last_content: &TerminalContent) -> TerminalContent {
1352 let content = term.renderable_content();
1353 TerminalContent {
1354 cells: content
1355 .display_iter
1356 //TODO: Add this once there's a way to retain empty lines
1357 // .filter(|ic| {
1358 // !ic.flags.contains(Flags::HIDDEN)
1359 // && !(ic.bg == Named(NamedColor::Background)
1360 // && ic.c == ' '
1361 // && !ic.flags.contains(Flags::INVERSE))
1362 // })
1363 .map(|ic| IndexedCell {
1364 point: ic.point,
1365 cell: ic.cell.clone(),
1366 })
1367 .collect::<Vec<IndexedCell>>(),
1368 mode: content.mode,
1369 display_offset: content.display_offset,
1370 selection_text: term.selection_to_string(),
1371 selection: content.selection,
1372 cursor: content.cursor,
1373 cursor_char: term.grid()[content.cursor.point].c,
1374 terminal_bounds: last_content.terminal_bounds,
1375 last_hovered_word: last_content.last_hovered_word.clone(),
1376 }
1377 }
1378
1379 pub fn last_n_non_empty_lines(&self, n: usize) -> Vec<String> {
1380 let term = self.term.clone();
1381 let terminal = term.lock_unfair();
1382
1383 let mut lines = Vec::new();
1384 let mut current_line = terminal.bottommost_line();
1385 while lines.len() < n {
1386 let mut line_buffer = String::new();
1387 for cell in &terminal.grid()[current_line] {
1388 line_buffer.push(cell.c);
1389 }
1390 let line = line_buffer.trim_end();
1391 if !line.is_empty() {
1392 lines.push(line.to_string());
1393 }
1394
1395 if current_line == terminal.topmost_line() {
1396 break;
1397 }
1398 current_line = Line(current_line.0 - 1);
1399 }
1400 lines.reverse();
1401 lines
1402 }
1403
1404 pub fn focus_in(&self) {
1405 if self.last_content.mode.contains(TermMode::FOCUS_IN_OUT) {
1406 self.write_to_pty("\x1b[I".to_string());
1407 }
1408 }
1409
1410 pub fn focus_out(&mut self) {
1411 if self.last_content.mode.contains(TermMode::FOCUS_IN_OUT) {
1412 self.write_to_pty("\x1b[O".to_string());
1413 }
1414 }
1415
1416 pub fn mouse_changed(&mut self, point: AlacPoint, side: AlacDirection) -> bool {
1417 match self.last_mouse {
1418 Some((old_point, old_side)) => {
1419 if old_point == point && old_side == side {
1420 false
1421 } else {
1422 self.last_mouse = Some((point, side));
1423 true
1424 }
1425 }
1426 None => {
1427 self.last_mouse = Some((point, side));
1428 true
1429 }
1430 }
1431 }
1432
1433 pub fn mouse_mode(&self, shift: bool) -> bool {
1434 self.last_content.mode.intersects(TermMode::MOUSE_MODE) && !shift
1435 }
1436
1437 pub fn mouse_move(&mut self, e: &MouseMoveEvent, cx: &mut Context<Self>) {
1438 let position = e.position - self.last_content.terminal_bounds.bounds.origin;
1439 if self.mouse_mode(e.modifiers.shift) {
1440 let (point, side) = grid_point_and_side(
1441 position,
1442 self.last_content.terminal_bounds,
1443 self.last_content.display_offset,
1444 );
1445
1446 if self.mouse_changed(point, side) {
1447 if let Some(bytes) =
1448 mouse_moved_report(point, e.pressed_button, e.modifiers, self.last_content.mode)
1449 {
1450 self.pty_tx.notify(bytes);
1451 }
1452 }
1453 } else if e.modifiers.secondary() {
1454 self.word_from_position(e.position);
1455 }
1456 cx.notify();
1457 }
1458
1459 fn word_from_position(&mut self, position: Point<Pixels>) {
1460 if self.selection_phase == SelectionPhase::Selecting {
1461 self.last_content.last_hovered_word = None;
1462 } else if self.last_content.terminal_bounds.bounds.contains(&position) {
1463 self.events.push_back(InternalEvent::FindHyperlink(
1464 position - self.last_content.terminal_bounds.bounds.origin,
1465 false,
1466 ));
1467 } else {
1468 self.last_content.last_hovered_word = None;
1469 }
1470 }
1471
1472 pub fn mouse_drag(
1473 &mut self,
1474 e: &MouseMoveEvent,
1475 region: Bounds<Pixels>,
1476 cx: &mut Context<Self>,
1477 ) {
1478 let position = e.position - self.last_content.terminal_bounds.bounds.origin;
1479 if !self.mouse_mode(e.modifiers.shift) {
1480 self.selection_phase = SelectionPhase::Selecting;
1481 // Alacritty has the same ordering, of first updating the selection
1482 // then scrolling 15ms later
1483 self.events
1484 .push_back(InternalEvent::UpdateSelection(position));
1485
1486 // Doesn't make sense to scroll the alt screen
1487 if !self.last_content.mode.contains(TermMode::ALT_SCREEN) {
1488 let scroll_delta = match self.drag_line_delta(e, region) {
1489 Some(value) => value,
1490 None => return,
1491 };
1492
1493 let scroll_lines =
1494 (scroll_delta / self.last_content.terminal_bounds.line_height) as i32;
1495
1496 self.events
1497 .push_back(InternalEvent::Scroll(AlacScroll::Delta(scroll_lines)));
1498 }
1499
1500 cx.notify();
1501 }
1502 }
1503
1504 fn drag_line_delta(&self, e: &MouseMoveEvent, region: Bounds<Pixels>) -> Option<Pixels> {
1505 //TODO: Why do these need to be doubled? Probably the same problem that the IME has
1506 let top = region.origin.y + (self.last_content.terminal_bounds.line_height * 2.);
1507 let bottom = region.bottom_left().y - (self.last_content.terminal_bounds.line_height * 2.);
1508 let scroll_delta = if e.position.y < top {
1509 (top - e.position.y).pow(1.1)
1510 } else if e.position.y > bottom {
1511 -((e.position.y - bottom).pow(1.1))
1512 } else {
1513 return None; //Nothing to do
1514 };
1515 Some(scroll_delta)
1516 }
1517
1518 pub fn mouse_down(&mut self, e: &MouseDownEvent, _cx: &mut Context<Self>) {
1519 let position = e.position - self.last_content.terminal_bounds.bounds.origin;
1520 let point = grid_point(
1521 position,
1522 self.last_content.terminal_bounds,
1523 self.last_content.display_offset,
1524 );
1525
1526 if self.mouse_mode(e.modifiers.shift) {
1527 if let Some(bytes) =
1528 mouse_button_report(point, e.button, e.modifiers, true, self.last_content.mode)
1529 {
1530 self.pty_tx.notify(bytes);
1531 }
1532 } else {
1533 match e.button {
1534 MouseButton::Left => {
1535 let (point, side) = grid_point_and_side(
1536 position,
1537 self.last_content.terminal_bounds,
1538 self.last_content.display_offset,
1539 );
1540
1541 let selection_type = match e.click_count {
1542 0 => return, //This is a release
1543 1 => Some(SelectionType::Simple),
1544 2 => Some(SelectionType::Semantic),
1545 3 => Some(SelectionType::Lines),
1546 _ => None,
1547 };
1548
1549 if selection_type == Some(SelectionType::Simple) && e.modifiers.shift {
1550 self.events
1551 .push_back(InternalEvent::UpdateSelection(position));
1552 return;
1553 }
1554
1555 let selection = selection_type
1556 .map(|selection_type| Selection::new(selection_type, point, side));
1557
1558 if let Some(sel) = selection {
1559 self.events
1560 .push_back(InternalEvent::SetSelection(Some((sel, point))));
1561 }
1562 }
1563 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1564 MouseButton::Middle => {
1565 if let Some(item) = _cx.read_from_primary() {
1566 let text = item.text().unwrap_or_default().to_string();
1567 self.input(text);
1568 }
1569 }
1570 _ => {}
1571 }
1572 }
1573 }
1574
1575 pub fn mouse_up(&mut self, e: &MouseUpEvent, cx: &Context<Self>) {
1576 let setting = TerminalSettings::get_global(cx);
1577
1578 let position = e.position - self.last_content.terminal_bounds.bounds.origin;
1579 if self.mouse_mode(e.modifiers.shift) {
1580 let point = grid_point(
1581 position,
1582 self.last_content.terminal_bounds,
1583 self.last_content.display_offset,
1584 );
1585
1586 if let Some(bytes) =
1587 mouse_button_report(point, e.button, e.modifiers, false, self.last_content.mode)
1588 {
1589 self.pty_tx.notify(bytes);
1590 }
1591 } else {
1592 if e.button == MouseButton::Left && setting.copy_on_select {
1593 self.copy();
1594 }
1595
1596 //Hyperlinks
1597 if self.selection_phase == SelectionPhase::Ended {
1598 let mouse_cell_index =
1599 content_index_for_mouse(position, &self.last_content.terminal_bounds);
1600 if let Some(link) = self.last_content.cells[mouse_cell_index].hyperlink() {
1601 cx.open_url(link.uri());
1602 } else if e.modifiers.secondary() {
1603 self.events
1604 .push_back(InternalEvent::FindHyperlink(position, true));
1605 }
1606 }
1607 }
1608
1609 self.selection_phase = SelectionPhase::Ended;
1610 self.last_mouse = None;
1611 }
1612
1613 ///Scroll the terminal
1614 pub fn scroll_wheel(&mut self, e: &ScrollWheelEvent) {
1615 let mouse_mode = self.mouse_mode(e.shift);
1616
1617 if let Some(scroll_lines) = self.determine_scroll_lines(e, mouse_mode) {
1618 if mouse_mode {
1619 let point = grid_point(
1620 e.position - self.last_content.terminal_bounds.bounds.origin,
1621 self.last_content.terminal_bounds,
1622 self.last_content.display_offset,
1623 );
1624
1625 if let Some(scrolls) = scroll_report(point, scroll_lines, e, self.last_content.mode)
1626 {
1627 for scroll in scrolls {
1628 self.pty_tx.notify(scroll);
1629 }
1630 };
1631 } else if self
1632 .last_content
1633 .mode
1634 .contains(TermMode::ALT_SCREEN | TermMode::ALTERNATE_SCROLL)
1635 && !e.shift
1636 {
1637 self.pty_tx.notify(alt_scroll(scroll_lines))
1638 } else if scroll_lines != 0 {
1639 let scroll = AlacScroll::Delta(scroll_lines);
1640
1641 self.events.push_back(InternalEvent::Scroll(scroll));
1642 }
1643 }
1644 }
1645
1646 fn refresh_hovered_word(&mut self, window: &Window) {
1647 self.word_from_position(window.mouse_position());
1648 }
1649
1650 fn determine_scroll_lines(&mut self, e: &ScrollWheelEvent, mouse_mode: bool) -> Option<i32> {
1651 let scroll_multiplier = if mouse_mode { 1. } else { SCROLL_MULTIPLIER };
1652 let line_height = self.last_content.terminal_bounds.line_height;
1653 match e.touch_phase {
1654 /* Reset scroll state on started */
1655 TouchPhase::Started => {
1656 self.scroll_px = px(0.);
1657 None
1658 }
1659 /* Calculate the appropriate scroll lines */
1660 TouchPhase::Moved => {
1661 let old_offset = (self.scroll_px / line_height) as i32;
1662
1663 self.scroll_px += e.delta.pixel_delta(line_height).y * scroll_multiplier;
1664
1665 let new_offset = (self.scroll_px / line_height) as i32;
1666
1667 // Whenever we hit the edges, reset our stored scroll to 0
1668 // so we can respond to changes in direction quickly
1669 self.scroll_px %= self.last_content.terminal_bounds.height();
1670
1671 Some(new_offset - old_offset)
1672 }
1673 TouchPhase::Ended => None,
1674 }
1675 }
1676
1677 pub fn find_matches(
1678 &self,
1679 mut searcher: RegexSearch,
1680 cx: &Context<Self>,
1681 ) -> Task<Vec<RangeInclusive<AlacPoint>>> {
1682 let term = self.term.clone();
1683 cx.background_spawn(async move {
1684 let term = term.lock();
1685
1686 all_search_matches(&term, &mut searcher).collect()
1687 })
1688 }
1689
1690 pub fn working_directory(&self) -> Option<PathBuf> {
1691 if self.is_ssh_terminal {
1692 // We can't yet reliably detect the working directory of a shell on the
1693 // SSH host. Until we can do that, it doesn't make sense to display
1694 // the working directory on the client and persist that.
1695 None
1696 } else {
1697 self.client_side_working_directory()
1698 }
1699 }
1700
1701 /// Returns the working directory of the process that's connected to the PTY.
1702 /// That means it returns the working directory of the local shell or program
1703 /// that's running inside the terminal.
1704 ///
1705 /// This does *not* return the working directory of the shell that runs on the
1706 /// remote host, in case Zed is connected to a remote host.
1707 fn client_side_working_directory(&self) -> Option<PathBuf> {
1708 self.pty_info
1709 .current
1710 .as_ref()
1711 .map(|process| process.cwd.clone())
1712 }
1713
1714 pub fn title(&self, truncate: bool) -> String {
1715 const MAX_CHARS: usize = 25;
1716 match &self.task {
1717 Some(task_state) => {
1718 if truncate {
1719 truncate_and_trailoff(&task_state.label, MAX_CHARS)
1720 } else {
1721 task_state.full_label.clone()
1722 }
1723 }
1724 None => self
1725 .title_override
1726 .as_ref()
1727 .map(|title_override| title_override.to_string())
1728 .unwrap_or_else(|| {
1729 self.pty_info
1730 .current
1731 .as_ref()
1732 .map(|fpi| {
1733 let process_file = fpi
1734 .cwd
1735 .file_name()
1736 .map(|name| name.to_string_lossy().to_string())
1737 .unwrap_or_default();
1738
1739 let argv = fpi.argv.clone();
1740 let process_name = format!(
1741 "{}{}",
1742 fpi.name,
1743 if !argv.is_empty() {
1744 format!(" {}", (argv[1..]).join(" "))
1745 } else {
1746 "".to_string()
1747 }
1748 );
1749 let (process_file, process_name) = if truncate {
1750 (
1751 truncate_and_trailoff(&process_file, MAX_CHARS),
1752 truncate_and_trailoff(&process_name, MAX_CHARS),
1753 )
1754 } else {
1755 (process_file, process_name)
1756 };
1757 format!("{process_file} — {process_name}")
1758 })
1759 .unwrap_or_else(|| "Terminal".to_string())
1760 }),
1761 }
1762 }
1763
1764 pub fn task(&self) -> Option<&TaskState> {
1765 self.task.as_ref()
1766 }
1767
1768 pub fn wait_for_completed_task(&self, cx: &App) -> Task<()> {
1769 if let Some(task) = self.task() {
1770 if task.status == TaskStatus::Running {
1771 let completion_receiver = task.completion_rx.clone();
1772 return cx.spawn(|_| async move {
1773 let _ = completion_receiver.recv().await;
1774 });
1775 }
1776 }
1777 Task::ready(())
1778 }
1779
1780 fn register_task_finished(&mut self, error_code: Option<i32>, cx: &mut Context<'_, Terminal>) {
1781 self.completion_tx.try_send(()).ok();
1782 let task = match &mut self.task {
1783 Some(task) => task,
1784 None => {
1785 if error_code.is_none() {
1786 cx.emit(Event::CloseTerminal);
1787 }
1788 return;
1789 }
1790 };
1791 if task.status != TaskStatus::Running {
1792 return;
1793 }
1794 match error_code {
1795 Some(error_code) => {
1796 task.status.register_task_exit(error_code);
1797 }
1798 None => {
1799 task.status.register_terminal_exit();
1800 }
1801 };
1802
1803 let (finished_successfully, task_line, command_line) = task_summary(task, error_code);
1804 let mut lines_to_show = Vec::new();
1805 if task.show_summary {
1806 lines_to_show.push(task_line.as_str());
1807 }
1808 if task.show_command {
1809 lines_to_show.push(command_line.as_str());
1810 }
1811
1812 if !lines_to_show.is_empty() {
1813 // SAFETY: the invocation happens on non `TaskStatus::Running` tasks, once,
1814 // after either `AlacTermEvent::Exit` or `AlacTermEvent::ChildExit` events that are spawned
1815 // when Zed task finishes and no more output is made.
1816 // After the task summary is output once, no more text is appended to the terminal.
1817 unsafe { append_text_to_term(&mut self.term.lock(), &lines_to_show) };
1818 }
1819
1820 match task.hide {
1821 HideStrategy::Never => {}
1822 HideStrategy::Always => {
1823 cx.emit(Event::CloseTerminal);
1824 }
1825 HideStrategy::OnSuccess => {
1826 if finished_successfully {
1827 cx.emit(Event::CloseTerminal);
1828 }
1829 }
1830 }
1831 }
1832}
1833
1834fn is_path_surrounded_by_common_symbols(path: &str) -> bool {
1835 // Avoid detecting `[]` or `()` strings as paths, surrounded by common symbols
1836 path.len() > 2
1837 // The rest of the brackets and various quotes cannot be matched by the [`WORD_REGEX`] hence not checked for.
1838 && (path.starts_with('[') && path.ends_with(']')
1839 || path.starts_with('(') && path.ends_with(')'))
1840}
1841
1842const TASK_DELIMITER: &str = "⏵ ";
1843fn task_summary(task: &TaskState, error_code: Option<i32>) -> (bool, String, String) {
1844 let escaped_full_label = task.full_label.replace("\r\n", "\r").replace('\n', "\r");
1845 let (success, task_line) = match error_code {
1846 Some(0) => {
1847 (true, format!("{TASK_DELIMITER}Task `{escaped_full_label}` finished successfully"))
1848 }
1849 Some(error_code) => {
1850 (false, format!("{TASK_DELIMITER}Task `{escaped_full_label}` finished with non-zero error code: {error_code}"))
1851 }
1852 None => {
1853 (false, format!("{TASK_DELIMITER}Task `{escaped_full_label}` finished"))
1854 }
1855 };
1856 let escaped_command_label = task.command_label.replace("\r\n", "\r").replace('\n', "\r");
1857 let command_line = format!("{TASK_DELIMITER}Command: {escaped_command_label}");
1858 (success, task_line, command_line)
1859}
1860
1861/// Appends a stringified task summary to the terminal, after its output.
1862///
1863/// SAFETY: This function should only be called after terminal's PTY is no longer alive.
1864/// New text being added to the terminal here, uses "less public" APIs,
1865/// which are not maintaining the entire terminal state intact.
1866///
1867///
1868/// The library
1869///
1870/// * does not increment inner grid cursor's _lines_ on `input` calls
1871/// (but displaying the lines correctly and incrementing cursor's columns)
1872///
1873/// * ignores `\n` and \r` character input, requiring the `newline` call instead
1874///
1875/// * does not alter grid state after `newline` call
1876/// so its `bottommost_line` is always the same additions, and
1877/// the cursor's `point` is not updated to the new line and column values
1878///
1879/// * ??? there could be more consequences, and any further "proper" streaming from the PTY might bug and/or panic.
1880/// Still, subsequent `append_text_to_term` invocations are possible and display the contents correctly.
1881///
1882/// Despite the quirks, this is the simplest approach to appending text to the terminal: its alternative, `grid_mut` manipulations,
1883/// do not properly set the scrolling state and display odd text after appending; also those manipulations are more tedious and error-prone.
1884/// The function achieves proper display and scrolling capabilities, at a cost of grid state not properly synchronized.
1885/// This is enough for printing moderately-sized texts like task summaries, but might break or perform poorly for larger texts.
1886unsafe fn append_text_to_term(term: &mut Term<ZedListener>, text_lines: &[&str]) {
1887 term.newline();
1888 term.grid_mut().cursor.point.column = Column(0);
1889 for line in text_lines {
1890 for c in line.chars() {
1891 term.input(c);
1892 }
1893 term.newline();
1894 term.grid_mut().cursor.point.column = Column(0);
1895 }
1896}
1897
1898impl Drop for Terminal {
1899 fn drop(&mut self) {
1900 self.pty_tx.0.send(Msg::Shutdown).ok();
1901 }
1902}
1903
1904impl EventEmitter<Event> for Terminal {}
1905
1906/// Based on alacritty/src/display/hint.rs > regex_match_at
1907/// Retrieve the match, if the specified point is inside the content matching the regex.
1908fn regex_match_at<T>(term: &Term<T>, point: AlacPoint, regex: &mut RegexSearch) -> Option<Match> {
1909 visible_regex_match_iter(term, regex).find(|rm| rm.contains(&point))
1910}
1911
1912/// Copied from alacritty/src/display/hint.rs:
1913/// Iterate over all visible regex matches.
1914pub fn visible_regex_match_iter<'a, T>(
1915 term: &'a Term<T>,
1916 regex: &'a mut RegexSearch,
1917) -> impl Iterator<Item = Match> + 'a {
1918 let viewport_start = Line(-(term.grid().display_offset() as i32));
1919 let viewport_end = viewport_start + term.bottommost_line();
1920 let mut start = term.line_search_left(AlacPoint::new(viewport_start, Column(0)));
1921 let mut end = term.line_search_right(AlacPoint::new(viewport_end, Column(0)));
1922 start.line = start.line.max(viewport_start - MAX_SEARCH_LINES);
1923 end.line = end.line.min(viewport_end + MAX_SEARCH_LINES);
1924
1925 RegexIter::new(start, end, AlacDirection::Right, term, regex)
1926 .skip_while(move |rm| rm.end().line < viewport_start)
1927 .take_while(move |rm| rm.start().line <= viewport_end)
1928}
1929
1930fn make_selection(range: &RangeInclusive<AlacPoint>) -> Selection {
1931 let mut selection = Selection::new(SelectionType::Simple, *range.start(), AlacDirection::Left);
1932 selection.update(*range.end(), AlacDirection::Right);
1933 selection
1934}
1935
1936fn all_search_matches<'a, T>(
1937 term: &'a Term<T>,
1938 regex: &'a mut RegexSearch,
1939) -> impl Iterator<Item = Match> + 'a {
1940 let start = AlacPoint::new(term.grid().topmost_line(), Column(0));
1941 let end = AlacPoint::new(term.grid().bottommost_line(), term.grid().last_column());
1942 RegexIter::new(start, end, AlacDirection::Right, term, regex)
1943}
1944
1945fn content_index_for_mouse(pos: Point<Pixels>, terminal_bounds: &TerminalBounds) -> usize {
1946 let col = (pos.x / terminal_bounds.cell_width()).round() as usize;
1947 let clamped_col = min(col, terminal_bounds.columns() - 1);
1948 let row = (pos.y / terminal_bounds.line_height()).round() as usize;
1949 let clamped_row = min(row, terminal_bounds.screen_lines() - 1);
1950 clamped_row * terminal_bounds.columns() + clamped_col
1951}
1952
1953/// Converts an 8 bit ANSI color to its GPUI equivalent.
1954/// Accepts `usize` for compatibility with the `alacritty::Colors` interface,
1955/// Other than that use case, should only be called with values in the `[0,255]` range
1956pub fn get_color_at_index(index: usize, theme: &Theme) -> Hsla {
1957 let colors = theme.colors();
1958
1959 match index {
1960 // 0-15 are the same as the named colors above
1961 0 => colors.terminal_ansi_black,
1962 1 => colors.terminal_ansi_red,
1963 2 => colors.terminal_ansi_green,
1964 3 => colors.terminal_ansi_yellow,
1965 4 => colors.terminal_ansi_blue,
1966 5 => colors.terminal_ansi_magenta,
1967 6 => colors.terminal_ansi_cyan,
1968 7 => colors.terminal_ansi_white,
1969 8 => colors.terminal_ansi_bright_black,
1970 9 => colors.terminal_ansi_bright_red,
1971 10 => colors.terminal_ansi_bright_green,
1972 11 => colors.terminal_ansi_bright_yellow,
1973 12 => colors.terminal_ansi_bright_blue,
1974 13 => colors.terminal_ansi_bright_magenta,
1975 14 => colors.terminal_ansi_bright_cyan,
1976 15 => colors.terminal_ansi_bright_white,
1977 // 16-231 are mapped to their RGB colors on a 0-5 range per channel
1978 16..=231 => {
1979 let (r, g, b) = rgb_for_index(index as u8); // Split the index into its ANSI-RGB components
1980 let step = (u8::MAX as f32 / 5.).floor() as u8; // Split the RGB range into 5 chunks, with floor so no overflow
1981 rgba_color(r * step, g * step, b * step) // Map the ANSI-RGB components to an RGB color
1982 }
1983 // 232-255 are a 24 step grayscale from black to white
1984 232..=255 => {
1985 let i = index as u8 - 232; // Align index to 0..24
1986 let step = (u8::MAX as f32 / 24.).floor() as u8; // Split the RGB grayscale values into 24 chunks
1987 rgba_color(i * step, i * step, i * step) // Map the ANSI-grayscale components to the RGB-grayscale
1988 }
1989 // For compatibility with the alacritty::Colors interface
1990 256 => colors.text,
1991 257 => colors.background,
1992 258 => theme.players().local().cursor,
1993 259 => colors.terminal_ansi_dim_black,
1994 260 => colors.terminal_ansi_dim_red,
1995 261 => colors.terminal_ansi_dim_green,
1996 262 => colors.terminal_ansi_dim_yellow,
1997 263 => colors.terminal_ansi_dim_blue,
1998 264 => colors.terminal_ansi_dim_magenta,
1999 265 => colors.terminal_ansi_dim_cyan,
2000 266 => colors.terminal_ansi_dim_white,
2001 267 => colors.terminal_bright_foreground,
2002 268 => colors.terminal_ansi_black, // 'Dim Background', non-standard color
2003
2004 _ => black(),
2005 }
2006}
2007
2008/// Generates the RGB channels in [0, 5] for a given index into the 6x6x6 ANSI color cube.
2009/// See: [8 bit ANSI color](https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit).
2010///
2011/// Wikipedia gives a formula for calculating the index for a given color:
2012///
2013/// ```
2014/// index = 16 + 36 × r + 6 × g + b (0 ≤ r, g, b ≤ 5)
2015/// ```
2016///
2017/// This function does the reverse, calculating the `r`, `g`, and `b` components from a given index.
2018fn rgb_for_index(i: u8) -> (u8, u8, u8) {
2019 debug_assert!((16..=231).contains(&i));
2020 let i = i - 16;
2021 let r = (i - (i % 36)) / 36;
2022 let g = ((i % 36) - (i % 6)) / 6;
2023 let b = (i % 36) % 6;
2024 (r, g, b)
2025}
2026
2027pub fn rgba_color(r: u8, g: u8, b: u8) -> Hsla {
2028 Rgba {
2029 r: (r as f32 / 255.),
2030 g: (g as f32 / 255.),
2031 b: (b as f32 / 255.),
2032 a: 1.,
2033 }
2034 .into()
2035}
2036
2037#[cfg(test)]
2038mod tests {
2039 use alacritty_terminal::{
2040 index::{Column, Line, Point as AlacPoint},
2041 term::cell::Cell,
2042 };
2043 use gpui::{bounds, point, size, Pixels, Point};
2044 use rand::{distributions::Alphanumeric, rngs::ThreadRng, thread_rng, Rng};
2045
2046 use crate::{
2047 content_index_for_mouse, rgb_for_index, IndexedCell, TerminalBounds, TerminalContent,
2048 };
2049
2050 #[test]
2051 fn test_rgb_for_index() {
2052 // Test every possible value in the color cube.
2053 for i in 16..=231 {
2054 let (r, g, b) = rgb_for_index(i);
2055 assert_eq!(i, 16 + 36 * r + 6 * g + b);
2056 }
2057 }
2058
2059 #[test]
2060 fn test_mouse_to_cell_test() {
2061 let mut rng = thread_rng();
2062 const ITERATIONS: usize = 10;
2063 const PRECISION: usize = 1000;
2064
2065 for _ in 0..ITERATIONS {
2066 let viewport_cells = rng.gen_range(15..20);
2067 let cell_size = rng.gen_range(5 * PRECISION..20 * PRECISION) as f32 / PRECISION as f32;
2068
2069 let size = crate::TerminalBounds {
2070 cell_width: Pixels::from(cell_size),
2071 line_height: Pixels::from(cell_size),
2072 bounds: bounds(
2073 Point::default(),
2074 size(
2075 Pixels::from(cell_size * (viewport_cells as f32)),
2076 Pixels::from(cell_size * (viewport_cells as f32)),
2077 ),
2078 ),
2079 };
2080
2081 let cells = get_cells(size, &mut rng);
2082 let content = convert_cells_to_content(size, &cells);
2083
2084 for row in 0..(viewport_cells - 1) {
2085 let row = row as usize;
2086 for col in 0..(viewport_cells - 1) {
2087 let col = col as usize;
2088
2089 let row_offset = rng.gen_range(0..PRECISION) as f32 / PRECISION as f32;
2090 let col_offset = rng.gen_range(0..PRECISION) as f32 / PRECISION as f32;
2091
2092 let mouse_pos = point(
2093 Pixels::from(col as f32 * cell_size + col_offset),
2094 Pixels::from(row as f32 * cell_size + row_offset),
2095 );
2096
2097 let content_index =
2098 content_index_for_mouse(mouse_pos, &content.terminal_bounds);
2099 let mouse_cell = content.cells[content_index].c;
2100 let real_cell = cells[row][col];
2101
2102 assert_eq!(mouse_cell, real_cell);
2103 }
2104 }
2105 }
2106 }
2107
2108 #[test]
2109 fn test_mouse_to_cell_clamp() {
2110 let mut rng = thread_rng();
2111
2112 let size = crate::TerminalBounds {
2113 cell_width: Pixels::from(10.),
2114 line_height: Pixels::from(10.),
2115 bounds: bounds(
2116 Point::default(),
2117 size(Pixels::from(100.), Pixels::from(100.)),
2118 ),
2119 };
2120
2121 let cells = get_cells(size, &mut rng);
2122 let content = convert_cells_to_content(size, &cells);
2123
2124 assert_eq!(
2125 content.cells[content_index_for_mouse(
2126 point(Pixels::from(-10.), Pixels::from(-10.)),
2127 &content.terminal_bounds,
2128 )]
2129 .c,
2130 cells[0][0]
2131 );
2132 assert_eq!(
2133 content.cells[content_index_for_mouse(
2134 point(Pixels::from(1000.), Pixels::from(1000.)),
2135 &content.terminal_bounds,
2136 )]
2137 .c,
2138 cells[9][9]
2139 );
2140 }
2141
2142 fn get_cells(size: TerminalBounds, rng: &mut ThreadRng) -> Vec<Vec<char>> {
2143 let mut cells = Vec::new();
2144
2145 for _ in 0..((size.height() / size.line_height()) as usize) {
2146 let mut row_vec = Vec::new();
2147 for _ in 0..((size.width() / size.cell_width()) as usize) {
2148 let cell_char = rng.sample(Alphanumeric) as char;
2149 row_vec.push(cell_char)
2150 }
2151 cells.push(row_vec)
2152 }
2153
2154 cells
2155 }
2156
2157 fn convert_cells_to_content(
2158 terminal_bounds: TerminalBounds,
2159 cells: &[Vec<char>],
2160 ) -> TerminalContent {
2161 let mut ic = Vec::new();
2162
2163 for (index, row) in cells.iter().enumerate() {
2164 for (cell_index, cell_char) in row.iter().enumerate() {
2165 ic.push(IndexedCell {
2166 point: AlacPoint::new(Line(index as i32), Column(cell_index)),
2167 cell: Cell {
2168 c: *cell_char,
2169 ..Default::default()
2170 },
2171 });
2172 }
2173 }
2174
2175 TerminalContent {
2176 cells: ic,
2177 terminal_bounds,
2178 ..Default::default()
2179 }
2180 }
2181
2182 fn re_test(re: &str, hay: &str, expected: Vec<&str>) {
2183 let results: Vec<_> = regex::Regex::new(re)
2184 .unwrap()
2185 .find_iter(hay)
2186 .map(|m| m.as_str())
2187 .collect();
2188 assert_eq!(results, expected);
2189 }
2190 #[test]
2191 fn test_url_regex() {
2192 re_test(
2193 crate::URL_REGEX,
2194 "test http://example.com test mailto:bob@example.com train",
2195 vec!["http://example.com", "mailto:bob@example.com"],
2196 );
2197 }
2198 #[test]
2199 fn test_word_regex() {
2200 re_test(
2201 crate::WORD_REGEX,
2202 "hello, world! \"What\" is this?",
2203 vec!["hello", "world", "What", "is", "this"],
2204 );
2205 }
2206 #[test]
2207 fn test_word_regex_with_linenum() {
2208 // filename(line) and filename(line,col) as used in MSBuild output
2209 // should be considered a single "word", even though comma is
2210 // usually a word separator
2211 re_test(
2212 crate::WORD_REGEX,
2213 "a Main.cs(20) b",
2214 vec!["a", "Main.cs(20)", "b"],
2215 );
2216 re_test(
2217 crate::WORD_REGEX,
2218 "Main.cs(20,5) Error desc",
2219 vec!["Main.cs(20,5)", "Error", "desc"],
2220 );
2221 // filename:line:col is a popular format for unix tools
2222 re_test(
2223 crate::WORD_REGEX,
2224 "a Main.cs:20:5 b",
2225 vec!["a", "Main.cs:20:5", "b"],
2226 );
2227 // Some tools output "filename:line:col:message", which currently isn't
2228 // handled correctly, but might be in the future
2229 re_test(
2230 crate::WORD_REGEX,
2231 "Main.cs:20:5:Error desc",
2232 vec!["Main.cs:20:5:Error", "desc"],
2233 );
2234 }
2235}