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