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