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
19pub 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
36pub struct Terminal {
38 surface: NativeSurface,
39 focus: FocusHandle,
40 bounds: Bounds<Pixels>,
41 tick_task: Option<Task<()>>,
42}
43
44impl Terminal {
45 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 (key, implied_shift) = unshifted_macos_key(&keystroke.key);
140 let Some(keycode) = mac_keycode(key) else {
141 if matches!(action, KeyAction::Press | KeyAction::Repeat)
142 && !keystroke.modifiers.control
143 && !keystroke.modifiers.alt
144 && !keystroke.modifiers.platform
145 && let Some(text) = keystroke.key_char.as_deref()
146 && let Ok(text) = CString::new(text)
147 {
148 self.surface.text(&text);
149 }
150 return;
151 };
152 let text = keystroke
153 .key_char
154 .as_deref()
155 .and_then(|text| CString::new(text).ok());
156 let unshifted = key.chars().next().map_or(0, u32::from);
157 let mut key_modifiers = keystroke.modifiers;
158 key_modifiers.shift |= implied_shift;
159 let _ = self.surface.key(
160 action,
161 modifiers(key_modifiers),
162 keycode,
163 text.as_deref(),
164 unshifted,
165 );
166 }
167
168 fn mouse_position(&mut self, position: gpui::Point<Pixels>, modifiers: gpui::Modifiers) {
169 let x = f64::from(f32::from(position.x - self.bounds.origin.x));
170 let y = f64::from(f32::from(position.y - self.bounds.origin.y));
171 self.surface.mouse_position(x, y, modifiers.into());
172 }
173
174 fn mouse_down(&mut self, event: &MouseDownEvent, window: &mut Window, cx: &mut Context<Self>) {
175 self.focus.focus(window, cx);
176 self.surface.set_focus(true);
177 self.mouse_position(event.position, event.modifiers);
178 self.surface.mouse_button(
179 MouseState::Press,
180 event.button.into(),
181 event.modifiers.into(),
182 );
183 }
184
185 fn mouse_up(&mut self, event: &MouseUpEvent) {
186 self.mouse_position(event.position, event.modifiers);
187 self.surface.mouse_button(
188 MouseState::Release,
189 event.button.into(),
190 event.modifiers.into(),
191 );
192 }
193
194 fn scroll(&mut self, event: &ScrollWheelEvent) {
195 self.mouse_position(event.position, event.modifiers);
196 let (x, y, precision) = match event.delta {
197 ScrollDelta::Pixels(delta) => (
198 f64::from(f32::from(delta.x)),
199 f64::from(f32::from(delta.y)),
200 true,
201 ),
202 ScrollDelta::Lines(delta) => (f64::from(delta.x), f64::from(delta.y), false),
203 };
204 self.surface.mouse_scroll(x, y, precision);
205 }
206}
207
208impl Render for Terminal {
209 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
210 self.start_ticking(cx);
211 let terminal = cx.entity().downgrade();
212 div()
213 .key_context("Terminal")
214 .track_focus(&self.focus)
215 .size_full()
216 .min_h_0()
217 .child(
218 canvas(
219 move |bounds, _, cx| {
220 let _ = terminal.update(cx, |terminal, _| terminal.update_frame(bounds));
221 },
222 |_, _, _, _| {},
223 )
224 .absolute()
225 .size_full(),
226 )
227 .on_key_down(cx.listener(|terminal, event, _, _| terminal.key_down(event)))
228 .on_key_up(cx.listener(|terminal, event, _, _| terminal.key_up(event)))
229 .on_mouse_move(cx.listener(|terminal, event: &MouseMoveEvent, _, _| {
230 terminal.mouse_position(event.position, event.modifiers);
231 }))
232 .on_mouse_down(
233 gpui::MouseButton::Left,
234 cx.listener(|terminal, event, window, cx| terminal.mouse_down(event, window, cx)),
235 )
236 .on_mouse_down(
237 gpui::MouseButton::Middle,
238 cx.listener(|terminal, event, window, cx| terminal.mouse_down(event, window, cx)),
239 )
240 .on_mouse_down(
241 gpui::MouseButton::Right,
242 cx.listener(|terminal, event, window, cx| terminal.mouse_down(event, window, cx)),
243 )
244 .on_mouse_up(
245 gpui::MouseButton::Left,
246 cx.listener(|terminal, event, _, _| terminal.mouse_up(event)),
247 )
248 .on_mouse_up(
249 gpui::MouseButton::Middle,
250 cx.listener(|terminal, event, _, _| terminal.mouse_up(event)),
251 )
252 .on_mouse_up(
253 gpui::MouseButton::Right,
254 cx.listener(|terminal, event, _, _| terminal.mouse_up(event)),
255 )
256 .on_scroll_wheel(cx.listener(|terminal, event, _, _| terminal.scroll(event)))
257 }
258}
259
260impl From<gpui::Modifiers> for Modifiers {
261 fn from(value: gpui::Modifiers) -> Self {
262 modifiers(value)
263 }
264}
265
266impl From<gpui::MouseButton> for MouseButton {
267 fn from(value: gpui::MouseButton) -> Self {
268 match value {
269 gpui::MouseButton::Left => Self::Left,
270 gpui::MouseButton::Right => Self::Right,
271 gpui::MouseButton::Middle => Self::Middle,
272 gpui::MouseButton::Navigate(_) => Self::Unknown,
273 }
274 }
275}
276
277fn appkit_view(window: &Window) -> Result<NonNull<c_void>, String> {
278 let handle = raw_window_handle::HasWindowHandle::window_handle(window)
279 .map_err(|error| format!("read native window handle: {error}"))?;
280 match handle.as_raw() {
281 RawWindowHandle::AppKit(handle) => Ok(handle.ns_view),
282 _ => Err("libghostty native surfaces are currently available only on macOS".to_owned()),
283 }
284}
285
286fn modifiers(value: gpui::Modifiers) -> Modifiers {
287 let mut result = Modifiers::empty();
288 if value.shift {
289 result.insert(Modifiers::SHIFT);
290 }
291 if value.control {
292 result.insert(Modifiers::CONTROL);
293 }
294 if value.alt {
295 result.insert(Modifiers::ALT);
296 }
297 if value.platform {
298 result.insert(Modifiers::SUPER);
299 }
300 result
301}
302
303fn unshifted_macos_key(key: &str) -> (&str, bool) {
304 match key {
305 "!" => ("1", true),
306 "@" => ("2", true),
307 "#" => ("3", true),
308 "$" => ("4", true),
309 "%" => ("5", true),
310 "^" => ("6", true),
311 "&" => ("7", true),
312 "*" => ("8", true),
313 "(" => ("9", true),
314 ")" => ("0", true),
315 "_" => ("-", true),
316 "+" => ("=", true),
317 "{" => ("[", true),
318 "}" => ("]", true),
319 "|" => ("\\", true),
320 ":" => (";", true),
321 "\"" => ("'", true),
322 "<" => (",", true),
323 ">" => (".", true),
324 "?" => ("/", true),
325 "~" => ("`", true),
326 _ => (key, false),
327 }
328}
329
330fn mac_keycode(key: &str) -> Option<u32> {
331 Some(match key {
332 "a" => 0,
333 "s" => 1,
334 "d" => 2,
335 "f" => 3,
336 "h" => 4,
337 "g" => 5,
338 "z" => 6,
339 "x" => 7,
340 "c" => 8,
341 "v" => 9,
342 "b" => 11,
343 "q" => 12,
344 "w" => 13,
345 "e" => 14,
346 "r" => 15,
347 "y" => 16,
348 "t" => 17,
349 "1" => 18,
350 "2" => 19,
351 "3" => 20,
352 "4" => 21,
353 "6" => 22,
354 "5" => 23,
355 "=" => 24,
356 "9" => 25,
357 "7" => 26,
358 "-" => 27,
359 "8" => 28,
360 "0" => 29,
361 "]" => 30,
362 "o" => 31,
363 "u" => 32,
364 "[" => 33,
365 "i" => 34,
366 "p" => 35,
367 "enter" | "return" => 36,
368 "l" => 37,
369 "j" => 38,
370 "'" => 39,
371 "k" => 40,
372 ";" => 41,
373 "\\" => 42,
374 "," => 43,
375 "/" => 44,
376 "n" => 45,
377 "m" => 46,
378 "." => 47,
379 "tab" => 48,
380 "space" => 49,
381 "`" => 50,
382 "backspace" => 51,
383 "escape" => 53,
384 "f17" => 64,
385 "f18" => 79,
386 "f19" => 80,
387 "f20" => 90,
388 "f5" => 96,
389 "f6" => 97,
390 "f7" => 98,
391 "f3" => 99,
392 "f8" => 100,
393 "f9" => 101,
394 "f11" => 103,
395 "f13" => 105,
396 "f16" => 106,
397 "f14" => 107,
398 "f10" => 109,
399 "f12" => 111,
400 "f15" => 113,
401 "home" => 115,
402 "pageup" | "page_up" | "page-up" => 116,
403 "delete" => 117,
404 "f4" => 118,
405 "end" => 119,
406 "f2" => 120,
407 "pagedown" | "page_down" | "page-down" => 121,
408 "left" => 123,
409 "right" => 124,
410 "down" => 125,
411 "up" => 126,
412 _ => return None,
413 })
414}
415
416#[cfg(test)]
417mod tests {
418 use super::*;
419
420 #[test]
421 fn keycode_mapping_covers_terminal_navigation_and_repeat_keys() {
422 for key in ["j", "k", "up", "down", "pageup", "pagedown", "escape"] {
423 assert!(mac_keycode(key).is_some(), "missing keycode for {key}");
424 }
425 }
426
427 #[test]
428 fn shifted_punctuation_uses_a_physical_key_event() {
429 for (shifted, unshifted) in [
430 ("!", "1"),
431 ("*", "8"),
432 ("+", "="),
433 ("{", "["),
434 ("|", "\\"),
435 (":", ";"),
436 ("\"", "'"),
437 ("?", "/"),
438 ("~", "`"),
439 ] {
440 let (key, implied_shift) = unshifted_macos_key(shifted);
441 assert_eq!(key, unshifted);
442 assert!(implied_shift);
443 assert!(mac_keycode(key).is_some());
444 }
445 }
446}