terminal.rs

  1pub mod connected_el;
  2pub mod connected_view;
  3pub mod mappings;
  4pub mod modal;
  5pub mod terminal_view;
  6
  7use alacritty_terminal::{
  8    ansi::{ClearMode, Handler},
  9    config::{Config, Program, PtyConfig, Scrolling},
 10    event::{Event as AlacTermEvent, EventListener, Notify, WindowSize},
 11    event_loop::{EventLoop, Msg, Notifier},
 12    grid::{Dimensions, Scroll},
 13    index::{Direction, Point},
 14    selection::{Selection, SelectionType},
 15    sync::FairMutex,
 16    term::{RenderableContent, TermMode},
 17    tty::{self, setup_env},
 18    Term,
 19};
 20use anyhow::{bail, Result};
 21
 22use futures::{
 23    channel::mpsc::{unbounded, UnboundedReceiver, UnboundedSender},
 24    FutureExt,
 25};
 26
 27use mappings::mouse::mouse_moved_report;
 28use modal::deploy_modal;
 29use settings::{Settings, Shell, TerminalBlink};
 30use std::{collections::HashMap, fmt::Display, path::PathBuf, sync::Arc, time::Duration};
 31use thiserror::Error;
 32
 33use gpui::{
 34    geometry::vector::{vec2f, Vector2F},
 35    keymap::Keystroke,
 36    ClipboardItem, Entity, ModelContext, MouseMovedEvent, MutableAppContext,
 37};
 38
 39use crate::mappings::{
 40    colors::{get_color_at_index, to_alac_rgb},
 41    keys::to_esc_str,
 42};
 43
 44///Initialize and register all of our action handlers
 45pub fn init(cx: &mut MutableAppContext) {
 46    cx.add_action(deploy_modal);
 47
 48    terminal_view::init(cx);
 49    connected_view::init(cx);
 50}
 51
 52const DEBUG_TERMINAL_WIDTH: f32 = 500.;
 53const DEBUG_TERMINAL_HEIGHT: f32 = 30.;
 54const DEBUG_CELL_WIDTH: f32 = 5.;
 55const DEBUG_LINE_HEIGHT: f32 = 5.;
 56
 57///Upward flowing events, for changing the title and such
 58#[derive(Clone, Copy, Debug)]
 59pub enum Event {
 60    TitleChanged,
 61    CloseTerminal,
 62    Bell,
 63    Wakeup,
 64    BlinkChanged,
 65}
 66
 67#[derive(Clone, Debug)]
 68enum InternalEvent {
 69    TermEvent(AlacTermEvent),
 70    Resize(TerminalSize),
 71    Clear,
 72    Scroll(Scroll),
 73    SetSelection(Option<Selection>),
 74    UpdateSelection((Point, Direction)),
 75    Copy,
 76}
 77
 78///A translation struct for Alacritty to communicate with us from their event loop
 79#[derive(Clone)]
 80pub struct ZedListener(UnboundedSender<AlacTermEvent>);
 81
 82impl EventListener for ZedListener {
 83    fn send_event(&self, event: AlacTermEvent) {
 84        self.0.unbounded_send(event).ok();
 85    }
 86}
 87
 88#[derive(Clone, Copy, Debug)]
 89pub struct TerminalSize {
 90    cell_width: f32,
 91    line_height: f32,
 92    height: f32,
 93    width: f32,
 94}
 95
 96impl TerminalSize {
 97    pub fn new(line_height: f32, cell_width: f32, size: Vector2F) -> Self {
 98        TerminalSize {
 99            cell_width,
100            line_height,
101            width: size.x(),
102            height: size.y(),
103        }
104    }
105
106    pub fn num_lines(&self) -> usize {
107        (self.height / self.line_height).floor() as usize
108    }
109
110    pub fn num_columns(&self) -> usize {
111        (self.width / self.cell_width).floor() as usize
112    }
113
114    pub fn height(&self) -> f32 {
115        self.height
116    }
117
118    pub fn width(&self) -> f32 {
119        self.width
120    }
121
122    pub fn cell_width(&self) -> f32 {
123        self.cell_width
124    }
125
126    pub fn line_height(&self) -> f32 {
127        self.line_height
128    }
129}
130impl Default for TerminalSize {
131    fn default() -> Self {
132        TerminalSize::new(
133            DEBUG_LINE_HEIGHT,
134            DEBUG_CELL_WIDTH,
135            vec2f(DEBUG_TERMINAL_WIDTH, DEBUG_TERMINAL_HEIGHT),
136        )
137    }
138}
139
140impl From<TerminalSize> for WindowSize {
141    fn from(val: TerminalSize) -> Self {
142        WindowSize {
143            num_lines: val.num_lines() as u16,
144            num_cols: val.num_columns() as u16,
145            cell_width: val.cell_width() as u16,
146            cell_height: val.line_height() as u16,
147        }
148    }
149}
150
151impl Dimensions for TerminalSize {
152    fn total_lines(&self) -> usize {
153        self.screen_lines() //TODO: Check that this is fine. This is supposed to be for the back buffer...
154    }
155
156    fn screen_lines(&self) -> usize {
157        self.num_lines()
158    }
159
160    fn columns(&self) -> usize {
161        self.num_columns()
162    }
163}
164
165#[derive(Error, Debug)]
166pub struct TerminalError {
167    pub directory: Option<PathBuf>,
168    pub shell: Option<Shell>,
169    pub source: std::io::Error,
170}
171
172impl TerminalError {
173    pub fn fmt_directory(&self) -> String {
174        self.directory
175            .clone()
176            .map(|path| {
177                match path
178                    .into_os_string()
179                    .into_string()
180                    .map_err(|os_str| format!("<non-utf8 path> {}", os_str.to_string_lossy()))
181                {
182                    Ok(s) => s,
183                    Err(s) => s,
184                }
185            })
186            .unwrap_or_else(|| {
187                let default_dir =
188                    dirs::home_dir().map(|buf| buf.into_os_string().to_string_lossy().to_string());
189                match default_dir {
190                    Some(dir) => format!("<none specified, using home directory> {}", dir),
191                    None => "<none specified, could not find home directory>".to_string(),
192                }
193            })
194    }
195
196    pub fn shell_to_string(&self) -> Option<String> {
197        self.shell.as_ref().map(|shell| match shell {
198            Shell::System => "<system shell>".to_string(),
199            Shell::Program(p) => p.to_string(),
200            Shell::WithArguments { program, args } => format!("{} {}", program, args.join(" ")),
201        })
202    }
203
204    pub fn fmt_shell(&self) -> String {
205        self.shell
206            .clone()
207            .map(|shell| match shell {
208                Shell::System => {
209                    let mut buf = [0; 1024];
210                    let pw = alacritty_unix::get_pw_entry(&mut buf).ok();
211
212                    match pw {
213                        Some(pw) => format!("<system defined shell> {}", pw.shell),
214                        None => "<could not access the password file>".to_string(),
215                    }
216                }
217                Shell::Program(s) => s,
218                Shell::WithArguments { program, args } => format!("{} {}", program, args.join(" ")),
219            })
220            .unwrap_or_else(|| {
221                let mut buf = [0; 1024];
222                let pw = alacritty_unix::get_pw_entry(&mut buf).ok();
223                match pw {
224                    Some(pw) => {
225                        format!("<none specified, using system defined shell> {}", pw.shell)
226                    }
227                    None => "<none specified, could not access the password file> {}".to_string(),
228                }
229            })
230    }
231}
232
233impl Display for TerminalError {
234    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
235        let dir_string: String = self.fmt_directory();
236        let shell = self.fmt_shell();
237
238        write!(
239            f,
240            "Working directory: {} Shell command: `{}`, IOError: {}",
241            dir_string, shell, self.source
242        )
243    }
244}
245
246pub struct TerminalBuilder {
247    terminal: Terminal,
248    events_rx: UnboundedReceiver<AlacTermEvent>,
249}
250
251impl TerminalBuilder {
252    pub fn new(
253        working_directory: Option<PathBuf>,
254        shell: Option<Shell>,
255        env: Option<HashMap<String, String>>,
256        initial_size: TerminalSize,
257        blink_settings: Option<TerminalBlink>,
258    ) -> Result<TerminalBuilder> {
259        let pty_config = {
260            let alac_shell = shell.clone().and_then(|shell| match shell {
261                Shell::System => None,
262                Shell::Program(program) => Some(Program::Just(program)),
263                Shell::WithArguments { program, args } => Some(Program::WithArgs { program, args }),
264            });
265
266            PtyConfig {
267                shell: alac_shell,
268                working_directory: working_directory.clone(),
269                hold: false,
270            }
271        };
272
273        let mut env = env.unwrap_or_default();
274
275        //TODO: Properly set the current locale,
276        env.insert("LC_ALL".to_string(), "en_US.UTF-8".to_string());
277
278        let alac_scrolling = Scrolling::default();
279        // alac_scrolling.set_history((BACK_BUFFER_SIZE * 2) as u32);
280
281        let config = Config {
282            pty_config: pty_config.clone(),
283            env,
284            scrolling: alac_scrolling,
285            ..Default::default()
286        };
287
288        setup_env(&config);
289
290        //Spawn a task so the Alacritty EventLoop can communicate with us in a view context
291        //TODO: Remove with a bounded sender which can be dispatched on &self
292        let (events_tx, events_rx) = unbounded();
293        //Set up the terminal...
294        let mut term = Term::new(&config, &initial_size, ZedListener(events_tx.clone()));
295
296        //Start off blinking if we need to
297        if let Some(TerminalBlink::On) = blink_settings {
298            term.set_mode(alacritty_terminal::ansi::Mode::BlinkingCursor)
299        }
300
301        let term = Arc::new(FairMutex::new(term));
302
303        //Setup the pty...
304        let pty = match tty::new(&pty_config, initial_size.into(), None) {
305            Ok(pty) => pty,
306            Err(error) => {
307                bail!(TerminalError {
308                    directory: working_directory,
309                    shell,
310                    source: error,
311                });
312            }
313        };
314
315        let shell_txt = {
316            match shell {
317                Some(Shell::System) | None => {
318                    let mut buf = [0; 1024];
319                    let pw = alacritty_unix::get_pw_entry(&mut buf).unwrap();
320                    pw.shell.to_string()
321                }
322                Some(Shell::Program(program)) => program,
323                Some(Shell::WithArguments { program, args }) => {
324                    format!("{} {}", program, args.join(" "))
325                }
326            }
327        };
328
329        //And connect them together
330        let event_loop = EventLoop::new(
331            term.clone(),
332            ZedListener(events_tx.clone()),
333            pty,
334            pty_config.hold,
335            false,
336        );
337
338        //Kick things off
339        let pty_tx = event_loop.channel();
340        let _io_thread = event_loop.spawn();
341
342        let terminal = Terminal {
343            pty_tx: Notifier(pty_tx),
344            term,
345            events: vec![],
346            title: shell_txt.clone(),
347            default_title: shell_txt,
348            last_mode: TermMode::NONE,
349            cur_size: initial_size,
350            last_mouse: None,
351        };
352
353        Ok(TerminalBuilder {
354            terminal,
355            events_rx,
356        })
357    }
358
359    pub fn subscribe(mut self, cx: &mut ModelContext<Terminal>) -> Terminal {
360        //Event loop
361        cx.spawn_weak(|this, mut cx| async move {
362            use futures::StreamExt;
363
364            while let Some(event) = self.events_rx.next().await {
365                this.upgrade(&cx)?.update(&mut cx, |this, cx| {
366                    //Process the first event immediately for lowered latency
367                    this.process_event(&event, cx);
368                });
369
370                'outer: loop {
371                    let mut events = vec![];
372                    let mut timer = cx.background().timer(Duration::from_millis(4)).fuse();
373
374                    loop {
375                        futures::select_biased! {
376                            _ = timer => break,
377                            event = self.events_rx.next() => {
378                                if let Some(event) = event {
379                                    events.push(event);
380                                    if events.len() > 100 {
381                                        break;
382                                    }
383                                } else {
384                                    break;
385                                }
386                            },
387                        }
388                    }
389
390                    if events.is_empty() {
391                        smol::future::yield_now().await;
392                        break 'outer;
393                    } else {
394                        this.upgrade(&cx)?.update(&mut cx, |this, cx| {
395                            for event in events {
396                                this.process_event(&event, cx);
397                            }
398                        });
399                        smol::future::yield_now().await;
400                    }
401                }
402            }
403
404            Some(())
405        })
406        .detach();
407
408        self.terminal
409    }
410}
411
412pub struct Terminal {
413    pty_tx: Notifier,
414    term: Arc<FairMutex<Term<ZedListener>>>,
415    events: Vec<InternalEvent>,
416    default_title: String,
417    title: String,
418    cur_size: TerminalSize,
419    last_mode: TermMode,
420    last_mouse: Option<(Point, Direction)>,
421}
422
423impl Terminal {
424    fn process_event(&mut self, event: &AlacTermEvent, cx: &mut ModelContext<Self>) {
425        match event {
426            AlacTermEvent::Title(title) => {
427                self.title = title.to_string();
428                cx.emit(Event::TitleChanged);
429            }
430            AlacTermEvent::ResetTitle => {
431                self.title = self.default_title.clone();
432                cx.emit(Event::TitleChanged);
433            }
434            AlacTermEvent::ClipboardStore(_, data) => {
435                cx.write_to_clipboard(ClipboardItem::new(data.to_string()))
436            }
437            AlacTermEvent::ClipboardLoad(_, format) => self.write_to_pty(format(
438                &cx.read_from_clipboard()
439                    .map(|ci| ci.text().to_string())
440                    .unwrap_or_else(|| "".to_string()),
441            )),
442            AlacTermEvent::PtyWrite(out) => self.write_to_pty(out.clone()),
443            AlacTermEvent::TextAreaSizeRequest(format) => {
444                self.write_to_pty(format(self.cur_size.into()))
445            }
446            AlacTermEvent::CursorBlinkingChange => {
447                cx.emit(Event::BlinkChanged);
448            }
449            AlacTermEvent::Bell => {
450                cx.emit(Event::Bell);
451            }
452            AlacTermEvent::Exit => cx.emit(Event::CloseTerminal),
453            AlacTermEvent::MouseCursorDirty => {
454                //NOOP, Handled in render
455            }
456            AlacTermEvent::Wakeup => {
457                cx.emit(Event::Wakeup);
458                cx.notify();
459            }
460            AlacTermEvent::ColorRequest(_, _) => {
461                self.events.push(InternalEvent::TermEvent(event.clone()))
462            }
463        }
464    }
465
466    ///Takes events from Alacritty and translates them to behavior on this view
467    fn process_terminal_event(
468        &mut self,
469        event: &InternalEvent,
470        term: &mut Term<ZedListener>,
471        cx: &mut ModelContext<Self>,
472    ) {
473        match event {
474            InternalEvent::TermEvent(term_event) => {
475                if let AlacTermEvent::ColorRequest(index, format) = term_event {
476                    let color = term.colors()[*index].unwrap_or_else(|| {
477                        let term_style = &cx.global::<Settings>().theme.terminal;
478                        to_alac_rgb(get_color_at_index(index, &term_style.colors))
479                    });
480                    self.write_to_pty(format(color))
481                }
482            }
483            InternalEvent::Resize(new_size) => {
484                self.cur_size = *new_size;
485
486                self.pty_tx.0.send(Msg::Resize((*new_size).into())).ok();
487
488                term.resize(*new_size);
489            }
490            InternalEvent::Clear => {
491                self.write_to_pty("\x0c".to_string());
492                term.clear_screen(ClearMode::Saved);
493            }
494            InternalEvent::Scroll(scroll) => term.scroll_display(*scroll),
495            InternalEvent::SetSelection(sel) => term.selection = sel.clone(),
496            InternalEvent::UpdateSelection((point, side)) => {
497                if let Some(mut selection) = term.selection.take() {
498                    selection.update(*point, *side);
499                    term.selection = Some(selection);
500                }
501            }
502
503            InternalEvent::Copy => {
504                if let Some(txt) = term.selection_to_string() {
505                    cx.write_to_clipboard(ClipboardItem::new(txt))
506                }
507            }
508        }
509    }
510
511    pub fn input(&mut self, input: String) {
512        self.scroll(Scroll::Bottom);
513        self.events.push(InternalEvent::SetSelection(None));
514        self.write_to_pty(input);
515    }
516
517    ///Write the Input payload to the tty.
518    fn write_to_pty(&self, input: String) {
519        self.pty_tx.notify(input.into_bytes());
520    }
521
522    ///Resize the terminal and the PTY.
523    pub fn set_size(&mut self, new_size: TerminalSize) {
524        self.events.push(InternalEvent::Resize(new_size))
525    }
526
527    pub fn clear(&mut self) {
528        self.events.push(InternalEvent::Clear)
529    }
530
531    pub fn try_keystroke(&mut self, keystroke: &Keystroke) -> bool {
532        let esc = to_esc_str(keystroke, &self.last_mode);
533        if let Some(esc) = esc {
534            self.input(esc);
535            true
536        } else {
537            false
538        }
539    }
540
541    ///Paste text into the terminal
542    pub fn paste(&mut self, text: &str) {
543        let paste_text = if self.last_mode.contains(TermMode::BRACKETED_PASTE) {
544            format!("{}{}{}", "\x1b[200~", text.replace('\x1b', ""), "\x1b[201~")
545        } else {
546            text.replace("\r\n", "\r").replace('\n', "\r")
547        };
548        self.input(paste_text)
549    }
550
551    pub fn copy(&mut self) {
552        self.events.push(InternalEvent::Copy);
553    }
554
555    pub fn render_lock<F, T>(&mut self, cx: &mut ModelContext<Self>, f: F) -> T
556    where
557        F: FnOnce(RenderableContent, char) -> T,
558    {
559        let m = self.term.clone(); //Arc clone
560        let mut term = m.lock();
561
562        while let Some(e) = self.events.pop() {
563            self.process_terminal_event(&e, &mut term, cx)
564        }
565
566        // self.utilization = Self::estimate_utilization(term.take_last_processed_bytes());
567        self.last_mode = *term.mode();
568
569        let content = term.renderable_content();
570
571        let cursor_text = term.grid()[content.cursor.point].c;
572
573        f(content, cursor_text)
574    }
575
576    pub fn focus_in(&self) {
577        if self.last_mode.contains(TermMode::FOCUS_IN_OUT) {
578            self.write_to_pty("\x1b[I".to_string());
579        }
580    }
581
582    pub fn focus_out(&self) {
583        if self.last_mode.contains(TermMode::FOCUS_IN_OUT) {
584            self.write_to_pty("\x1b[O".to_string());
585        }
586    }
587
588    pub fn mouse_changed(&mut self, point: Point, side: Direction) -> bool {
589        match self.last_mouse {
590            Some((old_point, old_side)) => {
591                if old_point == point && old_side == side {
592                    false
593                } else {
594                    self.last_mouse = Some((point, side));
595                    true
596                }
597            }
598            None => {
599                self.last_mouse = Some((point, side));
600                true
601            }
602        }
603    }
604
605    /// Handle a mouse move
606    pub fn mouse_move(&mut self, point: Point, side: Direction, e: &MouseMovedEvent) {
607        if self.mouse_changed(point, side) {
608            if let Some(bytes) = mouse_moved_report(point, e, self.last_mode) {
609                self.pty_tx.notify(bytes);
610            }
611        }
612    }
613
614    pub fn mouse_drag(&mut self, point: Point, side: Direction) {
615        self.events
616            .push(InternalEvent::UpdateSelection((point, side)));
617    }
618
619    pub fn mouse_down(&mut self, point: Point, side: Direction) {
620        if self.last_mode.intersects(TermMode::MOUSE_REPORT_CLICK) {
621            //TODE: MOUSE MODE
622        } else {
623            self.events
624                .push(InternalEvent::SetSelection(Some(Selection::new(
625                    SelectionType::Simple,
626                    point,
627                    side,
628                ))));
629        }
630    }
631
632    pub fn click(&mut self, point: Point, side: Direction, clicks: usize) {
633        if self.last_mode.intersects(TermMode::MOUSE_MODE) {
634            //TODE: MOUSE MODE
635        } else {
636            let selection_type = match clicks {
637                0 => return, //This is a release
638                1 => Some(SelectionType::Simple),
639                2 => Some(SelectionType::Semantic),
640                3 => Some(SelectionType::Lines),
641                _ => None,
642            };
643
644            let selection =
645                selection_type.map(|selection_type| Selection::new(selection_type, point, side));
646
647            self.events.push(InternalEvent::SetSelection(selection));
648        }
649    }
650
651    ///Scroll the terminal
652    pub fn scroll(&mut self, scroll: Scroll) {
653        if self.last_mode.intersects(TermMode::MOUSE_MODE) {
654            //TODE: MOUSE MODE
655        }
656
657        self.events.push(InternalEvent::Scroll(scroll));
658    }
659}
660
661impl Drop for Terminal {
662    fn drop(&mut self) {
663        self.pty_tx.0.send(Msg::Shutdown).ok();
664    }
665}
666
667impl Entity for Terminal {
668    type Event = Event;
669}
670
671#[cfg(test)]
672mod tests {
673    pub mod terminal_test_context;
674}
675
676//TODO Move this around and clean up the code
677mod alacritty_unix {
678    use alacritty_terminal::config::Program;
679    use gpui::anyhow::{bail, Result};
680
681    use std::ffi::CStr;
682    use std::mem::MaybeUninit;
683    use std::ptr;
684
685    #[derive(Debug)]
686    pub struct Passwd<'a> {
687        _name: &'a str,
688        _dir: &'a str,
689        pub shell: &'a str,
690    }
691
692    /// Return a Passwd struct with pointers into the provided buf.
693    ///
694    /// # Unsafety
695    ///
696    /// If `buf` is changed while `Passwd` is alive, bad thing will almost certainly happen.
697    pub fn get_pw_entry(buf: &mut [i8; 1024]) -> Result<Passwd<'_>> {
698        // Create zeroed passwd struct.
699        let mut entry: MaybeUninit<libc::passwd> = MaybeUninit::uninit();
700
701        let mut res: *mut libc::passwd = ptr::null_mut();
702
703        // Try and read the pw file.
704        let uid = unsafe { libc::getuid() };
705        let status = unsafe {
706            libc::getpwuid_r(
707                uid,
708                entry.as_mut_ptr(),
709                buf.as_mut_ptr() as *mut _,
710                buf.len(),
711                &mut res,
712            )
713        };
714        let entry = unsafe { entry.assume_init() };
715
716        if status < 0 {
717            bail!("getpwuid_r failed");
718        }
719
720        if res.is_null() {
721            bail!("pw not found");
722        }
723
724        // Sanity check.
725        assert_eq!(entry.pw_uid, uid);
726
727        // Build a borrowed Passwd struct.
728        Ok(Passwd {
729            _name: unsafe { CStr::from_ptr(entry.pw_name).to_str().unwrap() },
730            _dir: unsafe { CStr::from_ptr(entry.pw_dir).to_str().unwrap() },
731            shell: unsafe { CStr::from_ptr(entry.pw_shell).to_str().unwrap() },
732        })
733    }
734
735    #[cfg(target_os = "macos")]
736    pub fn _default_shell(pw: &Passwd<'_>) -> Program {
737        let shell_name = pw.shell.rsplit('/').next().unwrap();
738        let argv = vec![
739            String::from("-c"),
740            format!("exec -a -{} {}", shell_name, pw.shell),
741        ];
742
743        Program::WithArgs {
744            program: "/bin/bash".to_owned(),
745            args: argv,
746        }
747    }
748
749    #[cfg(not(target_os = "macos"))]
750    pub fn default_shell(pw: &Passwd<'_>) -> Program {
751        Program::Just(env::var("SHELL").unwrap_or_else(|_| pw.shell.to_owned()))
752    }
753}