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