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