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