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