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