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