Skip to main content

gpui_libghostty/
terminal.rs

1use std::{
2    ffi::{CString, c_void},
3    path::PathBuf,
4    ptr::NonNull,
5    time::Duration,
6};
7
8use gpui::{
9    AppContext as _, Bounds, Context, Entity, FocusHandle, InteractiveElement as _, IntoElement,
10    KeyDownEvent, KeyUpEvent, MouseDownEvent, MouseMoveEvent, MouseUpEvent, ParentElement as _,
11    Pixels, Render, ScrollDelta, ScrollWheelEvent, Styled as _, Task, Window, canvas, div,
12};
13use raw_window_handle::RawWindowHandle;
14
15use crate::native::{KeyAction, Modifiers, MouseButton, MouseState, NativeSurface};
16
17const TICK_INTERVAL: Duration = Duration::from_millis(8);
18
19/// Configuration for a terminal process rendered by libghostty.
20pub struct TerminalOptions {
21    pub command: String,
22    pub working_directory: PathBuf,
23    pub focus_on_spawn: bool,
24}
25
26impl TerminalOptions {
27    pub fn new(command: impl Into<String>, working_directory: impl Into<PathBuf>) -> Self {
28        Self {
29            command: command.into(),
30            working_directory: working_directory.into(),
31            focus_on_spawn: true,
32        }
33    }
34}
35
36/// A GPUI entity backed by Ghostty's native macOS Metal surface.
37pub struct Terminal {
38    surface: NativeSurface,
39    focus: FocusHandle,
40    bounds: Bounds<Pixels>,
41    tick_task: Option<Task<()>>,
42}
43
44impl Terminal {
45    /// Spawns the configured command and attaches its native surface to `window`.
46    pub fn spawn<T: 'static>(
47        options: TerminalOptions,
48        window: &mut Window,
49        cx: &mut Context<T>,
50    ) -> Result<Entity<Self>, String> {
51        let working_directory =
52            CString::new(options.working_directory.to_string_lossy().as_bytes()).map_err(|_| {
53                format!(
54                    "terminal working directory contains a NUL byte: {}",
55                    options.working_directory.display()
56                )
57            })?;
58        let command = CString::new(options.command)
59            .map_err(|_| "terminal command contains a NUL byte".to_owned())?;
60        let parent_view = appkit_view(window)?;
61        let surface = NativeSurface::new(parent_view, &working_directory, &command)
62            .map_err(|error| format!("initialize libghostty: {error}"))?;
63        let focus = cx.focus_handle();
64        if options.focus_on_spawn {
65            focus.focus(window, cx);
66        }
67        Ok(cx.new(|_| Self {
68            surface,
69            focus,
70            bounds: Bounds::default(),
71            tick_task: None,
72        }))
73    }
74
75    pub fn is_alive(&self) -> bool {
76        self.surface.is_alive()
77    }
78
79    pub fn focus<T>(&mut self, window: &mut Window, cx: &mut Context<T>) {
80        self.surface.set_visible(true);
81        self.surface.set_focus(true);
82        self.focus.focus(window, cx);
83    }
84
85    pub fn set_visible(&mut self, visible: bool) {
86        self.surface.set_visible(visible);
87        self.surface.set_focus(visible);
88    }
89
90    fn start_ticking(&mut self, cx: &mut Context<Self>) {
91        if self.tick_task.is_some() {
92            return;
93        }
94        self.surface.tick();
95        let terminal = cx.entity().downgrade();
96        self.tick_task = Some(cx.spawn(async move |_, cx| {
97            loop {
98                cx.background_executor().timer(TICK_INTERVAL).await;
99                let updated = terminal.update(cx, |terminal, cx| {
100                    if terminal.surface.needs_tick() {
101                        terminal.surface.tick();
102                        cx.notify();
103                    }
104                });
105                if updated.is_err() {
106                    break;
107                }
108            }
109        }));
110    }
111
112    fn update_frame(&mut self, bounds: Bounds<Pixels>) {
113        self.bounds = bounds;
114        self.surface.set_frame(
115            f64::from(f32::from(bounds.origin.x)),
116            f64::from(f32::from(bounds.origin.y)),
117            f64::from(f32::from(bounds.size.width)),
118            f64::from(f32::from(bounds.size.height)),
119        );
120        self.surface.set_visible(true);
121    }
122
123    fn key_down(&mut self, event: &KeyDownEvent) {
124        self.send_key(
125            if event.is_held {
126                KeyAction::Repeat
127            } else {
128                KeyAction::Press
129            },
130            &event.keystroke,
131        );
132    }
133
134    fn key_up(&mut self, event: &KeyUpEvent) {
135        self.send_key(KeyAction::Release, &event.keystroke);
136    }
137
138    fn send_key(&mut self, action: KeyAction, keystroke: &gpui::Keystroke) {
139        let Some(keycode) = mac_keycode(&keystroke.key) else {
140            if matches!(action, KeyAction::Press | KeyAction::Repeat)
141                && !keystroke.modifiers.control
142                && !keystroke.modifiers.alt
143                && !keystroke.modifiers.platform
144                && let Some(text) = keystroke.key_char.as_deref()
145                && let Ok(text) = CString::new(text)
146            {
147                self.surface.text(&text);
148            }
149            return;
150        };
151        let text = keystroke
152            .key_char
153            .as_deref()
154            .and_then(|text| CString::new(text).ok());
155        let unshifted = keystroke.key.chars().next().map_or(0, u32::from);
156        let _ = self.surface.key(
157            action,
158            modifiers(keystroke.modifiers),
159            keycode,
160            text.as_deref(),
161            unshifted,
162        );
163    }
164
165    fn mouse_position(&mut self, position: gpui::Point<Pixels>, modifiers: gpui::Modifiers) {
166        let x = f64::from(f32::from(position.x - self.bounds.origin.x));
167        let y = f64::from(f32::from(position.y - self.bounds.origin.y));
168        self.surface.mouse_position(x, y, modifiers.into());
169    }
170
171    fn mouse_down(&mut self, event: &MouseDownEvent, window: &mut Window, cx: &mut Context<Self>) {
172        self.focus.focus(window, cx);
173        self.surface.set_focus(true);
174        self.mouse_position(event.position, event.modifiers);
175        self.surface.mouse_button(
176            MouseState::Press,
177            event.button.into(),
178            event.modifiers.into(),
179        );
180    }
181
182    fn mouse_up(&mut self, event: &MouseUpEvent) {
183        self.mouse_position(event.position, event.modifiers);
184        self.surface.mouse_button(
185            MouseState::Release,
186            event.button.into(),
187            event.modifiers.into(),
188        );
189    }
190
191    fn scroll(&mut self, event: &ScrollWheelEvent) {
192        self.mouse_position(event.position, event.modifiers);
193        let (x, y, precision) = match event.delta {
194            ScrollDelta::Pixels(delta) => (
195                f64::from(f32::from(delta.x)),
196                f64::from(f32::from(delta.y)),
197                true,
198            ),
199            ScrollDelta::Lines(delta) => (f64::from(delta.x), f64::from(delta.y), false),
200        };
201        self.surface.mouse_scroll(x, y, precision);
202    }
203}
204
205impl Render for Terminal {
206    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
207        self.start_ticking(cx);
208        let terminal = cx.entity().downgrade();
209        div()
210            .key_context("Terminal")
211            .track_focus(&self.focus)
212            .size_full()
213            .min_h_0()
214            .child(
215                canvas(
216                    move |bounds, _, cx| {
217                        let _ = terminal.update(cx, |terminal, _| terminal.update_frame(bounds));
218                    },
219                    |_, _, _, _| {},
220                )
221                .absolute()
222                .size_full(),
223            )
224            .on_key_down(cx.listener(|terminal, event, _, _| terminal.key_down(event)))
225            .on_key_up(cx.listener(|terminal, event, _, _| terminal.key_up(event)))
226            .on_mouse_move(cx.listener(|terminal, event: &MouseMoveEvent, _, _| {
227                terminal.mouse_position(event.position, event.modifiers);
228            }))
229            .on_mouse_down(
230                gpui::MouseButton::Left,
231                cx.listener(|terminal, event, window, cx| terminal.mouse_down(event, window, cx)),
232            )
233            .on_mouse_down(
234                gpui::MouseButton::Middle,
235                cx.listener(|terminal, event, window, cx| terminal.mouse_down(event, window, cx)),
236            )
237            .on_mouse_down(
238                gpui::MouseButton::Right,
239                cx.listener(|terminal, event, window, cx| terminal.mouse_down(event, window, cx)),
240            )
241            .on_mouse_up(
242                gpui::MouseButton::Left,
243                cx.listener(|terminal, event, _, _| terminal.mouse_up(event)),
244            )
245            .on_mouse_up(
246                gpui::MouseButton::Middle,
247                cx.listener(|terminal, event, _, _| terminal.mouse_up(event)),
248            )
249            .on_mouse_up(
250                gpui::MouseButton::Right,
251                cx.listener(|terminal, event, _, _| terminal.mouse_up(event)),
252            )
253            .on_scroll_wheel(cx.listener(|terminal, event, _, _| terminal.scroll(event)))
254    }
255}
256
257impl From<gpui::Modifiers> for Modifiers {
258    fn from(value: gpui::Modifiers) -> Self {
259        modifiers(value)
260    }
261}
262
263impl From<gpui::MouseButton> for MouseButton {
264    fn from(value: gpui::MouseButton) -> Self {
265        match value {
266            gpui::MouseButton::Left => Self::Left,
267            gpui::MouseButton::Right => Self::Right,
268            gpui::MouseButton::Middle => Self::Middle,
269            gpui::MouseButton::Navigate(_) => Self::Unknown,
270        }
271    }
272}
273
274fn appkit_view(window: &Window) -> Result<NonNull<c_void>, String> {
275    let handle = raw_window_handle::HasWindowHandle::window_handle(window)
276        .map_err(|error| format!("read native window handle: {error}"))?;
277    match handle.as_raw() {
278        RawWindowHandle::AppKit(handle) => Ok(handle.ns_view),
279        _ => Err("libghostty native surfaces are currently available only on macOS".to_owned()),
280    }
281}
282
283fn modifiers(value: gpui::Modifiers) -> Modifiers {
284    let mut result = Modifiers::empty();
285    if value.shift {
286        result.insert(Modifiers::SHIFT);
287    }
288    if value.control {
289        result.insert(Modifiers::CONTROL);
290    }
291    if value.alt {
292        result.insert(Modifiers::ALT);
293    }
294    if value.platform {
295        result.insert(Modifiers::SUPER);
296    }
297    result
298}
299
300fn mac_keycode(key: &str) -> Option<u32> {
301    Some(match key {
302        "a" => 0,
303        "s" => 1,
304        "d" => 2,
305        "f" => 3,
306        "h" => 4,
307        "g" => 5,
308        "z" => 6,
309        "x" => 7,
310        "c" => 8,
311        "v" => 9,
312        "b" => 11,
313        "q" => 12,
314        "w" => 13,
315        "e" => 14,
316        "r" => 15,
317        "y" => 16,
318        "t" => 17,
319        "1" => 18,
320        "2" => 19,
321        "3" => 20,
322        "4" => 21,
323        "6" => 22,
324        "5" => 23,
325        "=" => 24,
326        "9" => 25,
327        "7" => 26,
328        "-" => 27,
329        "8" => 28,
330        "0" => 29,
331        "]" => 30,
332        "o" => 31,
333        "u" => 32,
334        "[" => 33,
335        "i" => 34,
336        "p" => 35,
337        "enter" | "return" => 36,
338        "l" => 37,
339        "j" => 38,
340        "'" => 39,
341        "k" => 40,
342        ";" => 41,
343        "\\" => 42,
344        "," => 43,
345        "/" => 44,
346        "n" => 45,
347        "m" => 46,
348        "." => 47,
349        "tab" => 48,
350        "space" => 49,
351        "`" => 50,
352        "backspace" => 51,
353        "escape" => 53,
354        "f17" => 64,
355        "f18" => 79,
356        "f19" => 80,
357        "f20" => 90,
358        "f5" => 96,
359        "f6" => 97,
360        "f7" => 98,
361        "f3" => 99,
362        "f8" => 100,
363        "f9" => 101,
364        "f11" => 103,
365        "f13" => 105,
366        "f16" => 106,
367        "f14" => 107,
368        "f10" => 109,
369        "f12" => 111,
370        "f15" => 113,
371        "home" => 115,
372        "pageup" | "page_up" | "page-up" => 116,
373        "delete" => 117,
374        "f4" => 118,
375        "end" => 119,
376        "f2" => 120,
377        "pagedown" | "page_down" | "page-down" => 121,
378        "left" => 123,
379        "right" => 124,
380        "down" => 125,
381        "up" => 126,
382        _ => return None,
383    })
384}
385
386#[cfg(test)]
387mod tests {
388    use super::*;
389
390    #[test]
391    fn keycode_mapping_covers_terminal_navigation_and_repeat_keys() {
392        for key in ["j", "k", "up", "down", "pageup", "pagedown", "escape"] {
393            assert!(mac_keycode(key).is_some(), "missing keycode for {key}");
394        }
395    }
396}