diff --git a/apps/mobile/app.config.ts b/apps/mobile/app.config.ts index 00a667391e..b832d5d290 100644 --- a/apps/mobile/app.config.ts +++ b/apps/mobile/app.config.ts @@ -114,6 +114,14 @@ const config: ExpoConfig = { }, }, ], + [ + "expo-build-properties", + { + ios: { + deploymentTarget: "16.1", + }, + }, + ], "expo-secure-store", "expo-router", "./plugins/withAndroidCleartextTraffic.cjs", diff --git a/apps/mobile/modules/t3-terminal/README.md b/apps/mobile/modules/t3-terminal/README.md new file mode 100644 index 0000000000..021d19ac2f --- /dev/null +++ b/apps/mobile/modules/t3-terminal/README.md @@ -0,0 +1,25 @@ +# T3 Mobile Terminal Native Module + +This local Expo module owns the native terminal surface for the mobile app. + +The JavaScript contract is intentionally small: + +- input from the native surface is emitted as `{ data: string }` +- resize from the native surface is emitted as `{ cols: number, rows: number }` +- remote PTY output is delivered by the existing `WsRpcClient.terminal` RPC stream + +The iOS implementation uses the vendored `GhosttyKit.xcframework` built from the same custom-I/O +Ghostty fork used by VVTerm. `T3TerminalView` owns a `libghostty` surface and mirrors VVTerm's +custom I/O model: + +1. initialize libghostty once for the process +2. create one Ghostty app and surface per native view +3. feed remote output into the surface with `ghostty_surface_feed_data` +4. send user input back to JS with the write callback +5. emit Ghostty's measured terminal size through `onResize` + +Android currently implements the same view name (`T3TerminalSurface`) and event payloads so the +React Native screen and RPC code stay platform-neutral. The renderer backend can be replaced with a +future Android Ghostty build without changing JS. + +Vendored Ghostty revision and license details are in `THIRD_PARTY_NOTICES.md`. diff --git a/apps/mobile/modules/t3-terminal/T3TerminalNative.podspec b/apps/mobile/modules/t3-terminal/T3TerminalNative.podspec new file mode 100644 index 0000000000..2d40f97769 --- /dev/null +++ b/apps/mobile/modules/t3-terminal/T3TerminalNative.podspec @@ -0,0 +1,21 @@ +require 'json' + +package = JSON.parse(File.read(File.join(__dir__, 'package.json'))) + +Pod::Spec.new do |s| + s.name = 'T3TerminalNative' + s.version = package['version'] + s.summary = 'Native terminal surface for T3 Code mobile.' + s.description = 'Native terminal surface bridge used by the T3 Code React Native app.' + s.homepage = 'https://t3tools.com' + s.license = { :type => 'UNLICENSED' } + s.author = { 'T3 Tools' => 'hello@t3tools.com' } + s.platforms = { :ios => '16.1' } + s.source = { :path => '.' } + s.source_files = 'ios/**/*.{h,m,mm,swift}' + s.vendored_frameworks = 'Vendor/libghostty/GhosttyKit.xcframework' + s.frameworks = 'IOSurface', 'Metal', 'MetalKit', 'QuartzCore', 'UIKit' + s.libraries = 'c++', 'z' + s.swift_version = '5.9' + s.dependency 'ExpoModulesCore' +end diff --git a/apps/mobile/modules/t3-terminal/THIRD_PARTY_NOTICES.md b/apps/mobile/modules/t3-terminal/THIRD_PARTY_NOTICES.md new file mode 100644 index 0000000000..a8d9998735 --- /dev/null +++ b/apps/mobile/modules/t3-terminal/THIRD_PARTY_NOTICES.md @@ -0,0 +1,15 @@ +# Third-Party Notices + +## Ghostty / libghostty + +The iOS terminal renderer vendors `GhosttyKit.xcframework`, a libghostty build produced from +VVTerm's custom-I/O Ghostty fork. + +- Upstream project: https://github.com/ghostty-org/ghostty +- Vendored source fork: https://github.com/wiedymi/ghostty +- Vendored revision: `268a0a9d761fb19673f05d28042488e2002300f2` +- Reference integration: https://github.com/vivy-company/vvterm +- License: MIT + +Ghostty's MIT license applies to the vendored framework. Keep this notice in sync when updating +`Vendor/libghostty`. diff --git a/apps/mobile/modules/t3-terminal/Vendor/libghostty/GhosttyKit.xcframework/Info.plist b/apps/mobile/modules/t3-terminal/Vendor/libghostty/GhosttyKit.xcframework/Info.plist new file mode 100644 index 0000000000..a433fb7f04 --- /dev/null +++ b/apps/mobile/modules/t3-terminal/Vendor/libghostty/GhosttyKit.xcframework/Info.plist @@ -0,0 +1,47 @@ + + + + + AvailableLibraries + + + BinaryPath + libghostty-fat.a + HeadersPath + Headers + LibraryIdentifier + ios-arm64 + LibraryPath + libghostty-fat.a + SupportedArchitectures + + arm64 + + SupportedPlatform + ios + + + BinaryPath + libghostty-fat.a + HeadersPath + Headers + LibraryIdentifier + ios-arm64-simulator + LibraryPath + libghostty-fat.a + SupportedArchitectures + + arm64 + + SupportedPlatform + ios + SupportedPlatformVariant + simulator + + + CFBundlePackageType + XFWK + XCFrameworkFormatVersion + 1.0 + + diff --git a/apps/mobile/modules/t3-terminal/Vendor/libghostty/GhosttyKit.xcframework/ios-arm64-simulator/Headers/ghostty.h b/apps/mobile/modules/t3-terminal/Vendor/libghostty/GhosttyKit.xcframework/ios-arm64-simulator/Headers/ghostty.h new file mode 100644 index 0000000000..08b88d595b --- /dev/null +++ b/apps/mobile/modules/t3-terminal/Vendor/libghostty/GhosttyKit.xcframework/ios-arm64-simulator/Headers/ghostty.h @@ -0,0 +1,1187 @@ +// Ghostty embedding API. The documentation for the embedding API is +// only within the Zig source files that define the implementations. This +// isn't meant to be a general purpose embedding API (yet) so there hasn't +// been documentation or example work beyond that. +// +// The only consumer of this API is the macOS app, but the API is built to +// be more general purpose. +#ifndef GHOSTTY_H +#define GHOSTTY_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include +#include +#include + +//------------------------------------------------------------------- +// Macros + +#define GHOSTTY_SUCCESS 0 + +//------------------------------------------------------------------- +// Types + +// Opaque types +typedef void* ghostty_app_t; +typedef void* ghostty_config_t; +typedef void* ghostty_surface_t; +typedef void* ghostty_inspector_t; + +// All the types below are fully defined and must be kept in sync with +// their Zig counterparts. Any changes to these types MUST have an associated +// Zig change. +typedef enum { + GHOSTTY_PLATFORM_INVALID, + GHOSTTY_PLATFORM_MACOS, + GHOSTTY_PLATFORM_IOS, +} ghostty_platform_e; + +// Callback for custom I/O write handler. +typedef void (*ghostty_surface_write_fn)(void* userdata, + const uint8_t* data, + size_t len); + +typedef enum { + GHOSTTY_CLIPBOARD_STANDARD, + GHOSTTY_CLIPBOARD_SELECTION, +} ghostty_clipboard_e; + +typedef struct { + const char *mime; + const char *data; +} ghostty_clipboard_content_s; + +typedef enum { + GHOSTTY_CLIPBOARD_REQUEST_PASTE, + GHOSTTY_CLIPBOARD_REQUEST_OSC_52_READ, + GHOSTTY_CLIPBOARD_REQUEST_OSC_52_WRITE, +} ghostty_clipboard_request_e; + +typedef enum { + GHOSTTY_MOUSE_RELEASE, + GHOSTTY_MOUSE_PRESS, +} ghostty_input_mouse_state_e; + +typedef enum { + GHOSTTY_MOUSE_UNKNOWN, + GHOSTTY_MOUSE_LEFT, + GHOSTTY_MOUSE_RIGHT, + GHOSTTY_MOUSE_MIDDLE, + GHOSTTY_MOUSE_FOUR, + GHOSTTY_MOUSE_FIVE, + GHOSTTY_MOUSE_SIX, + GHOSTTY_MOUSE_SEVEN, + GHOSTTY_MOUSE_EIGHT, + GHOSTTY_MOUSE_NINE, + GHOSTTY_MOUSE_TEN, + GHOSTTY_MOUSE_ELEVEN, +} ghostty_input_mouse_button_e; + +typedef enum { + GHOSTTY_MOUSE_MOMENTUM_NONE, + GHOSTTY_MOUSE_MOMENTUM_BEGAN, + GHOSTTY_MOUSE_MOMENTUM_STATIONARY, + GHOSTTY_MOUSE_MOMENTUM_CHANGED, + GHOSTTY_MOUSE_MOMENTUM_ENDED, + GHOSTTY_MOUSE_MOMENTUM_CANCELLED, + GHOSTTY_MOUSE_MOMENTUM_MAY_BEGIN, +} ghostty_input_mouse_momentum_e; + +typedef enum { + GHOSTTY_COLOR_SCHEME_LIGHT = 0, + GHOSTTY_COLOR_SCHEME_DARK = 1, +} ghostty_color_scheme_e; + +// This is a packed struct (see src/input/mouse.zig) but the C standard +// afaik doesn't let us reliably define packed structs so we build it up +// from scratch. +typedef int ghostty_input_scroll_mods_t; + +typedef enum { + GHOSTTY_MODS_NONE = 0, + GHOSTTY_MODS_SHIFT = 1 << 0, + GHOSTTY_MODS_CTRL = 1 << 1, + GHOSTTY_MODS_ALT = 1 << 2, + GHOSTTY_MODS_SUPER = 1 << 3, + GHOSTTY_MODS_CAPS = 1 << 4, + GHOSTTY_MODS_NUM = 1 << 5, + GHOSTTY_MODS_SHIFT_RIGHT = 1 << 6, + GHOSTTY_MODS_CTRL_RIGHT = 1 << 7, + GHOSTTY_MODS_ALT_RIGHT = 1 << 8, + GHOSTTY_MODS_SUPER_RIGHT = 1 << 9, +} ghostty_input_mods_e; + +typedef enum { + GHOSTTY_BINDING_FLAGS_CONSUMED = 1 << 0, + GHOSTTY_BINDING_FLAGS_ALL = 1 << 1, + GHOSTTY_BINDING_FLAGS_GLOBAL = 1 << 2, + GHOSTTY_BINDING_FLAGS_PERFORMABLE = 1 << 3, +} ghostty_binding_flags_e; + +typedef enum { + GHOSTTY_ACTION_RELEASE, + GHOSTTY_ACTION_PRESS, + GHOSTTY_ACTION_REPEAT, +} ghostty_input_action_e; + +// Based on: https://www.w3.org/TR/uievents-code/ +typedef enum { + GHOSTTY_KEY_UNIDENTIFIED, + + // "Writing System Keys" § 3.1.1 + GHOSTTY_KEY_BACKQUOTE, + GHOSTTY_KEY_BACKSLASH, + GHOSTTY_KEY_BRACKET_LEFT, + GHOSTTY_KEY_BRACKET_RIGHT, + GHOSTTY_KEY_COMMA, + GHOSTTY_KEY_DIGIT_0, + GHOSTTY_KEY_DIGIT_1, + GHOSTTY_KEY_DIGIT_2, + GHOSTTY_KEY_DIGIT_3, + GHOSTTY_KEY_DIGIT_4, + GHOSTTY_KEY_DIGIT_5, + GHOSTTY_KEY_DIGIT_6, + GHOSTTY_KEY_DIGIT_7, + GHOSTTY_KEY_DIGIT_8, + GHOSTTY_KEY_DIGIT_9, + GHOSTTY_KEY_EQUAL, + GHOSTTY_KEY_INTL_BACKSLASH, + GHOSTTY_KEY_INTL_RO, + GHOSTTY_KEY_INTL_YEN, + GHOSTTY_KEY_A, + GHOSTTY_KEY_B, + GHOSTTY_KEY_C, + GHOSTTY_KEY_D, + GHOSTTY_KEY_E, + GHOSTTY_KEY_F, + GHOSTTY_KEY_G, + GHOSTTY_KEY_H, + GHOSTTY_KEY_I, + GHOSTTY_KEY_J, + GHOSTTY_KEY_K, + GHOSTTY_KEY_L, + GHOSTTY_KEY_M, + GHOSTTY_KEY_N, + GHOSTTY_KEY_O, + GHOSTTY_KEY_P, + GHOSTTY_KEY_Q, + GHOSTTY_KEY_R, + GHOSTTY_KEY_S, + GHOSTTY_KEY_T, + GHOSTTY_KEY_U, + GHOSTTY_KEY_V, + GHOSTTY_KEY_W, + GHOSTTY_KEY_X, + GHOSTTY_KEY_Y, + GHOSTTY_KEY_Z, + GHOSTTY_KEY_MINUS, + GHOSTTY_KEY_PERIOD, + GHOSTTY_KEY_QUOTE, + GHOSTTY_KEY_SEMICOLON, + GHOSTTY_KEY_SLASH, + + // "Functional Keys" § 3.1.2 + GHOSTTY_KEY_ALT_LEFT, + GHOSTTY_KEY_ALT_RIGHT, + GHOSTTY_KEY_BACKSPACE, + GHOSTTY_KEY_CAPS_LOCK, + GHOSTTY_KEY_CONTEXT_MENU, + GHOSTTY_KEY_CONTROL_LEFT, + GHOSTTY_KEY_CONTROL_RIGHT, + GHOSTTY_KEY_ENTER, + GHOSTTY_KEY_META_LEFT, + GHOSTTY_KEY_META_RIGHT, + GHOSTTY_KEY_SHIFT_LEFT, + GHOSTTY_KEY_SHIFT_RIGHT, + GHOSTTY_KEY_SPACE, + GHOSTTY_KEY_TAB, + GHOSTTY_KEY_CONVERT, + GHOSTTY_KEY_KANA_MODE, + GHOSTTY_KEY_NON_CONVERT, + + // "Control Pad Section" § 3.2 + GHOSTTY_KEY_DELETE, + GHOSTTY_KEY_END, + GHOSTTY_KEY_HELP, + GHOSTTY_KEY_HOME, + GHOSTTY_KEY_INSERT, + GHOSTTY_KEY_PAGE_DOWN, + GHOSTTY_KEY_PAGE_UP, + + // "Arrow Pad Section" § 3.3 + GHOSTTY_KEY_ARROW_DOWN, + GHOSTTY_KEY_ARROW_LEFT, + GHOSTTY_KEY_ARROW_RIGHT, + GHOSTTY_KEY_ARROW_UP, + + // "Numpad Section" § 3.4 + GHOSTTY_KEY_NUM_LOCK, + GHOSTTY_KEY_NUMPAD_0, + GHOSTTY_KEY_NUMPAD_1, + GHOSTTY_KEY_NUMPAD_2, + GHOSTTY_KEY_NUMPAD_3, + GHOSTTY_KEY_NUMPAD_4, + GHOSTTY_KEY_NUMPAD_5, + GHOSTTY_KEY_NUMPAD_6, + GHOSTTY_KEY_NUMPAD_7, + GHOSTTY_KEY_NUMPAD_8, + GHOSTTY_KEY_NUMPAD_9, + GHOSTTY_KEY_NUMPAD_ADD, + GHOSTTY_KEY_NUMPAD_BACKSPACE, + GHOSTTY_KEY_NUMPAD_CLEAR, + GHOSTTY_KEY_NUMPAD_CLEAR_ENTRY, + GHOSTTY_KEY_NUMPAD_COMMA, + GHOSTTY_KEY_NUMPAD_DECIMAL, + GHOSTTY_KEY_NUMPAD_DIVIDE, + GHOSTTY_KEY_NUMPAD_ENTER, + GHOSTTY_KEY_NUMPAD_EQUAL, + GHOSTTY_KEY_NUMPAD_MEMORY_ADD, + GHOSTTY_KEY_NUMPAD_MEMORY_CLEAR, + GHOSTTY_KEY_NUMPAD_MEMORY_RECALL, + GHOSTTY_KEY_NUMPAD_MEMORY_STORE, + GHOSTTY_KEY_NUMPAD_MEMORY_SUBTRACT, + GHOSTTY_KEY_NUMPAD_MULTIPLY, + GHOSTTY_KEY_NUMPAD_PAREN_LEFT, + GHOSTTY_KEY_NUMPAD_PAREN_RIGHT, + GHOSTTY_KEY_NUMPAD_SUBTRACT, + GHOSTTY_KEY_NUMPAD_SEPARATOR, + GHOSTTY_KEY_NUMPAD_UP, + GHOSTTY_KEY_NUMPAD_DOWN, + GHOSTTY_KEY_NUMPAD_RIGHT, + GHOSTTY_KEY_NUMPAD_LEFT, + GHOSTTY_KEY_NUMPAD_BEGIN, + GHOSTTY_KEY_NUMPAD_HOME, + GHOSTTY_KEY_NUMPAD_END, + GHOSTTY_KEY_NUMPAD_INSERT, + GHOSTTY_KEY_NUMPAD_DELETE, + GHOSTTY_KEY_NUMPAD_PAGE_UP, + GHOSTTY_KEY_NUMPAD_PAGE_DOWN, + + // "Function Section" § 3.5 + GHOSTTY_KEY_ESCAPE, + GHOSTTY_KEY_F1, + GHOSTTY_KEY_F2, + GHOSTTY_KEY_F3, + GHOSTTY_KEY_F4, + GHOSTTY_KEY_F5, + GHOSTTY_KEY_F6, + GHOSTTY_KEY_F7, + GHOSTTY_KEY_F8, + GHOSTTY_KEY_F9, + GHOSTTY_KEY_F10, + GHOSTTY_KEY_F11, + GHOSTTY_KEY_F12, + GHOSTTY_KEY_F13, + GHOSTTY_KEY_F14, + GHOSTTY_KEY_F15, + GHOSTTY_KEY_F16, + GHOSTTY_KEY_F17, + GHOSTTY_KEY_F18, + GHOSTTY_KEY_F19, + GHOSTTY_KEY_F20, + GHOSTTY_KEY_F21, + GHOSTTY_KEY_F22, + GHOSTTY_KEY_F23, + GHOSTTY_KEY_F24, + GHOSTTY_KEY_F25, + GHOSTTY_KEY_FN, + GHOSTTY_KEY_FN_LOCK, + GHOSTTY_KEY_PRINT_SCREEN, + GHOSTTY_KEY_SCROLL_LOCK, + GHOSTTY_KEY_PAUSE, + + // "Media Keys" § 3.6 + GHOSTTY_KEY_BROWSER_BACK, + GHOSTTY_KEY_BROWSER_FAVORITES, + GHOSTTY_KEY_BROWSER_FORWARD, + GHOSTTY_KEY_BROWSER_HOME, + GHOSTTY_KEY_BROWSER_REFRESH, + GHOSTTY_KEY_BROWSER_SEARCH, + GHOSTTY_KEY_BROWSER_STOP, + GHOSTTY_KEY_EJECT, + GHOSTTY_KEY_LAUNCH_APP_1, + GHOSTTY_KEY_LAUNCH_APP_2, + GHOSTTY_KEY_LAUNCH_MAIL, + GHOSTTY_KEY_MEDIA_PLAY_PAUSE, + GHOSTTY_KEY_MEDIA_SELECT, + GHOSTTY_KEY_MEDIA_STOP, + GHOSTTY_KEY_MEDIA_TRACK_NEXT, + GHOSTTY_KEY_MEDIA_TRACK_PREVIOUS, + GHOSTTY_KEY_POWER, + GHOSTTY_KEY_SLEEP, + GHOSTTY_KEY_AUDIO_VOLUME_DOWN, + GHOSTTY_KEY_AUDIO_VOLUME_MUTE, + GHOSTTY_KEY_AUDIO_VOLUME_UP, + GHOSTTY_KEY_WAKE_UP, + + // "Legacy, Non-standard, and Special Keys" § 3.7 + GHOSTTY_KEY_COPY, + GHOSTTY_KEY_CUT, + GHOSTTY_KEY_PASTE, +} ghostty_input_key_e; + +typedef struct { + ghostty_input_action_e action; + ghostty_input_mods_e mods; + ghostty_input_mods_e consumed_mods; + uint32_t keycode; + const char* text; + uint32_t unshifted_codepoint; + bool composing; +} ghostty_input_key_s; + +typedef enum { + GHOSTTY_TRIGGER_PHYSICAL, + GHOSTTY_TRIGGER_UNICODE, + GHOSTTY_TRIGGER_CATCH_ALL, +} ghostty_input_trigger_tag_e; + +typedef union { + ghostty_input_key_e translated; + ghostty_input_key_e physical; + uint32_t unicode; + // catch_all has no payload +} ghostty_input_trigger_key_u; + +typedef struct { + ghostty_input_trigger_tag_e tag; + ghostty_input_trigger_key_u key; + ghostty_input_mods_e mods; +} ghostty_input_trigger_s; + +typedef struct { + const char* action_key; + const char* action; + const char* title; + const char* description; +} ghostty_command_s; + +typedef enum { + GHOSTTY_BUILD_MODE_DEBUG, + GHOSTTY_BUILD_MODE_RELEASE_SAFE, + GHOSTTY_BUILD_MODE_RELEASE_FAST, + GHOSTTY_BUILD_MODE_RELEASE_SMALL, +} ghostty_build_mode_e; + +typedef struct { + ghostty_build_mode_e build_mode; + const char* version; + uintptr_t version_len; +} ghostty_info_s; + +typedef struct { + const char* message; +} ghostty_diagnostic_s; + +typedef struct { + const char* ptr; + uintptr_t len; + bool sentinel; +} ghostty_string_s; + +typedef struct { + double tl_px_x; + double tl_px_y; + uint32_t offset_start; + uint32_t offset_len; + const char* text; + uintptr_t text_len; +} ghostty_text_s; + +typedef enum { + GHOSTTY_POINT_ACTIVE, + GHOSTTY_POINT_VIEWPORT, + GHOSTTY_POINT_SCREEN, + GHOSTTY_POINT_SURFACE, +} ghostty_point_tag_e; + +typedef enum { + GHOSTTY_POINT_COORD_EXACT, + GHOSTTY_POINT_COORD_TOP_LEFT, + GHOSTTY_POINT_COORD_BOTTOM_RIGHT, +} ghostty_point_coord_e; + +typedef struct { + ghostty_point_tag_e tag; + ghostty_point_coord_e coord; + uint32_t x; + uint32_t y; +} ghostty_point_s; + +typedef struct { + ghostty_point_s top_left; + ghostty_point_s bottom_right; + bool rectangle; +} ghostty_selection_s; + +typedef struct { + const char* key; + const char* value; +} ghostty_env_var_s; + +typedef struct { + void* nsview; +} ghostty_platform_macos_s; + +typedef struct { + void* uiview; +} ghostty_platform_ios_s; + +typedef union { + ghostty_platform_macos_s macos; + ghostty_platform_ios_s ios; +} ghostty_platform_u; + +typedef enum { + GHOSTTY_SURFACE_CONTEXT_WINDOW = 0, + GHOSTTY_SURFACE_CONTEXT_TAB = 1, + GHOSTTY_SURFACE_CONTEXT_SPLIT = 2, +} ghostty_surface_context_e; + +typedef struct { + ghostty_platform_e platform_tag; + ghostty_platform_u platform; + void* userdata; + double scale_factor; + float font_size; + const char* working_directory; + const char* command; + ghostty_env_var_s* env_vars; + size_t env_var_count; + const char* initial_input; + bool wait_after_command; + ghostty_surface_context_e context; + bool use_custom_io; +} ghostty_surface_config_s; + +typedef struct { + uint16_t columns; + uint16_t rows; + uint32_t width_px; + uint32_t height_px; + uint32_t cell_width_px; + uint32_t cell_height_px; +} ghostty_surface_size_s; + +// Config types + +// config.Path +typedef struct { + const char* path; + bool optional; +} ghostty_config_path_s; + +// config.Color +typedef struct { + uint8_t r; + uint8_t g; + uint8_t b; +} ghostty_config_color_s; + +// config.ColorList +typedef struct { + const ghostty_config_color_s* colors; + size_t len; +} ghostty_config_color_list_s; + +// config.RepeatableCommand +typedef struct { + const ghostty_command_s* commands; + size_t len; +} ghostty_config_command_list_s; + +// config.Palette +typedef struct { + ghostty_config_color_s colors[256]; +} ghostty_config_palette_s; + +// config.QuickTerminalSize +typedef enum { + GHOSTTY_QUICK_TERMINAL_SIZE_NONE, + GHOSTTY_QUICK_TERMINAL_SIZE_PERCENTAGE, + GHOSTTY_QUICK_TERMINAL_SIZE_PIXELS, +} ghostty_quick_terminal_size_tag_e; + +typedef union { + float percentage; + uint32_t pixels; +} ghostty_quick_terminal_size_value_u; + +typedef struct { + ghostty_quick_terminal_size_tag_e tag; + ghostty_quick_terminal_size_value_u value; +} ghostty_quick_terminal_size_s; + +typedef struct { + ghostty_quick_terminal_size_s primary; + ghostty_quick_terminal_size_s secondary; +} ghostty_config_quick_terminal_size_s; + +// config.Fullscreen +typedef enum { + GHOSTTY_CONFIG_FULLSCREEN_FALSE, + GHOSTTY_CONFIG_FULLSCREEN_TRUE, + GHOSTTY_CONFIG_FULLSCREEN_NON_NATIVE, + GHOSTTY_CONFIG_FULLSCREEN_NON_NATIVE_VISIBLE_MENU, + GHOSTTY_CONFIG_FULLSCREEN_NON_NATIVE_PADDED_NOTCH, +} ghostty_config_fullscreen_e; + +// apprt.Target.Key +typedef enum { + GHOSTTY_TARGET_APP, + GHOSTTY_TARGET_SURFACE, +} ghostty_target_tag_e; + +typedef union { + ghostty_surface_t surface; +} ghostty_target_u; + +typedef struct { + ghostty_target_tag_e tag; + ghostty_target_u target; +} ghostty_target_s; + +// apprt.action.SplitDirection +typedef enum { + GHOSTTY_SPLIT_DIRECTION_RIGHT, + GHOSTTY_SPLIT_DIRECTION_DOWN, + GHOSTTY_SPLIT_DIRECTION_LEFT, + GHOSTTY_SPLIT_DIRECTION_UP, +} ghostty_action_split_direction_e; + +// apprt.action.GotoSplit +typedef enum { + GHOSTTY_GOTO_SPLIT_PREVIOUS, + GHOSTTY_GOTO_SPLIT_NEXT, + GHOSTTY_GOTO_SPLIT_UP, + GHOSTTY_GOTO_SPLIT_LEFT, + GHOSTTY_GOTO_SPLIT_DOWN, + GHOSTTY_GOTO_SPLIT_RIGHT, +} ghostty_action_goto_split_e; + +// apprt.action.GotoWindow +typedef enum { + GHOSTTY_GOTO_WINDOW_PREVIOUS, + GHOSTTY_GOTO_WINDOW_NEXT, +} ghostty_action_goto_window_e; + +// apprt.action.ResizeSplit.Direction +typedef enum { + GHOSTTY_RESIZE_SPLIT_UP, + GHOSTTY_RESIZE_SPLIT_DOWN, + GHOSTTY_RESIZE_SPLIT_LEFT, + GHOSTTY_RESIZE_SPLIT_RIGHT, +} ghostty_action_resize_split_direction_e; + +// apprt.action.ResizeSplit +typedef struct { + uint16_t amount; + ghostty_action_resize_split_direction_e direction; +} ghostty_action_resize_split_s; + +// apprt.action.MoveTab +typedef struct { + ssize_t amount; +} ghostty_action_move_tab_s; + +// apprt.action.GotoTab +typedef enum { + GHOSTTY_GOTO_TAB_PREVIOUS = -1, + GHOSTTY_GOTO_TAB_NEXT = -2, + GHOSTTY_GOTO_TAB_LAST = -3, +} ghostty_action_goto_tab_e; + +// apprt.action.Fullscreen +typedef enum { + GHOSTTY_FULLSCREEN_NATIVE, + GHOSTTY_FULLSCREEN_MACOS_NON_NATIVE, + GHOSTTY_FULLSCREEN_MACOS_NON_NATIVE_VISIBLE_MENU, + GHOSTTY_FULLSCREEN_MACOS_NON_NATIVE_PADDED_NOTCH, +} ghostty_action_fullscreen_e; + +// apprt.action.FloatWindow +typedef enum { + GHOSTTY_FLOAT_WINDOW_ON, + GHOSTTY_FLOAT_WINDOW_OFF, + GHOSTTY_FLOAT_WINDOW_TOGGLE, +} ghostty_action_float_window_e; + +// apprt.action.SecureInput +typedef enum { + GHOSTTY_SECURE_INPUT_ON, + GHOSTTY_SECURE_INPUT_OFF, + GHOSTTY_SECURE_INPUT_TOGGLE, +} ghostty_action_secure_input_e; + +// apprt.action.Inspector +typedef enum { + GHOSTTY_INSPECTOR_TOGGLE, + GHOSTTY_INSPECTOR_SHOW, + GHOSTTY_INSPECTOR_HIDE, +} ghostty_action_inspector_e; + +// apprt.action.QuitTimer +typedef enum { + GHOSTTY_QUIT_TIMER_START, + GHOSTTY_QUIT_TIMER_STOP, +} ghostty_action_quit_timer_e; + +// apprt.action.Readonly +typedef enum { + GHOSTTY_READONLY_OFF, + GHOSTTY_READONLY_ON, +} ghostty_action_readonly_e; + +// apprt.action.DesktopNotification.C +typedef struct { + const char* title; + const char* body; +} ghostty_action_desktop_notification_s; + +// apprt.action.SetTitle.C +typedef struct { + const char* title; +} ghostty_action_set_title_s; + +// apprt.action.PromptTitle +typedef enum { + GHOSTTY_PROMPT_TITLE_SURFACE, + GHOSTTY_PROMPT_TITLE_TAB, +} ghostty_action_prompt_title_e; + +// apprt.action.Pwd.C +typedef struct { + const char* pwd; +} ghostty_action_pwd_s; + +// terminal.MouseShape +typedef enum { + GHOSTTY_MOUSE_SHAPE_DEFAULT, + GHOSTTY_MOUSE_SHAPE_CONTEXT_MENU, + GHOSTTY_MOUSE_SHAPE_HELP, + GHOSTTY_MOUSE_SHAPE_POINTER, + GHOSTTY_MOUSE_SHAPE_PROGRESS, + GHOSTTY_MOUSE_SHAPE_WAIT, + GHOSTTY_MOUSE_SHAPE_CELL, + GHOSTTY_MOUSE_SHAPE_CROSSHAIR, + GHOSTTY_MOUSE_SHAPE_TEXT, + GHOSTTY_MOUSE_SHAPE_VERTICAL_TEXT, + GHOSTTY_MOUSE_SHAPE_ALIAS, + GHOSTTY_MOUSE_SHAPE_COPY, + GHOSTTY_MOUSE_SHAPE_MOVE, + GHOSTTY_MOUSE_SHAPE_NO_DROP, + GHOSTTY_MOUSE_SHAPE_NOT_ALLOWED, + GHOSTTY_MOUSE_SHAPE_GRAB, + GHOSTTY_MOUSE_SHAPE_GRABBING, + GHOSTTY_MOUSE_SHAPE_ALL_SCROLL, + GHOSTTY_MOUSE_SHAPE_COL_RESIZE, + GHOSTTY_MOUSE_SHAPE_ROW_RESIZE, + GHOSTTY_MOUSE_SHAPE_N_RESIZE, + GHOSTTY_MOUSE_SHAPE_E_RESIZE, + GHOSTTY_MOUSE_SHAPE_S_RESIZE, + GHOSTTY_MOUSE_SHAPE_W_RESIZE, + GHOSTTY_MOUSE_SHAPE_NE_RESIZE, + GHOSTTY_MOUSE_SHAPE_NW_RESIZE, + GHOSTTY_MOUSE_SHAPE_SE_RESIZE, + GHOSTTY_MOUSE_SHAPE_SW_RESIZE, + GHOSTTY_MOUSE_SHAPE_EW_RESIZE, + GHOSTTY_MOUSE_SHAPE_NS_RESIZE, + GHOSTTY_MOUSE_SHAPE_NESW_RESIZE, + GHOSTTY_MOUSE_SHAPE_NWSE_RESIZE, + GHOSTTY_MOUSE_SHAPE_ZOOM_IN, + GHOSTTY_MOUSE_SHAPE_ZOOM_OUT, +} ghostty_action_mouse_shape_e; + +// apprt.action.MouseVisibility +typedef enum { + GHOSTTY_MOUSE_VISIBLE, + GHOSTTY_MOUSE_HIDDEN, +} ghostty_action_mouse_visibility_e; + +// apprt.action.MouseOverLink +typedef struct { + const char* url; + size_t len; +} ghostty_action_mouse_over_link_s; + +// apprt.action.SizeLimit +typedef struct { + uint32_t min_width; + uint32_t min_height; + uint32_t max_width; + uint32_t max_height; +} ghostty_action_size_limit_s; + +// apprt.action.InitialSize +typedef struct { + uint32_t width; + uint32_t height; +} ghostty_action_initial_size_s; + +// apprt.action.CellSize +typedef struct { + uint32_t width; + uint32_t height; +} ghostty_action_cell_size_s; + +// renderer.Health +typedef enum { + GHOSTTY_RENDERER_HEALTH_HEALTHY, + GHOSTTY_RENDERER_HEALTH_UNHEALTHY, +} ghostty_action_renderer_health_e; + +// apprt.action.KeySequence +typedef struct { + bool active; + ghostty_input_trigger_s trigger; +} ghostty_action_key_sequence_s; + +// apprt.action.KeyTable.Tag +typedef enum { + GHOSTTY_KEY_TABLE_ACTIVATE, + GHOSTTY_KEY_TABLE_DEACTIVATE, + GHOSTTY_KEY_TABLE_DEACTIVATE_ALL, +} ghostty_action_key_table_tag_e; + +// apprt.action.KeyTable.CValue +typedef union { + struct { + const char *name; + size_t len; + } activate; +} ghostty_action_key_table_u; + +// apprt.action.KeyTable.C +typedef struct { + ghostty_action_key_table_tag_e tag; + ghostty_action_key_table_u value; +} ghostty_action_key_table_s; + +// apprt.action.ColorKind +typedef enum { + GHOSTTY_ACTION_COLOR_KIND_FOREGROUND = -1, + GHOSTTY_ACTION_COLOR_KIND_BACKGROUND = -2, + GHOSTTY_ACTION_COLOR_KIND_CURSOR = -3, +} ghostty_action_color_kind_e; + +// apprt.action.ColorChange +typedef struct { + ghostty_action_color_kind_e kind; + uint8_t r; + uint8_t g; + uint8_t b; +} ghostty_action_color_change_s; + +// apprt.action.ConfigChange +typedef struct { + ghostty_config_t config; +} ghostty_action_config_change_s; + +// apprt.action.ReloadConfig +typedef struct { + bool soft; +} ghostty_action_reload_config_s; + +// apprt.action.OpenUrlKind +typedef enum { + GHOSTTY_ACTION_OPEN_URL_KIND_UNKNOWN, + GHOSTTY_ACTION_OPEN_URL_KIND_TEXT, + GHOSTTY_ACTION_OPEN_URL_KIND_HTML, +} ghostty_action_open_url_kind_e; + +// apprt.action.OpenUrl.C +typedef struct { + ghostty_action_open_url_kind_e kind; + const char* url; + uintptr_t len; +} ghostty_action_open_url_s; + +// apprt.action.CloseTabMode +typedef enum { + GHOSTTY_ACTION_CLOSE_TAB_MODE_THIS, + GHOSTTY_ACTION_CLOSE_TAB_MODE_OTHER, + GHOSTTY_ACTION_CLOSE_TAB_MODE_RIGHT, +} ghostty_action_close_tab_mode_e; + +// apprt.surface.Message.ChildExited +typedef struct { + uint32_t exit_code; + uint64_t timetime_ms; +} ghostty_surface_message_childexited_s; + +// terminal.osc.Command.ProgressReport.State +typedef enum { + GHOSTTY_PROGRESS_STATE_REMOVE, + GHOSTTY_PROGRESS_STATE_SET, + GHOSTTY_PROGRESS_STATE_ERROR, + GHOSTTY_PROGRESS_STATE_INDETERMINATE, + GHOSTTY_PROGRESS_STATE_PAUSE, +} ghostty_action_progress_report_state_e; + +// terminal.osc.Command.ProgressReport.C +typedef struct { + ghostty_action_progress_report_state_e state; + // -1 if no progress was reported, otherwise 0-100 indicating percent + // completeness. + int8_t progress; +} ghostty_action_progress_report_s; + +// apprt.action.CommandFinished.C +typedef struct { + // -1 if no exit code was reported, otherwise 0-255 + int16_t exit_code; + // number of nanoseconds that command was running for + uint64_t duration; +} ghostty_action_command_finished_s; + +// apprt.action.StartSearch.C +typedef struct { + const char* needle; +} ghostty_action_start_search_s; + +// apprt.action.SearchTotal +typedef struct { + ssize_t total; +} ghostty_action_search_total_s; + +// apprt.action.SearchSelected +typedef struct { + ssize_t selected; +} ghostty_action_search_selected_s; + +// terminal.Scrollbar +typedef struct { + uint64_t total; + uint64_t offset; + uint64_t len; +} ghostty_action_scrollbar_s; + +// apprt.Action.Key +typedef enum { + GHOSTTY_ACTION_QUIT, + GHOSTTY_ACTION_NEW_WINDOW, + GHOSTTY_ACTION_NEW_TAB, + GHOSTTY_ACTION_CLOSE_TAB, + GHOSTTY_ACTION_NEW_SPLIT, + GHOSTTY_ACTION_CLOSE_ALL_WINDOWS, + GHOSTTY_ACTION_TOGGLE_MAXIMIZE, + GHOSTTY_ACTION_TOGGLE_FULLSCREEN, + GHOSTTY_ACTION_TOGGLE_TAB_OVERVIEW, + GHOSTTY_ACTION_TOGGLE_WINDOW_DECORATIONS, + GHOSTTY_ACTION_TOGGLE_QUICK_TERMINAL, + GHOSTTY_ACTION_TOGGLE_COMMAND_PALETTE, + GHOSTTY_ACTION_TOGGLE_VISIBILITY, + GHOSTTY_ACTION_TOGGLE_BACKGROUND_OPACITY, + GHOSTTY_ACTION_MOVE_TAB, + GHOSTTY_ACTION_GOTO_TAB, + GHOSTTY_ACTION_GOTO_SPLIT, + GHOSTTY_ACTION_GOTO_WINDOW, + GHOSTTY_ACTION_RESIZE_SPLIT, + GHOSTTY_ACTION_EQUALIZE_SPLITS, + GHOSTTY_ACTION_TOGGLE_SPLIT_ZOOM, + GHOSTTY_ACTION_PRESENT_TERMINAL, + GHOSTTY_ACTION_SIZE_LIMIT, + GHOSTTY_ACTION_RESET_WINDOW_SIZE, + GHOSTTY_ACTION_INITIAL_SIZE, + GHOSTTY_ACTION_CELL_SIZE, + GHOSTTY_ACTION_SCROLLBAR, + GHOSTTY_ACTION_RENDER, + GHOSTTY_ACTION_INSPECTOR, + GHOSTTY_ACTION_SHOW_GTK_INSPECTOR, + GHOSTTY_ACTION_RENDER_INSPECTOR, + GHOSTTY_ACTION_DESKTOP_NOTIFICATION, + GHOSTTY_ACTION_SET_TITLE, + GHOSTTY_ACTION_PROMPT_TITLE, + GHOSTTY_ACTION_PWD, + GHOSTTY_ACTION_MOUSE_SHAPE, + GHOSTTY_ACTION_MOUSE_VISIBILITY, + GHOSTTY_ACTION_MOUSE_OVER_LINK, + GHOSTTY_ACTION_RENDERER_HEALTH, + GHOSTTY_ACTION_OPEN_CONFIG, + GHOSTTY_ACTION_QUIT_TIMER, + GHOSTTY_ACTION_FLOAT_WINDOW, + GHOSTTY_ACTION_SECURE_INPUT, + GHOSTTY_ACTION_KEY_SEQUENCE, + GHOSTTY_ACTION_KEY_TABLE, + GHOSTTY_ACTION_COLOR_CHANGE, + GHOSTTY_ACTION_RELOAD_CONFIG, + GHOSTTY_ACTION_CONFIG_CHANGE, + GHOSTTY_ACTION_CLOSE_WINDOW, + GHOSTTY_ACTION_RING_BELL, + GHOSTTY_ACTION_UNDO, + GHOSTTY_ACTION_REDO, + GHOSTTY_ACTION_CHECK_FOR_UPDATES, + GHOSTTY_ACTION_OPEN_URL, + GHOSTTY_ACTION_SHOW_CHILD_EXITED, + GHOSTTY_ACTION_PROGRESS_REPORT, + GHOSTTY_ACTION_SHOW_ON_SCREEN_KEYBOARD, + GHOSTTY_ACTION_COMMAND_FINISHED, + GHOSTTY_ACTION_START_SEARCH, + GHOSTTY_ACTION_END_SEARCH, + GHOSTTY_ACTION_SEARCH_TOTAL, + GHOSTTY_ACTION_SEARCH_SELECTED, + GHOSTTY_ACTION_READONLY, + GHOSTTY_ACTION_COPY_TITLE_TO_CLIPBOARD, +} ghostty_action_tag_e; + +typedef union { + ghostty_action_split_direction_e new_split; + ghostty_action_fullscreen_e toggle_fullscreen; + ghostty_action_move_tab_s move_tab; + ghostty_action_goto_tab_e goto_tab; + ghostty_action_goto_split_e goto_split; + ghostty_action_goto_window_e goto_window; + ghostty_action_resize_split_s resize_split; + ghostty_action_size_limit_s size_limit; + ghostty_action_initial_size_s initial_size; + ghostty_action_cell_size_s cell_size; + ghostty_action_scrollbar_s scrollbar; + ghostty_action_inspector_e inspector; + ghostty_action_desktop_notification_s desktop_notification; + ghostty_action_set_title_s set_title; + ghostty_action_prompt_title_e prompt_title; + ghostty_action_pwd_s pwd; + ghostty_action_mouse_shape_e mouse_shape; + ghostty_action_mouse_visibility_e mouse_visibility; + ghostty_action_mouse_over_link_s mouse_over_link; + ghostty_action_renderer_health_e renderer_health; + ghostty_action_quit_timer_e quit_timer; + ghostty_action_float_window_e float_window; + ghostty_action_secure_input_e secure_input; + ghostty_action_key_sequence_s key_sequence; + ghostty_action_key_table_s key_table; + ghostty_action_color_change_s color_change; + ghostty_action_reload_config_s reload_config; + ghostty_action_config_change_s config_change; + ghostty_action_open_url_s open_url; + ghostty_action_close_tab_mode_e close_tab_mode; + ghostty_surface_message_childexited_s child_exited; + ghostty_action_progress_report_s progress_report; + ghostty_action_command_finished_s command_finished; + ghostty_action_start_search_s start_search; + ghostty_action_search_total_s search_total; + ghostty_action_search_selected_s search_selected; + ghostty_action_readonly_e readonly; +} ghostty_action_u; + +typedef struct { + ghostty_action_tag_e tag; + ghostty_action_u action; +} ghostty_action_s; + +typedef void (*ghostty_runtime_wakeup_cb)(void*); +typedef void (*ghostty_runtime_read_clipboard_cb)(void*, + ghostty_clipboard_e, + void*); +typedef void (*ghostty_runtime_confirm_read_clipboard_cb)( + void*, + const char*, + void*, + ghostty_clipboard_request_e); +typedef void (*ghostty_runtime_write_clipboard_cb)(void*, + ghostty_clipboard_e, + const ghostty_clipboard_content_s*, + size_t, + bool); +typedef void (*ghostty_runtime_close_surface_cb)(void*, bool); +typedef bool (*ghostty_runtime_action_cb)(ghostty_app_t, + ghostty_target_s, + ghostty_action_s); + +typedef struct { + void* userdata; + bool supports_selection_clipboard; + ghostty_runtime_wakeup_cb wakeup_cb; + ghostty_runtime_action_cb action_cb; + ghostty_runtime_read_clipboard_cb read_clipboard_cb; + ghostty_runtime_confirm_read_clipboard_cb confirm_read_clipboard_cb; + ghostty_runtime_write_clipboard_cb write_clipboard_cb; + ghostty_runtime_close_surface_cb close_surface_cb; +} ghostty_runtime_config_s; + +// apprt.ipc.Target.Key +typedef enum { + GHOSTTY_IPC_TARGET_CLASS, + GHOSTTY_IPC_TARGET_DETECT, +} ghostty_ipc_target_tag_e; + +typedef union { + char *klass; +} ghostty_ipc_target_u; + +typedef struct { + ghostty_ipc_target_tag_e tag; + ghostty_ipc_target_u target; +} chostty_ipc_target_s; + +// apprt.ipc.Action.NewWindow +typedef struct { + // This should be a null terminated list of strings. + const char **arguments; +} ghostty_ipc_action_new_window_s; + +typedef union { + ghostty_ipc_action_new_window_s new_window; +} ghostty_ipc_action_u; + +// apprt.ipc.Action.Key +typedef enum { + GHOSTTY_IPC_ACTION_NEW_WINDOW, +} ghostty_ipc_action_tag_e; + +//------------------------------------------------------------------- +// Published API + +int ghostty_init(uintptr_t, char**); +void ghostty_cli_try_action(void); +ghostty_info_s ghostty_info(void); +const char* ghostty_translate(const char*); +void ghostty_string_free(ghostty_string_s); + +ghostty_config_t ghostty_config_new(); +void ghostty_config_free(ghostty_config_t); +ghostty_config_t ghostty_config_clone(ghostty_config_t); +void ghostty_config_load_cli_args(ghostty_config_t); +void ghostty_config_load_file(ghostty_config_t, const char*); +void ghostty_config_load_default_files(ghostty_config_t); +void ghostty_config_load_recursive_files(ghostty_config_t); +void ghostty_config_finalize(ghostty_config_t); +bool ghostty_config_get(ghostty_config_t, void*, const char*, uintptr_t); +ghostty_input_trigger_s ghostty_config_trigger(ghostty_config_t, + const char*, + uintptr_t); +uint32_t ghostty_config_diagnostics_count(ghostty_config_t); +ghostty_diagnostic_s ghostty_config_get_diagnostic(ghostty_config_t, uint32_t); +ghostty_string_s ghostty_config_open_path(void); + +ghostty_app_t ghostty_app_new(const ghostty_runtime_config_s*, + ghostty_config_t); +void ghostty_app_free(ghostty_app_t); +void ghostty_app_tick(ghostty_app_t); +void* ghostty_app_userdata(ghostty_app_t); +void ghostty_app_set_focus(ghostty_app_t, bool); +bool ghostty_app_key(ghostty_app_t, ghostty_input_key_s); +bool ghostty_app_key_is_binding(ghostty_app_t, ghostty_input_key_s); +void ghostty_app_keyboard_changed(ghostty_app_t); +void ghostty_app_open_config(ghostty_app_t); +void ghostty_app_update_config(ghostty_app_t, ghostty_config_t); +bool ghostty_app_needs_confirm_quit(ghostty_app_t); +bool ghostty_app_has_global_keybinds(ghostty_app_t); +void ghostty_app_set_color_scheme(ghostty_app_t, ghostty_color_scheme_e); + +ghostty_surface_config_s ghostty_surface_config_new(); + +ghostty_surface_t ghostty_surface_new(ghostty_app_t, + const ghostty_surface_config_s*); +void ghostty_surface_free(ghostty_surface_t); +void* ghostty_surface_userdata(ghostty_surface_t); +ghostty_app_t ghostty_surface_app(ghostty_surface_t); +ghostty_surface_config_s ghostty_surface_inherited_config(ghostty_surface_t, ghostty_surface_context_e); +void ghostty_surface_update_config(ghostty_surface_t, ghostty_config_t); +bool ghostty_surface_needs_confirm_quit(ghostty_surface_t); +bool ghostty_surface_process_exited(ghostty_surface_t); +void ghostty_surface_refresh(ghostty_surface_t); +void ghostty_surface_draw(ghostty_surface_t); +// Custom I/O API - feed output into the terminal and receive writes. +void ghostty_surface_feed_data(ghostty_surface_t, const uint8_t*, size_t); +void ghostty_surface_set_write_callback(ghostty_surface_t, + ghostty_surface_write_fn, + void*); +void ghostty_surface_set_content_scale(ghostty_surface_t, double, double); +void ghostty_surface_set_focus(ghostty_surface_t, bool); +void ghostty_surface_set_occlusion(ghostty_surface_t, bool); +void ghostty_surface_set_size(ghostty_surface_t, uint32_t, uint32_t); +ghostty_surface_size_s ghostty_surface_size(ghostty_surface_t); +void ghostty_surface_set_color_scheme(ghostty_surface_t, + ghostty_color_scheme_e); +ghostty_input_mods_e ghostty_surface_key_translation_mods(ghostty_surface_t, + ghostty_input_mods_e); +bool ghostty_surface_key(ghostty_surface_t, ghostty_input_key_s); +bool ghostty_surface_key_is_binding(ghostty_surface_t, + ghostty_input_key_s, + ghostty_binding_flags_e*); +void ghostty_surface_text(ghostty_surface_t, const char*, uintptr_t); +void ghostty_surface_preedit(ghostty_surface_t, const char*, uintptr_t); +bool ghostty_surface_mouse_captured(ghostty_surface_t); +bool ghostty_surface_mouse_button(ghostty_surface_t, + ghostty_input_mouse_state_e, + ghostty_input_mouse_button_e, + ghostty_input_mods_e); +void ghostty_surface_mouse_pos(ghostty_surface_t, + double, + double, + ghostty_input_mods_e); +void ghostty_surface_mouse_scroll(ghostty_surface_t, + double, + double, + ghostty_input_scroll_mods_t); +void ghostty_surface_mouse_pressure(ghostty_surface_t, uint32_t, double); +void ghostty_surface_ime_point(ghostty_surface_t, double*, double*, double*, double*); +void ghostty_surface_request_close(ghostty_surface_t); +void ghostty_surface_split(ghostty_surface_t, ghostty_action_split_direction_e); +void ghostty_surface_split_focus(ghostty_surface_t, + ghostty_action_goto_split_e); +void ghostty_surface_split_resize(ghostty_surface_t, + ghostty_action_resize_split_direction_e, + uint16_t); +void ghostty_surface_split_equalize(ghostty_surface_t); +bool ghostty_surface_binding_action(ghostty_surface_t, const char*, uintptr_t); +void ghostty_surface_complete_clipboard_request(ghostty_surface_t, + const char*, + void*, + bool); +bool ghostty_surface_has_selection(ghostty_surface_t); +bool ghostty_surface_read_selection(ghostty_surface_t, ghostty_text_s*); +bool ghostty_surface_read_text(ghostty_surface_t, + ghostty_selection_s, + ghostty_text_s*); +void ghostty_surface_free_text(ghostty_surface_t, ghostty_text_s*); + +#ifdef __APPLE__ +void ghostty_surface_set_display_id(ghostty_surface_t, uint32_t); +void* ghostty_surface_quicklook_font(ghostty_surface_t); +bool ghostty_surface_quicklook_word(ghostty_surface_t, ghostty_text_s*); +#endif + +ghostty_inspector_t ghostty_surface_inspector(ghostty_surface_t); +void ghostty_inspector_free(ghostty_surface_t); +void ghostty_inspector_set_focus(ghostty_inspector_t, bool); +void ghostty_inspector_set_content_scale(ghostty_inspector_t, double, double); +void ghostty_inspector_set_size(ghostty_inspector_t, uint32_t, uint32_t); +void ghostty_inspector_mouse_button(ghostty_inspector_t, + ghostty_input_mouse_state_e, + ghostty_input_mouse_button_e, + ghostty_input_mods_e); +void ghostty_inspector_mouse_pos(ghostty_inspector_t, double, double); +void ghostty_inspector_mouse_scroll(ghostty_inspector_t, + double, + double, + ghostty_input_scroll_mods_t); +void ghostty_inspector_key(ghostty_inspector_t, + ghostty_input_action_e, + ghostty_input_key_e, + ghostty_input_mods_e); +void ghostty_inspector_text(ghostty_inspector_t, const char*); + +#ifdef __APPLE__ +bool ghostty_inspector_metal_init(ghostty_inspector_t, void*); +void ghostty_inspector_metal_render(ghostty_inspector_t, void*, void*); +bool ghostty_inspector_metal_shutdown(ghostty_inspector_t); +#endif + +// APIs I'd like to get rid of eventually but are still needed for now. +// Don't use these unless you know what you're doing. +void ghostty_set_window_background_blur(ghostty_app_t, void*); + +// Benchmark API, if available. +bool ghostty_benchmark_cli(const char*, const char*); + +#ifdef __cplusplus +} +#endif + +#endif /* GHOSTTY_H */ diff --git a/apps/mobile/modules/t3-terminal/Vendor/libghostty/GhosttyKit.xcframework/ios-arm64-simulator/Headers/ghostty/vt.h b/apps/mobile/modules/t3-terminal/Vendor/libghostty/GhosttyKit.xcframework/ios-arm64-simulator/Headers/ghostty/vt.h new file mode 100644 index 0000000000..4f8fef88ec --- /dev/null +++ b/apps/mobile/modules/t3-terminal/Vendor/libghostty/GhosttyKit.xcframework/ios-arm64-simulator/Headers/ghostty/vt.h @@ -0,0 +1,87 @@ +/** + * @file vt.h + * + * libghostty-vt - Virtual terminal emulator library + * + * This library provides functionality for parsing and handling terminal + * escape sequences as well as maintaining terminal state such as styles, + * cursor position, screen, scrollback, and more. + * + * WARNING: This is an incomplete, work-in-progress API. It is not yet + * stable and is definitely going to change. + */ + +/** + * @mainpage libghostty-vt - Virtual Terminal Emulator Library + * + * libghostty-vt is a C library which implements a modern terminal emulator, + * extracted from the [Ghostty](https://ghostty.org) terminal emulator. + * + * libghostty-vt contains the logic for handling the core parts of a terminal + * emulator: parsing terminal escape sequences, maintaining terminal state, + * encoding input events, etc. It can handle scrollback, line wrapping, + * reflow on resize, and more. + * + * @warning This library is currently in development and the API is not yet stable. + * Breaking changes are expected in future versions. Use with caution in production code. + * + * @section groups_sec API Reference + * + * The API is organized into the following groups: + * - @ref key "Key Encoding" - Encode key events into terminal sequences + * - @ref osc "OSC Parser" - Parse OSC (Operating System Command) sequences + * - @ref sgr "SGR Parser" - Parse SGR (Select Graphic Rendition) sequences + * - @ref paste "Paste Utilities" - Validate paste data safety + * - @ref allocator "Memory Management" - Memory management and custom allocators + * - @ref wasm "WebAssembly Utilities" - WebAssembly convenience functions + * + * @section examples_sec Examples + * + * Complete working examples: + * - @ref c-vt/src/main.c - OSC parser example + * - @ref c-vt-key-encode/src/main.c - Key encoding example + * - @ref c-vt-paste/src/main.c - Paste safety check example + * - @ref c-vt-sgr/src/main.c - SGR parser example + * + */ + +/** @example c-vt/src/main.c + * This example demonstrates how to use the OSC parser to parse an OSC sequence, + * extract command information, and retrieve command-specific data like window titles. + */ + +/** @example c-vt-key-encode/src/main.c + * This example demonstrates how to use the key encoder to convert key events + * into terminal escape sequences using the Kitty keyboard protocol. + */ + +/** @example c-vt-paste/src/main.c + * This example demonstrates how to use the paste utilities to check if + * paste data is safe before sending it to the terminal. + */ + +/** @example c-vt-sgr/src/main.c + * This example demonstrates how to use the SGR parser to parse terminal + * styling sequences and extract text attributes like colors and underline styles. + */ + +#ifndef GHOSTTY_VT_H +#define GHOSTTY_VT_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include +#include +#include +#include +#include +#include + +#ifdef __cplusplus +} +#endif + +#endif /* GHOSTTY_VT_H */ diff --git a/apps/mobile/modules/t3-terminal/Vendor/libghostty/GhosttyKit.xcframework/ios-arm64-simulator/Headers/ghostty/vt/allocator.h b/apps/mobile/modules/t3-terminal/Vendor/libghostty/GhosttyKit.xcframework/ios-arm64-simulator/Headers/ghostty/vt/allocator.h new file mode 100644 index 0000000000..4cebe91bb1 --- /dev/null +++ b/apps/mobile/modules/t3-terminal/Vendor/libghostty/GhosttyKit.xcframework/ios-arm64-simulator/Headers/ghostty/vt/allocator.h @@ -0,0 +1,196 @@ +/** + * @file allocator.h + * + * Memory management interface for libghostty-vt. + */ + +#ifndef GHOSTTY_VT_ALLOCATOR_H +#define GHOSTTY_VT_ALLOCATOR_H + +#include +#include +#include + +/** @defgroup allocator Memory Management + * + * libghostty-vt does require memory allocation for various operations, + * but is resilient to allocation failures and will gracefully handle + * out-of-memory situations by returning error codes. + * + * The exact memory management semantics are documented in the relevant + * functions and data structures. + * + * libghostty-vt uses explicit memory allocation via an allocator + * interface provided by GhosttyAllocator. The interface is based on the + * [Zig](https://ziglang.org) allocator interface, since this has been + * shown to be a flexible and powerful interface in practice and enables + * a wide variety of allocation strategies. + * + * **For the common case, you can pass NULL as the allocator for any + * function that accepts one,** and libghostty will use a default allocator. + * The default allocator will be libc malloc/free if libc is linked. + * Otherwise, a custom allocator is used (currently Zig's SMP allocator) + * that doesn't require any external dependencies. + * + * ## Basic Usage + * + * For simple use cases, you can ignore this interface entirely by passing NULL + * as the allocator parameter to functions that accept one. This will use the + * default allocator (typically libc malloc/free, if libc is linked, but + * we provide our own default allocator if libc isn't linked). + * + * To use a custom allocator: + * 1. Implement the GhosttyAllocatorVtable function pointers + * 2. Create a GhosttyAllocator struct with your vtable and context + * 3. Pass the allocator to functions that accept one + * + * @{ + */ + +/** + * Function table for custom memory allocator operations. + * + * This vtable defines the interface for a custom memory allocator. All + * function pointers must be valid and non-NULL. + * + * @ingroup allocator + * + * If you're not going to use a custom allocator, you can ignore all of + * this. All functions that take an allocator pointer allow NULL to use a + * default allocator. + * + * The interface is based on the Zig allocator interface. I'll say up front + * that it is easy to look at this interface and think "wow, this is really + * overcomplicated". The reason for this complexity is well thought out by + * the Zig folks, and it enables a diverse set of allocation strategies + * as shown by the Zig ecosystem. As a consolation, please note that many + * of the arguments are only needed for advanced use cases and can be + * safely ignored in simple implementations. For example, if you look at + * the Zig implementation of the libc allocator in `lib/std/heap.zig` + * (search for CAllocator), you'll see it is very simple. + * + * We chose to align with the Zig allocator interface because: + * + * 1. It is a proven interface that serves a wide variety of use cases + * in the real world via the Zig ecosystem. It's shown to work. + * + * 2. Our core implementation itself is Zig, and this lets us very + * cheaply and easily convert between C and Zig allocators. + * + * NOTE(mitchellh): In the future, we can have default implementations of + * resize/remap and allow those to be null. + */ +typedef struct { + /** + * Return a pointer to `len` bytes with specified `alignment`, or return + * `NULL` indicating the allocation failed. + * + * @param ctx The allocator context + * @param len Number of bytes to allocate + * @param alignment Required alignment for the allocation. Guaranteed to + * be a power of two between 1 and 16 inclusive. + * @param ret_addr First return address of the allocation call stack (0 if not provided) + * @return Pointer to allocated memory, or NULL if allocation failed + */ + void* (*alloc)(void *ctx, size_t len, uint8_t alignment, uintptr_t ret_addr); + + /** + * Attempt to expand or shrink memory in place. + * + * `memory_len` must equal the length requested from the most recent + * successful call to `alloc`, `resize`, or `remap`. `alignment` must + * equal the same value that was passed as the `alignment` parameter to + * the original `alloc` call. + * + * `new_len` must be greater than zero. + * + * @param ctx The allocator context + * @param memory Pointer to the memory block to resize + * @param memory_len Current size of the memory block + * @param alignment Alignment (must match original allocation) + * @param new_len New requested size + * @param ret_addr First return address of the allocation call stack (0 if not provided) + * @return true if resize was successful in-place, false if relocation would be required + */ + bool (*resize)(void *ctx, void *memory, size_t memory_len, uint8_t alignment, size_t new_len, uintptr_t ret_addr); + + /** + * Attempt to expand or shrink memory, allowing relocation. + * + * `memory_len` must equal the length requested from the most recent + * successful call to `alloc`, `resize`, or `remap`. `alignment` must + * equal the same value that was passed as the `alignment` parameter to + * the original `alloc` call. + * + * A non-`NULL` return value indicates the resize was successful. The + * allocation may have same address, or may have been relocated. In either + * case, the allocation now has size of `new_len`. A `NULL` return value + * indicates that the resize would be equivalent to allocating new memory, + * copying the bytes from the old memory, and then freeing the old memory. + * In such case, it is more efficient for the caller to perform the copy. + * + * `new_len` must be greater than zero. + * + * @param ctx The allocator context + * @param memory Pointer to the memory block to remap + * @param memory_len Current size of the memory block + * @param alignment Alignment (must match original allocation) + * @param new_len New requested size + * @param ret_addr First return address of the allocation call stack (0 if not provided) + * @return Pointer to resized memory (may be relocated), or NULL if manual copy is needed + */ + void* (*remap)(void *ctx, void *memory, size_t memory_len, uint8_t alignment, size_t new_len, uintptr_t ret_addr); + + /** + * Free and invalidate a region of memory. + * + * `memory_len` must equal the length requested from the most recent + * successful call to `alloc`, `resize`, or `remap`. `alignment` must + * equal the same value that was passed as the `alignment` parameter to + * the original `alloc` call. + * + * @param ctx The allocator context + * @param memory Pointer to the memory block to free + * @param memory_len Size of the memory block + * @param alignment Alignment (must match original allocation) + * @param ret_addr First return address of the allocation call stack (0 if not provided) + */ + void (*free)(void *ctx, void *memory, size_t memory_len, uint8_t alignment, uintptr_t ret_addr); +} GhosttyAllocatorVtable; + +/** + * Custom memory allocator. + * + * For functions that take an allocator pointer, a NULL pointer indicates + * that the default allocator should be used. The default allocator will + * be libc malloc/free if we're linking to libc. If libc isn't linked, + * a custom allocator is used (currently Zig's SMP allocator). + * + * @ingroup allocator + * + * Usage example: + * @code + * GhosttyAllocator allocator = { + * .vtable = &my_allocator_vtable, + * .ctx = my_allocator_state + * }; + * @endcode + */ +typedef struct GhosttyAllocator { + /** + * Opaque context pointer passed to all vtable functions. + * This allows the allocator implementation to maintain state + * or reference external resources needed for memory management. + */ + void *ctx; + + /** + * Pointer to the allocator's vtable containing function pointers + * for memory operations (alloc, resize, remap, free). + */ + const GhosttyAllocatorVtable *vtable; +} GhosttyAllocator; + +/** @} */ + +#endif /* GHOSTTY_VT_ALLOCATOR_H */ diff --git a/apps/mobile/modules/t3-terminal/Vendor/libghostty/GhosttyKit.xcframework/ios-arm64-simulator/Headers/ghostty/vt/color.h b/apps/mobile/modules/t3-terminal/Vendor/libghostty/GhosttyKit.xcframework/ios-arm64-simulator/Headers/ghostty/vt/color.h new file mode 100644 index 0000000000..0d57b8db4a --- /dev/null +++ b/apps/mobile/modules/t3-terminal/Vendor/libghostty/GhosttyKit.xcframework/ios-arm64-simulator/Headers/ghostty/vt/color.h @@ -0,0 +1,96 @@ +/** + * @file color.h + * + * Color types and utilities. + */ + +#ifndef GHOSTTY_VT_COLOR_H +#define GHOSTTY_VT_COLOR_H + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * RGB color value. + * + * @ingroup sgr + */ +typedef struct { + uint8_t r; /**< Red component (0-255) */ + uint8_t g; /**< Green component (0-255) */ + uint8_t b; /**< Blue component (0-255) */ +} GhosttyColorRgb; + +/** + * Palette color index (0-255). + * + * @ingroup sgr + */ +typedef uint8_t GhosttyColorPaletteIndex; + +/** @addtogroup sgr + * @{ + */ + +/** Black color (0) @ingroup sgr */ +#define GHOSTTY_COLOR_NAMED_BLACK 0 +/** Red color (1) @ingroup sgr */ +#define GHOSTTY_COLOR_NAMED_RED 1 +/** Green color (2) @ingroup sgr */ +#define GHOSTTY_COLOR_NAMED_GREEN 2 +/** Yellow color (3) @ingroup sgr */ +#define GHOSTTY_COLOR_NAMED_YELLOW 3 +/** Blue color (4) @ingroup sgr */ +#define GHOSTTY_COLOR_NAMED_BLUE 4 +/** Magenta color (5) @ingroup sgr */ +#define GHOSTTY_COLOR_NAMED_MAGENTA 5 +/** Cyan color (6) @ingroup sgr */ +#define GHOSTTY_COLOR_NAMED_CYAN 6 +/** White color (7) @ingroup sgr */ +#define GHOSTTY_COLOR_NAMED_WHITE 7 +/** Bright black color (8) @ingroup sgr */ +#define GHOSTTY_COLOR_NAMED_BRIGHT_BLACK 8 +/** Bright red color (9) @ingroup sgr */ +#define GHOSTTY_COLOR_NAMED_BRIGHT_RED 9 +/** Bright green color (10) @ingroup sgr */ +#define GHOSTTY_COLOR_NAMED_BRIGHT_GREEN 10 +/** Bright yellow color (11) @ingroup sgr */ +#define GHOSTTY_COLOR_NAMED_BRIGHT_YELLOW 11 +/** Bright blue color (12) @ingroup sgr */ +#define GHOSTTY_COLOR_NAMED_BRIGHT_BLUE 12 +/** Bright magenta color (13) @ingroup sgr */ +#define GHOSTTY_COLOR_NAMED_BRIGHT_MAGENTA 13 +/** Bright cyan color (14) @ingroup sgr */ +#define GHOSTTY_COLOR_NAMED_BRIGHT_CYAN 14 +/** Bright white color (15) @ingroup sgr */ +#define GHOSTTY_COLOR_NAMED_BRIGHT_WHITE 15 + +/** @} */ + +/** + * Get the RGB color components. + * + * This function extracts the individual red, green, and blue components + * from a GhosttyColorRgb value. Primarily useful in WebAssembly environments + * where accessing struct fields directly is difficult. + * + * @param color The RGB color value + * @param r Pointer to store the red component (0-255) + * @param g Pointer to store the green component (0-255) + * @param b Pointer to store the blue component (0-255) + * + * @ingroup sgr + */ +void ghostty_color_rgb_get(GhosttyColorRgb color, + uint8_t* r, + uint8_t* g, + uint8_t* b); + +#ifdef __cplusplus +} +#endif + +#endif /* GHOSTTY_VT_COLOR_H */ diff --git a/apps/mobile/modules/t3-terminal/Vendor/libghostty/GhosttyKit.xcframework/ios-arm64-simulator/Headers/ghostty/vt/key.h b/apps/mobile/modules/t3-terminal/Vendor/libghostty/GhosttyKit.xcframework/ios-arm64-simulator/Headers/ghostty/vt/key.h new file mode 100644 index 0000000000..772b5d43bc --- /dev/null +++ b/apps/mobile/modules/t3-terminal/Vendor/libghostty/GhosttyKit.xcframework/ios-arm64-simulator/Headers/ghostty/vt/key.h @@ -0,0 +1,80 @@ +/** + * @file key.h + * + * Key encoding module - encode key events into terminal escape sequences. + */ + +#ifndef GHOSTTY_VT_KEY_H +#define GHOSTTY_VT_KEY_H + +/** @defgroup key Key Encoding + * + * Utilities for encoding key events into terminal escape sequences, + * supporting both legacy encoding as well as Kitty Keyboard Protocol. + * + * ## Basic Usage + * + * 1. Create an encoder instance with ghostty_key_encoder_new() + * 2. Configure encoder options with ghostty_key_encoder_setopt(). + * 3. For each key event: + * - Create a key event with ghostty_key_event_new() + * - Set event properties (action, key, modifiers, etc.) + * - Encode with ghostty_key_encoder_encode() + * - Free the event with ghostty_key_event_free() + * - Note: You can also reuse the same key event multiple times by + * changing its properties. + * 4. Free the encoder with ghostty_key_encoder_free() when done + * + * ## Example + * + * @code{.c} + * #include + * #include + * #include + * + * int main() { + * // Create encoder + * GhosttyKeyEncoder encoder; + * GhosttyResult result = ghostty_key_encoder_new(NULL, &encoder); + * assert(result == GHOSTTY_SUCCESS); + * + * // Enable Kitty keyboard protocol with all features + * ghostty_key_encoder_setopt(encoder, GHOSTTY_KEY_ENCODER_OPT_KITTY_FLAGS, + * &(uint8_t){GHOSTTY_KITTY_KEY_ALL}); + * + * // Create and configure key event for Ctrl+C press + * GhosttyKeyEvent event; + * result = ghostty_key_event_new(NULL, &event); + * assert(result == GHOSTTY_SUCCESS); + * ghostty_key_event_set_action(event, GHOSTTY_KEY_ACTION_PRESS); + * ghostty_key_event_set_key(event, GHOSTTY_KEY_C); + * ghostty_key_event_set_mods(event, GHOSTTY_MODS_CTRL); + * + * // Encode the key event + * char buf[128]; + * size_t written = 0; + * result = ghostty_key_encoder_encode(encoder, event, buf, sizeof(buf), &written); + * assert(result == GHOSTTY_SUCCESS); + * + * // Use the encoded sequence (e.g., write to terminal) + * fwrite(buf, 1, written, stdout); + * + * // Cleanup + * ghostty_key_event_free(event); + * ghostty_key_encoder_free(encoder); + * return 0; + * } + * @endcode + * + * For a complete working example, see example/c-vt-key-encode in the + * repository. + * + * @{ + */ + +#include +#include + +/** @} */ + +#endif /* GHOSTTY_VT_KEY_H */ diff --git a/apps/mobile/modules/t3-terminal/Vendor/libghostty/GhosttyKit.xcframework/ios-arm64-simulator/Headers/ghostty/vt/key/encoder.h b/apps/mobile/modules/t3-terminal/Vendor/libghostty/GhosttyKit.xcframework/ios-arm64-simulator/Headers/ghostty/vt/key/encoder.h new file mode 100644 index 0000000000..766a294279 --- /dev/null +++ b/apps/mobile/modules/t3-terminal/Vendor/libghostty/GhosttyKit.xcframework/ios-arm64-simulator/Headers/ghostty/vt/key/encoder.h @@ -0,0 +1,221 @@ +/** + * @file encoder.h + * + * Key event encoding to terminal escape sequences. + */ + +#ifndef GHOSTTY_VT_KEY_ENCODER_H +#define GHOSTTY_VT_KEY_ENCODER_H + +#include +#include +#include +#include +#include + +/** + * Opaque handle to a key encoder instance. + * + * This handle represents a key encoder that converts key events into terminal + * escape sequences. + * + * @ingroup key + */ +typedef struct GhosttyKeyEncoder *GhosttyKeyEncoder; + +/** + * Kitty keyboard protocol flags. + * + * Bitflags representing the various modes of the Kitty keyboard protocol. + * These can be combined using bitwise OR operations. Valid values all + * start with `GHOSTTY_KITTY_KEY_`. + * + * @ingroup key + */ +typedef uint8_t GhosttyKittyKeyFlags; + +/** Kitty keyboard protocol disabled (all flags off) */ +#define GHOSTTY_KITTY_KEY_DISABLED 0 + +/** Disambiguate escape codes */ +#define GHOSTTY_KITTY_KEY_DISAMBIGUATE (1 << 0) + +/** Report key press and release events */ +#define GHOSTTY_KITTY_KEY_REPORT_EVENTS (1 << 1) + +/** Report alternate key codes */ +#define GHOSTTY_KITTY_KEY_REPORT_ALTERNATES (1 << 2) + +/** Report all key events including those normally handled by the terminal */ +#define GHOSTTY_KITTY_KEY_REPORT_ALL (1 << 3) + +/** Report associated text with key events */ +#define GHOSTTY_KITTY_KEY_REPORT_ASSOCIATED (1 << 4) + +/** All Kitty keyboard protocol flags enabled */ +#define GHOSTTY_KITTY_KEY_ALL (GHOSTTY_KITTY_KEY_DISAMBIGUATE | GHOSTTY_KITTY_KEY_REPORT_EVENTS | GHOSTTY_KITTY_KEY_REPORT_ALTERNATES | GHOSTTY_KITTY_KEY_REPORT_ALL | GHOSTTY_KITTY_KEY_REPORT_ASSOCIATED) + +/** + * macOS option key behavior. + * + * Determines whether the "option" key on macOS is treated as "alt" or not. + * See the Ghostty `macos-option-as-alt` configuration option for more details. + * + * @ingroup key + */ +typedef enum { + /** Option key is not treated as alt */ + GHOSTTY_OPTION_AS_ALT_FALSE = 0, + /** Option key is treated as alt */ + GHOSTTY_OPTION_AS_ALT_TRUE = 1, + /** Only left option key is treated as alt */ + GHOSTTY_OPTION_AS_ALT_LEFT = 2, + /** Only right option key is treated as alt */ + GHOSTTY_OPTION_AS_ALT_RIGHT = 3, +} GhosttyOptionAsAlt; + +/** + * Key encoder option identifiers. + * + * These values are used with ghostty_key_encoder_setopt() to configure + * the behavior of the key encoder. + * + * @ingroup key + */ +typedef enum { + /** Terminal DEC mode 1: cursor key application mode (value: bool) */ + GHOSTTY_KEY_ENCODER_OPT_CURSOR_KEY_APPLICATION = 0, + + /** Terminal DEC mode 66: keypad key application mode (value: bool) */ + GHOSTTY_KEY_ENCODER_OPT_KEYPAD_KEY_APPLICATION = 1, + + /** Terminal DEC mode 1035: ignore keypad with numlock (value: bool) */ + GHOSTTY_KEY_ENCODER_OPT_IGNORE_KEYPAD_WITH_NUMLOCK = 2, + + /** Terminal DEC mode 1036: alt sends escape prefix (value: bool) */ + GHOSTTY_KEY_ENCODER_OPT_ALT_ESC_PREFIX = 3, + + /** xterm modifyOtherKeys mode 2 (value: bool) */ + GHOSTTY_KEY_ENCODER_OPT_MODIFY_OTHER_KEYS_STATE_2 = 4, + + /** Kitty keyboard protocol flags (value: GhosttyKittyKeyFlags bitmask) */ + GHOSTTY_KEY_ENCODER_OPT_KITTY_FLAGS = 5, + + /** macOS option-as-alt setting (value: GhosttyOptionAsAlt) */ + GHOSTTY_KEY_ENCODER_OPT_MACOS_OPTION_AS_ALT = 6, +} GhosttyKeyEncoderOption; + +/** + * Create a new key encoder instance. + * + * Creates a new key encoder with default options. The encoder can be configured + * using ghostty_key_encoder_setopt() and must be freed using + * ghostty_key_encoder_free() when no longer needed. + * + * @param allocator Pointer to the allocator to use for memory management, or NULL to use the default allocator + * @param encoder Pointer to store the created encoder handle + * @return GHOSTTY_SUCCESS on success, or an error code on failure + * + * @ingroup key + */ +GhosttyResult ghostty_key_encoder_new(const GhosttyAllocator *allocator, GhosttyKeyEncoder *encoder); + +/** + * Free a key encoder instance. + * + * Releases all resources associated with the key encoder. After this call, + * the encoder handle becomes invalid and must not be used. + * + * @param encoder The encoder handle to free (may be NULL) + * + * @ingroup key + */ +void ghostty_key_encoder_free(GhosttyKeyEncoder encoder); + +/** + * Set an option on the key encoder. + * + * Configures the behavior of the key encoder. Options control various aspects + * of encoding such as terminal modes (cursor key application mode, keypad mode), + * protocol selection (Kitty keyboard protocol flags), and platform-specific + * behaviors (macOS option-as-alt). + * + * A null pointer value does nothing. It does not reset the value to the + * default. The setopt call will do nothing. + * + * @param encoder The encoder handle, must not be NULL + * @param option The option to set + * @param value Pointer to the value to set (type depends on the option) + * + * @ingroup key + */ +void ghostty_key_encoder_setopt(GhosttyKeyEncoder encoder, GhosttyKeyEncoderOption option, const void *value); + +/** + * Encode a key event into a terminal escape sequence. + * + * Converts a key event into the appropriate terminal escape sequence based on + * the encoder's current options. The sequence is written to the provided buffer. + * + * Not all key events produce output. For example, unmodified modifier keys + * typically don't generate escape sequences. Check the out_len parameter to + * determine if any data was written. + * + * If the output buffer is too small, this function returns GHOSTTY_OUT_OF_MEMORY + * and out_len will contain the required buffer size. The caller can then + * allocate a larger buffer and call the function again. + * + * @param encoder The encoder handle, must not be NULL + * @param event The key event to encode, must not be NULL + * @param out_buf Buffer to write the encoded sequence to + * @param out_buf_size Size of the output buffer in bytes + * @param out_len Pointer to store the number of bytes written (may be NULL) + * @return GHOSTTY_SUCCESS on success, GHOSTTY_OUT_OF_MEMORY if buffer too small, or other error code + * + * ## Example: Calculate required buffer size + * + * @code{.c} + * // Query the required size with a NULL buffer (always returns OUT_OF_MEMORY) + * size_t required = 0; + * GhosttyResult result = ghostty_key_encoder_encode(encoder, event, NULL, 0, &required); + * assert(result == GHOSTTY_OUT_OF_MEMORY); + * + * // Allocate buffer of required size + * char *buf = malloc(required); + * + * // Encode with properly sized buffer + * size_t written = 0; + * result = ghostty_key_encoder_encode(encoder, event, buf, required, &written); + * assert(result == GHOSTTY_SUCCESS); + * + * // Use the encoded sequence... + * + * free(buf); + * @endcode + * + * ## Example: Direct encoding with static buffer + * + * @code{.c} + * // Most escape sequences are short, so a static buffer often suffices + * char buf[128]; + * size_t written = 0; + * GhosttyResult result = ghostty_key_encoder_encode(encoder, event, buf, sizeof(buf), &written); + * + * if (result == GHOSTTY_SUCCESS) { + * // Write the encoded sequence to the terminal + * write(pty_fd, buf, written); + * } else if (result == GHOSTTY_OUT_OF_MEMORY) { + * // Buffer too small, written contains required size + * char *dynamic_buf = malloc(written); + * result = ghostty_key_encoder_encode(encoder, event, dynamic_buf, written, &written); + * assert(result == GHOSTTY_SUCCESS); + * write(pty_fd, dynamic_buf, written); + * free(dynamic_buf); + * } + * @endcode + * + * @ingroup key + */ +GhosttyResult ghostty_key_encoder_encode(GhosttyKeyEncoder encoder, GhosttyKeyEvent event, char *out_buf, size_t out_buf_size, size_t *out_len); + +#endif /* GHOSTTY_VT_KEY_ENCODER_H */ diff --git a/apps/mobile/modules/t3-terminal/Vendor/libghostty/GhosttyKit.xcframework/ios-arm64-simulator/Headers/ghostty/vt/key/event.h b/apps/mobile/modules/t3-terminal/Vendor/libghostty/GhosttyKit.xcframework/ios-arm64-simulator/Headers/ghostty/vt/key/event.h new file mode 100644 index 0000000000..dbd2e9f841 --- /dev/null +++ b/apps/mobile/modules/t3-terminal/Vendor/libghostty/GhosttyKit.xcframework/ios-arm64-simulator/Headers/ghostty/vt/key/event.h @@ -0,0 +1,474 @@ +/** + * @file event.h + * + * Key event representation and manipulation. + */ + +#ifndef GHOSTTY_VT_KEY_EVENT_H +#define GHOSTTY_VT_KEY_EVENT_H + +#include +#include +#include +#include +#include + +/** + * Opaque handle to a key event. + * + * This handle represents a keyboard input event containing information about + * the physical key pressed, modifiers, and generated text. + * + * @ingroup key + */ +typedef struct GhosttyKeyEvent *GhosttyKeyEvent; + +/** + * Keyboard input event types. + * + * @ingroup key + */ +typedef enum { + /** Key was released */ + GHOSTTY_KEY_ACTION_RELEASE = 0, + /** Key was pressed */ + GHOSTTY_KEY_ACTION_PRESS = 1, + /** Key is being repeated (held down) */ + GHOSTTY_KEY_ACTION_REPEAT = 2, +} GhosttyKeyAction; + +/** + * Keyboard modifier keys bitmask. + * + * A bitmask representing all keyboard modifiers. This tracks which modifier keys + * are pressed and, where supported by the platform, which side (left or right) + * of each modifier is active. + * + * Use the GHOSTTY_MODS_* constants to test and set individual modifiers. + * + * Modifier side bits are only meaningful when the corresponding modifier bit is set. + * Not all platforms support distinguishing between left and right modifier + * keys and Ghostty is built to expect that some platforms may not provide this + * information. + * + * @ingroup key + */ +typedef uint16_t GhosttyMods; + +/** Shift key is pressed */ +#define GHOSTTY_MODS_SHIFT (1 << 0) +/** Control key is pressed */ +#define GHOSTTY_MODS_CTRL (1 << 1) +/** Alt/Option key is pressed */ +#define GHOSTTY_MODS_ALT (1 << 2) +/** Super/Command/Windows key is pressed */ +#define GHOSTTY_MODS_SUPER (1 << 3) +/** Caps Lock is active */ +#define GHOSTTY_MODS_CAPS_LOCK (1 << 4) +/** Num Lock is active */ +#define GHOSTTY_MODS_NUM_LOCK (1 << 5) + +/** + * Right shift is pressed (0 = left, 1 = right). + * Only meaningful when GHOSTTY_MODS_SHIFT is set. + */ +#define GHOSTTY_MODS_SHIFT_SIDE (1 << 6) +/** + * Right ctrl is pressed (0 = left, 1 = right). + * Only meaningful when GHOSTTY_MODS_CTRL is set. + */ +#define GHOSTTY_MODS_CTRL_SIDE (1 << 7) +/** + * Right alt is pressed (0 = left, 1 = right). + * Only meaningful when GHOSTTY_MODS_ALT is set. + */ +#define GHOSTTY_MODS_ALT_SIDE (1 << 8) +/** + * Right super is pressed (0 = left, 1 = right). + * Only meaningful when GHOSTTY_MODS_SUPER is set. + */ +#define GHOSTTY_MODS_SUPER_SIDE (1 << 9) + +/** + * Physical key codes. + * + * The set of key codes that Ghostty is aware of. These represent physical keys + * on the keyboard and are layout-independent. For example, the "a" key on a US + * keyboard is the same as the "ф" key on a Russian keyboard, but both will + * report the same key_a value. + * + * Layout-dependent strings are provided separately as UTF-8 text and are produced + * by the platform. These values are based on the W3C UI Events KeyboardEvent code + * standard. See: https://www.w3.org/TR/uievents-code + * + * @ingroup key + */ +typedef enum { + GHOSTTY_KEY_UNIDENTIFIED = 0, + + // Writing System Keys (W3C § 3.1.1) + GHOSTTY_KEY_BACKQUOTE, + GHOSTTY_KEY_BACKSLASH, + GHOSTTY_KEY_BRACKET_LEFT, + GHOSTTY_KEY_BRACKET_RIGHT, + GHOSTTY_KEY_COMMA, + GHOSTTY_KEY_DIGIT_0, + GHOSTTY_KEY_DIGIT_1, + GHOSTTY_KEY_DIGIT_2, + GHOSTTY_KEY_DIGIT_3, + GHOSTTY_KEY_DIGIT_4, + GHOSTTY_KEY_DIGIT_5, + GHOSTTY_KEY_DIGIT_6, + GHOSTTY_KEY_DIGIT_7, + GHOSTTY_KEY_DIGIT_8, + GHOSTTY_KEY_DIGIT_9, + GHOSTTY_KEY_EQUAL, + GHOSTTY_KEY_INTL_BACKSLASH, + GHOSTTY_KEY_INTL_RO, + GHOSTTY_KEY_INTL_YEN, + GHOSTTY_KEY_A, + GHOSTTY_KEY_B, + GHOSTTY_KEY_C, + GHOSTTY_KEY_D, + GHOSTTY_KEY_E, + GHOSTTY_KEY_F, + GHOSTTY_KEY_G, + GHOSTTY_KEY_H, + GHOSTTY_KEY_I, + GHOSTTY_KEY_J, + GHOSTTY_KEY_K, + GHOSTTY_KEY_L, + GHOSTTY_KEY_M, + GHOSTTY_KEY_N, + GHOSTTY_KEY_O, + GHOSTTY_KEY_P, + GHOSTTY_KEY_Q, + GHOSTTY_KEY_R, + GHOSTTY_KEY_S, + GHOSTTY_KEY_T, + GHOSTTY_KEY_U, + GHOSTTY_KEY_V, + GHOSTTY_KEY_W, + GHOSTTY_KEY_X, + GHOSTTY_KEY_Y, + GHOSTTY_KEY_Z, + GHOSTTY_KEY_MINUS, + GHOSTTY_KEY_PERIOD, + GHOSTTY_KEY_QUOTE, + GHOSTTY_KEY_SEMICOLON, + GHOSTTY_KEY_SLASH, + + // Functional Keys (W3C § 3.1.2) + GHOSTTY_KEY_ALT_LEFT, + GHOSTTY_KEY_ALT_RIGHT, + GHOSTTY_KEY_BACKSPACE, + GHOSTTY_KEY_CAPS_LOCK, + GHOSTTY_KEY_CONTEXT_MENU, + GHOSTTY_KEY_CONTROL_LEFT, + GHOSTTY_KEY_CONTROL_RIGHT, + GHOSTTY_KEY_ENTER, + GHOSTTY_KEY_META_LEFT, + GHOSTTY_KEY_META_RIGHT, + GHOSTTY_KEY_SHIFT_LEFT, + GHOSTTY_KEY_SHIFT_RIGHT, + GHOSTTY_KEY_SPACE, + GHOSTTY_KEY_TAB, + GHOSTTY_KEY_CONVERT, + GHOSTTY_KEY_KANA_MODE, + GHOSTTY_KEY_NON_CONVERT, + + // Control Pad Section (W3C § 3.2) + GHOSTTY_KEY_DELETE, + GHOSTTY_KEY_END, + GHOSTTY_KEY_HELP, + GHOSTTY_KEY_HOME, + GHOSTTY_KEY_INSERT, + GHOSTTY_KEY_PAGE_DOWN, + GHOSTTY_KEY_PAGE_UP, + + // Arrow Pad Section (W3C § 3.3) + GHOSTTY_KEY_ARROW_DOWN, + GHOSTTY_KEY_ARROW_LEFT, + GHOSTTY_KEY_ARROW_RIGHT, + GHOSTTY_KEY_ARROW_UP, + + // Numpad Section (W3C § 3.4) + GHOSTTY_KEY_NUM_LOCK, + GHOSTTY_KEY_NUMPAD_0, + GHOSTTY_KEY_NUMPAD_1, + GHOSTTY_KEY_NUMPAD_2, + GHOSTTY_KEY_NUMPAD_3, + GHOSTTY_KEY_NUMPAD_4, + GHOSTTY_KEY_NUMPAD_5, + GHOSTTY_KEY_NUMPAD_6, + GHOSTTY_KEY_NUMPAD_7, + GHOSTTY_KEY_NUMPAD_8, + GHOSTTY_KEY_NUMPAD_9, + GHOSTTY_KEY_NUMPAD_ADD, + GHOSTTY_KEY_NUMPAD_BACKSPACE, + GHOSTTY_KEY_NUMPAD_CLEAR, + GHOSTTY_KEY_NUMPAD_CLEAR_ENTRY, + GHOSTTY_KEY_NUMPAD_COMMA, + GHOSTTY_KEY_NUMPAD_DECIMAL, + GHOSTTY_KEY_NUMPAD_DIVIDE, + GHOSTTY_KEY_NUMPAD_ENTER, + GHOSTTY_KEY_NUMPAD_EQUAL, + GHOSTTY_KEY_NUMPAD_MEMORY_ADD, + GHOSTTY_KEY_NUMPAD_MEMORY_CLEAR, + GHOSTTY_KEY_NUMPAD_MEMORY_RECALL, + GHOSTTY_KEY_NUMPAD_MEMORY_STORE, + GHOSTTY_KEY_NUMPAD_MEMORY_SUBTRACT, + GHOSTTY_KEY_NUMPAD_MULTIPLY, + GHOSTTY_KEY_NUMPAD_PAREN_LEFT, + GHOSTTY_KEY_NUMPAD_PAREN_RIGHT, + GHOSTTY_KEY_NUMPAD_SUBTRACT, + GHOSTTY_KEY_NUMPAD_SEPARATOR, + GHOSTTY_KEY_NUMPAD_UP, + GHOSTTY_KEY_NUMPAD_DOWN, + GHOSTTY_KEY_NUMPAD_RIGHT, + GHOSTTY_KEY_NUMPAD_LEFT, + GHOSTTY_KEY_NUMPAD_BEGIN, + GHOSTTY_KEY_NUMPAD_HOME, + GHOSTTY_KEY_NUMPAD_END, + GHOSTTY_KEY_NUMPAD_INSERT, + GHOSTTY_KEY_NUMPAD_DELETE, + GHOSTTY_KEY_NUMPAD_PAGE_UP, + GHOSTTY_KEY_NUMPAD_PAGE_DOWN, + + // Function Section (W3C § 3.5) + GHOSTTY_KEY_ESCAPE, + GHOSTTY_KEY_F1, + GHOSTTY_KEY_F2, + GHOSTTY_KEY_F3, + GHOSTTY_KEY_F4, + GHOSTTY_KEY_F5, + GHOSTTY_KEY_F6, + GHOSTTY_KEY_F7, + GHOSTTY_KEY_F8, + GHOSTTY_KEY_F9, + GHOSTTY_KEY_F10, + GHOSTTY_KEY_F11, + GHOSTTY_KEY_F12, + GHOSTTY_KEY_F13, + GHOSTTY_KEY_F14, + GHOSTTY_KEY_F15, + GHOSTTY_KEY_F16, + GHOSTTY_KEY_F17, + GHOSTTY_KEY_F18, + GHOSTTY_KEY_F19, + GHOSTTY_KEY_F20, + GHOSTTY_KEY_F21, + GHOSTTY_KEY_F22, + GHOSTTY_KEY_F23, + GHOSTTY_KEY_F24, + GHOSTTY_KEY_F25, + GHOSTTY_KEY_FN, + GHOSTTY_KEY_FN_LOCK, + GHOSTTY_KEY_PRINT_SCREEN, + GHOSTTY_KEY_SCROLL_LOCK, + GHOSTTY_KEY_PAUSE, + + // Media Keys (W3C § 3.6) + GHOSTTY_KEY_BROWSER_BACK, + GHOSTTY_KEY_BROWSER_FAVORITES, + GHOSTTY_KEY_BROWSER_FORWARD, + GHOSTTY_KEY_BROWSER_HOME, + GHOSTTY_KEY_BROWSER_REFRESH, + GHOSTTY_KEY_BROWSER_SEARCH, + GHOSTTY_KEY_BROWSER_STOP, + GHOSTTY_KEY_EJECT, + GHOSTTY_KEY_LAUNCH_APP_1, + GHOSTTY_KEY_LAUNCH_APP_2, + GHOSTTY_KEY_LAUNCH_MAIL, + GHOSTTY_KEY_MEDIA_PLAY_PAUSE, + GHOSTTY_KEY_MEDIA_SELECT, + GHOSTTY_KEY_MEDIA_STOP, + GHOSTTY_KEY_MEDIA_TRACK_NEXT, + GHOSTTY_KEY_MEDIA_TRACK_PREVIOUS, + GHOSTTY_KEY_POWER, + GHOSTTY_KEY_SLEEP, + GHOSTTY_KEY_AUDIO_VOLUME_DOWN, + GHOSTTY_KEY_AUDIO_VOLUME_MUTE, + GHOSTTY_KEY_AUDIO_VOLUME_UP, + GHOSTTY_KEY_WAKE_UP, + + // Legacy, Non-standard, and Special Keys (W3C § 3.7) + GHOSTTY_KEY_COPY, + GHOSTTY_KEY_CUT, + GHOSTTY_KEY_PASTE, +} GhosttyKey; + +/** + * Create a new key event instance. + * + * Creates a new key event with default values. The event must be freed using + * ghostty_key_event_free() when no longer needed. + * + * @param allocator Pointer to the allocator to use for memory management, or NULL to use the default allocator + * @param event Pointer to store the created key event handle + * @return GHOSTTY_SUCCESS on success, or an error code on failure + * + * @ingroup key + */ +GhosttyResult ghostty_key_event_new(const GhosttyAllocator *allocator, GhosttyKeyEvent *event); + +/** + * Free a key event instance. + * + * Releases all resources associated with the key event. After this call, + * the event handle becomes invalid and must not be used. + * + * @param event The key event handle to free (may be NULL) + * + * @ingroup key + */ +void ghostty_key_event_free(GhosttyKeyEvent event); + +/** + * Set the key action (press, release, repeat). + * + * @param event The key event handle, must not be NULL + * @param action The action to set + * + * @ingroup key + */ +void ghostty_key_event_set_action(GhosttyKeyEvent event, GhosttyKeyAction action); + +/** + * Get the key action (press, release, repeat). + * + * @param event The key event handle, must not be NULL + * @return The key action + * + * @ingroup key + */ +GhosttyKeyAction ghostty_key_event_get_action(GhosttyKeyEvent event); + +/** + * Set the physical key code. + * + * @param event The key event handle, must not be NULL + * @param key The physical key code to set + * + * @ingroup key + */ +void ghostty_key_event_set_key(GhosttyKeyEvent event, GhosttyKey key); + +/** + * Get the physical key code. + * + * @param event The key event handle, must not be NULL + * @return The physical key code + * + * @ingroup key + */ +GhosttyKey ghostty_key_event_get_key(GhosttyKeyEvent event); + +/** + * Set the modifier keys bitmask. + * + * @param event The key event handle, must not be NULL + * @param mods The modifier keys bitmask to set + * + * @ingroup key + */ +void ghostty_key_event_set_mods(GhosttyKeyEvent event, GhosttyMods mods); + +/** + * Get the modifier keys bitmask. + * + * @param event The key event handle, must not be NULL + * @return The modifier keys bitmask + * + * @ingroup key + */ +GhosttyMods ghostty_key_event_get_mods(GhosttyKeyEvent event); + +/** + * Set the consumed modifiers bitmask. + * + * @param event The key event handle, must not be NULL + * @param consumed_mods The consumed modifiers bitmask to set + * + * @ingroup key + */ +void ghostty_key_event_set_consumed_mods(GhosttyKeyEvent event, GhosttyMods consumed_mods); + +/** + * Get the consumed modifiers bitmask. + * + * @param event The key event handle, must not be NULL + * @return The consumed modifiers bitmask + * + * @ingroup key + */ +GhosttyMods ghostty_key_event_get_consumed_mods(GhosttyKeyEvent event); + +/** + * Set whether the key event is part of a composition sequence. + * + * @param event The key event handle, must not be NULL + * @param composing Whether the key event is part of a composition sequence + * + * @ingroup key + */ +void ghostty_key_event_set_composing(GhosttyKeyEvent event, bool composing); + +/** + * Get whether the key event is part of a composition sequence. + * + * @param event The key event handle, must not be NULL + * @return Whether the key event is part of a composition sequence + * + * @ingroup key + */ +bool ghostty_key_event_get_composing(GhosttyKeyEvent event); + +/** + * Set the UTF-8 text generated by the key event. + * + * The key event does NOT take ownership of the text pointer. The caller + * must ensure the string remains valid for the lifetime needed by the event. + * + * @param event The key event handle, must not be NULL + * @param utf8 The UTF-8 text to set (or NULL for empty) + * @param len Length of the UTF-8 text in bytes + * + * @ingroup key + */ +void ghostty_key_event_set_utf8(GhosttyKeyEvent event, const char *utf8, size_t len); + +/** + * Get the UTF-8 text generated by the key event. + * + * The returned pointer is valid until the event is freed or the UTF-8 text is modified. + * + * @param event The key event handle, must not be NULL + * @param len Pointer to store the length of the UTF-8 text in bytes (may be NULL) + * @return The UTF-8 text (or NULL for empty) + * + * @ingroup key + */ +const char *ghostty_key_event_get_utf8(GhosttyKeyEvent event, size_t *len); + +/** + * Set the unshifted Unicode codepoint. + * + * @param event The key event handle, must not be NULL + * @param codepoint The unshifted Unicode codepoint to set + * + * @ingroup key + */ +void ghostty_key_event_set_unshifted_codepoint(GhosttyKeyEvent event, uint32_t codepoint); + +/** + * Get the unshifted Unicode codepoint. + * + * @param event The key event handle, must not be NULL + * @return The unshifted Unicode codepoint + * + * @ingroup key + */ +uint32_t ghostty_key_event_get_unshifted_codepoint(GhosttyKeyEvent event); + +#endif /* GHOSTTY_VT_KEY_EVENT_H */ diff --git a/apps/mobile/modules/t3-terminal/Vendor/libghostty/GhosttyKit.xcframework/ios-arm64-simulator/Headers/ghostty/vt/osc.h b/apps/mobile/modules/t3-terminal/Vendor/libghostty/GhosttyKit.xcframework/ios-arm64-simulator/Headers/ghostty/vt/osc.h new file mode 100644 index 0000000000..f53077ab32 --- /dev/null +++ b/apps/mobile/modules/t3-terminal/Vendor/libghostty/GhosttyKit.xcframework/ios-arm64-simulator/Headers/ghostty/vt/osc.h @@ -0,0 +1,233 @@ +/** + * @file osc.h + * + * OSC (Operating System Command) sequence parser and command handling. + */ + +#ifndef GHOSTTY_VT_OSC_H +#define GHOSTTY_VT_OSC_H + +#include +#include +#include +#include +#include + +/** + * Opaque handle to an OSC parser instance. + * + * This handle represents an OSC (Operating System Command) parser that can + * be used to parse the contents of OSC sequences. + * + * @ingroup osc + */ +typedef struct GhosttyOscParser *GhosttyOscParser; + +/** + * Opaque handle to a single OSC command. + * + * This handle represents a parsed OSC (Operating System Command) command. + * The command can be queried for its type and associated data. + * + * @ingroup osc + */ +typedef struct GhosttyOscCommand *GhosttyOscCommand; + +/** @defgroup osc OSC Parser + * + * OSC (Operating System Command) sequence parser and command handling. + * + * The parser operates in a streaming fashion, processing input byte-by-byte + * to handle OSC sequences that may arrive in fragments across multiple reads. + * This interface makes it easy to integrate into most environments and avoids + * over-allocating buffers. + * + * ## Basic Usage + * + * 1. Create a parser instance with ghostty_osc_new() + * 2. Feed bytes to the parser using ghostty_osc_next() + * 3. Finalize parsing with ghostty_osc_end() to get the command + * 4. Query command type and extract data using ghostty_osc_command_type() + * and ghostty_osc_command_data() + * 5. Free the parser with ghostty_osc_free() when done + * + * @{ + */ + +/** + * OSC command types. + * + * @ingroup osc + */ +typedef enum { + GHOSTTY_OSC_COMMAND_INVALID = 0, + GHOSTTY_OSC_COMMAND_CHANGE_WINDOW_TITLE = 1, + GHOSTTY_OSC_COMMAND_CHANGE_WINDOW_ICON = 2, + GHOSTTY_OSC_COMMAND_SEMANTIC_PROMPT = 3, + GHOSTTY_OSC_COMMAND_CLIPBOARD_CONTENTS = 4, + GHOSTTY_OSC_COMMAND_REPORT_PWD = 5, + GHOSTTY_OSC_COMMAND_MOUSE_SHAPE = 6, + GHOSTTY_OSC_COMMAND_COLOR_OPERATION = 7, + GHOSTTY_OSC_COMMAND_KITTY_COLOR_PROTOCOL = 8, + GHOSTTY_OSC_COMMAND_SHOW_DESKTOP_NOTIFICATION = 9, + GHOSTTY_OSC_COMMAND_HYPERLINK_START = 10, + GHOSTTY_OSC_COMMAND_HYPERLINK_END = 11, + GHOSTTY_OSC_COMMAND_CONEMU_SLEEP = 12, + GHOSTTY_OSC_COMMAND_CONEMU_SHOW_MESSAGE_BOX = 13, + GHOSTTY_OSC_COMMAND_CONEMU_CHANGE_TAB_TITLE = 14, + GHOSTTY_OSC_COMMAND_CONEMU_PROGRESS_REPORT = 15, + GHOSTTY_OSC_COMMAND_CONEMU_WAIT_INPUT = 16, + GHOSTTY_OSC_COMMAND_CONEMU_GUIMACRO = 17, + GHOSTTY_OSC_COMMAND_CONEMU_RUN_PROCESS = 18, + GHOSTTY_OSC_COMMAND_CONEMU_OUTPUT_ENVIRONMENT_VARIABLE = 19, + GHOSTTY_OSC_COMMAND_CONEMU_XTERM_EMULATION = 20, + GHOSTTY_OSC_COMMAND_CONEMU_COMMENT = 21, + GHOSTTY_OSC_COMMAND_KITTY_TEXT_SIZING = 22, +} GhosttyOscCommandType; + +/** + * OSC command data types. + * + * These values specify what type of data to extract from an OSC command + * using `ghostty_osc_command_data`. + * + * @ingroup osc + */ +typedef enum { + /** Invalid data type. Never results in any data extraction. */ + GHOSTTY_OSC_DATA_INVALID = 0, + + /** + * Window title string data. + * + * Valid for: GHOSTTY_OSC_COMMAND_CHANGE_WINDOW_TITLE + * + * Output type: const char ** (pointer to null-terminated string) + * + * Lifetime: Valid until the next call to any ghostty_osc_* function with + * the same parser instance. Memory is owned by the parser. + */ + GHOSTTY_OSC_DATA_CHANGE_WINDOW_TITLE_STR = 1, +} GhosttyOscCommandData; + +/** + * Create a new OSC parser instance. + * + * Creates a new OSC (Operating System Command) parser using the provided + * allocator. The parser must be freed using ghostty_vt_osc_free() when + * no longer needed. + * + * @param allocator Pointer to the allocator to use for memory management, or NULL to use the default allocator + * @param parser Pointer to store the created parser handle + * @return GHOSTTY_SUCCESS on success, or an error code on failure + * + * @ingroup osc + */ +GhosttyResult ghostty_osc_new(const GhosttyAllocator *allocator, GhosttyOscParser *parser); + +/** + * Free an OSC parser instance. + * + * Releases all resources associated with the OSC parser. After this call, + * the parser handle becomes invalid and must not be used. + * + * @param parser The parser handle to free (may be NULL) + * + * @ingroup osc + */ +void ghostty_osc_free(GhosttyOscParser parser); + +/** + * Reset an OSC parser instance to its initial state. + * + * Resets the parser state, clearing any partially parsed OSC sequences + * and returning the parser to its initial state. This is useful for + * reusing a parser instance or recovering from parse errors. + * + * @param parser The parser handle to reset, must not be null. + * + * @ingroup osc + */ +void ghostty_osc_reset(GhosttyOscParser parser); + +/** + * Parse the next byte in an OSC sequence. + * + * Processes a single byte as part of an OSC sequence. The parser maintains + * internal state to track the progress through the sequence. Call this + * function for each byte in the sequence data. + * + * When finished pumping the parser with bytes, call ghostty_osc_end + * to get the final result. + * + * @param parser The parser handle, must not be null. + * @param byte The next byte to parse + * + * @ingroup osc + */ +void ghostty_osc_next(GhosttyOscParser parser, uint8_t byte); + +/** + * Finalize OSC parsing and retrieve the parsed command. + * + * Call this function after feeding all bytes of an OSC sequence to the parser + * using ghostty_osc_next() with the exception of the terminating character + * (ESC or ST). This function finalizes the parsing process and returns the + * parsed OSC command. + * + * The return value is never NULL. Invalid commands will return a command + * with type GHOSTTY_OSC_COMMAND_INVALID. + * + * The terminator parameter specifies the byte that terminated the OSC sequence + * (typically 0x07 for BEL or 0x5C for ST after ESC). This information is + * preserved in the parsed command so that responses can use the same terminator + * format for better compatibility with the calling program. For commands that + * do not require a response, this parameter is ignored and the resulting + * command will not retain the terminator information. + * + * The returned command handle is valid until the next call to any + * `ghostty_osc_*` function with the same parser instance with the exception + * of command introspection functions such as `ghostty_osc_command_type`. + * + * @param parser The parser handle, must not be null. + * @param terminator The terminating byte of the OSC sequence (0x07 for BEL, 0x5C for ST) + * @return Handle to the parsed OSC command + * + * @ingroup osc + */ +GhosttyOscCommand ghostty_osc_end(GhosttyOscParser parser, uint8_t terminator); + +/** + * Get the type of an OSC command. + * + * Returns the type identifier for the given OSC command. This can be used + * to determine what kind of command was parsed and what data might be + * available from it. + * + * @param command The OSC command handle to query (may be NULL) + * @return The command type, or GHOSTTY_OSC_COMMAND_INVALID if command is NULL + * + * @ingroup osc + */ +GhosttyOscCommandType ghostty_osc_command_type(GhosttyOscCommand command); + +/** + * Extract data from an OSC command. + * + * Extracts typed data from the given OSC command based on the specified + * data type. The output pointer must be of the appropriate type for the + * requested data kind. Valid command types, output types, and memory + * safety information are documented in the `GhosttyOscCommandData` enum. + * + * @param command The OSC command handle to query (may be NULL) + * @param data The type of data to extract + * @param out Pointer to store the extracted data (type depends on data parameter) + * @return true if data extraction was successful, false otherwise + * + * @ingroup osc + */ +bool ghostty_osc_command_data(GhosttyOscCommand command, GhosttyOscCommandData data, void *out); + +/** @} */ + +#endif /* GHOSTTY_VT_OSC_H */ diff --git a/apps/mobile/modules/t3-terminal/Vendor/libghostty/GhosttyKit.xcframework/ios-arm64-simulator/Headers/ghostty/vt/paste.h b/apps/mobile/modules/t3-terminal/Vendor/libghostty/GhosttyKit.xcframework/ios-arm64-simulator/Headers/ghostty/vt/paste.h new file mode 100644 index 0000000000..d90f303d43 --- /dev/null +++ b/apps/mobile/modules/t3-terminal/Vendor/libghostty/GhosttyKit.xcframework/ios-arm64-simulator/Headers/ghostty/vt/paste.h @@ -0,0 +1,75 @@ +/** + * @file paste.h + * + * Paste utilities - validate and encode paste data for terminal input. + */ + +#ifndef GHOSTTY_VT_PASTE_H +#define GHOSTTY_VT_PASTE_H + +/** @defgroup paste Paste Utilities + * + * Utilities for validating paste data safety. + * + * ## Basic Usage + * + * Use ghostty_paste_is_safe() to check if paste data contains potentially + * dangerous sequences before sending it to the terminal. + * + * ## Example + * + * @code{.c} + * #include + * #include + * #include + * + * int main() { + * const char* safe_data = "hello world"; + * const char* unsafe_data = "rm -rf /\n"; + * + * if (ghostty_paste_is_safe(safe_data, strlen(safe_data))) { + * printf("Safe to paste\n"); + * } + * + * if (!ghostty_paste_is_safe(unsafe_data, strlen(unsafe_data))) { + * printf("Unsafe! Contains newline\n"); + * } + * + * return 0; + * } + * @endcode + * + * @{ + */ + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * Check if paste data is safe to paste into the terminal. + * + * Data is considered unsafe if it contains: + * - Newlines (`\n`) which can inject commands + * - The bracketed paste end sequence (`\x1b[201~`) which can be used + * to exit bracketed paste mode and inject commands + * + * This check is conservative and considers data unsafe regardless of + * current terminal state. + * + * @param data The paste data to check (must not be NULL) + * @param len The length of the data in bytes + * @return true if the data is safe to paste, false otherwise + */ +bool ghostty_paste_is_safe(const char* data, size_t len); + +#ifdef __cplusplus +} +#endif + +/** @} */ + +#endif /* GHOSTTY_VT_PASTE_H */ diff --git a/apps/mobile/modules/t3-terminal/Vendor/libghostty/GhosttyKit.xcframework/ios-arm64-simulator/Headers/ghostty/vt/result.h b/apps/mobile/modules/t3-terminal/Vendor/libghostty/GhosttyKit.xcframework/ios-arm64-simulator/Headers/ghostty/vt/result.h new file mode 100644 index 0000000000..65938ee766 --- /dev/null +++ b/apps/mobile/modules/t3-terminal/Vendor/libghostty/GhosttyKit.xcframework/ios-arm64-simulator/Headers/ghostty/vt/result.h @@ -0,0 +1,22 @@ +/** + * @file result.h + * + * Result codes for libghostty-vt operations. + */ + +#ifndef GHOSTTY_VT_RESULT_H +#define GHOSTTY_VT_RESULT_H + +/** + * Result codes for libghostty-vt operations. + */ +typedef enum { + /** Operation completed successfully */ + GHOSTTY_SUCCESS = 0, + /** Operation failed due to failed allocation */ + GHOSTTY_OUT_OF_MEMORY = -1, + /** Operation failed due to invalid value */ + GHOSTTY_INVALID_VALUE = -2, +} GhosttyResult; + +#endif /* GHOSTTY_VT_RESULT_H */ diff --git a/apps/mobile/modules/t3-terminal/Vendor/libghostty/GhosttyKit.xcframework/ios-arm64-simulator/Headers/ghostty/vt/sgr.h b/apps/mobile/modules/t3-terminal/Vendor/libghostty/GhosttyKit.xcframework/ios-arm64-simulator/Headers/ghostty/vt/sgr.h new file mode 100644 index 0000000000..0c1afc309b --- /dev/null +++ b/apps/mobile/modules/t3-terminal/Vendor/libghostty/GhosttyKit.xcframework/ios-arm64-simulator/Headers/ghostty/vt/sgr.h @@ -0,0 +1,394 @@ +/** + * @file sgr.h + * + * SGR (Select Graphic Rendition) attribute parsing and handling. + */ + +#ifndef GHOSTTY_VT_SGR_H +#define GHOSTTY_VT_SGR_H + +/** @defgroup sgr SGR Parser + * + * SGR (Select Graphic Rendition) attribute parser. + * + * SGR sequences are the syntax used to set styling attributes such as + * bold, italic, underline, and colors for text in terminal emulators. + * For example, you may be familiar with sequences like `ESC[1;31m`. The + * `1;31` is the SGR attribute list. + * + * The parser processes SGR parameters from CSI sequences (e.g., `ESC[1;31m`) + * and returns individual text attributes like bold, italic, colors, etc. + * It supports both semicolon (`;`) and colon (`:`) separators, possibly mixed, + * and handles various color formats including 8-color, 16-color, 256-color, + * X11 named colors, and RGB in multiple formats. + * + * ## Basic Usage + * + * 1. Create a parser instance with ghostty_sgr_new() + * 2. Set SGR parameters with ghostty_sgr_set_params() + * 3. Iterate through attributes using ghostty_sgr_next() + * 4. Free the parser with ghostty_sgr_free() when done + * + * ## Example + * + * @code{.c} + * #include + * #include + * #include + * + * int main() { + * // Create parser + * GhosttySgrParser parser; + * GhosttyResult result = ghostty_sgr_new(NULL, &parser); + * assert(result == GHOSTTY_SUCCESS); + * + * // Parse "bold, red foreground" sequence: ESC[1;31m + * uint16_t params[] = {1, 31}; + * result = ghostty_sgr_set_params(parser, params, NULL, 2); + * assert(result == GHOSTTY_SUCCESS); + * + * // Iterate through attributes + * GhosttySgrAttribute attr; + * while (ghostty_sgr_next(parser, &attr)) { + * switch (attr.tag) { + * case GHOSTTY_SGR_ATTR_BOLD: + * printf("Bold enabled\n"); + * break; + * case GHOSTTY_SGR_ATTR_FG_8: + * printf("Foreground color: %d\n", attr.value.fg_8); + * break; + * default: + * break; + * } + * } + * + * // Cleanup + * ghostty_sgr_free(parser); + * return 0; + * } + * @endcode + * + * @{ + */ + +#include +#include +#include +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * Opaque handle to an SGR parser instance. + * + * This handle represents an SGR (Select Graphic Rendition) parser that can + * be used to parse SGR sequences and extract individual text attributes. + * + * @ingroup sgr + */ +typedef struct GhosttySgrParser* GhosttySgrParser; + +/** + * SGR attribute tags. + * + * These values identify the type of an SGR attribute in a tagged union. + * Use the tag to determine which field in the attribute value union to access. + * + * @ingroup sgr + */ +typedef enum { + GHOSTTY_SGR_ATTR_UNSET = 0, + GHOSTTY_SGR_ATTR_UNKNOWN = 1, + GHOSTTY_SGR_ATTR_BOLD = 2, + GHOSTTY_SGR_ATTR_RESET_BOLD = 3, + GHOSTTY_SGR_ATTR_ITALIC = 4, + GHOSTTY_SGR_ATTR_RESET_ITALIC = 5, + GHOSTTY_SGR_ATTR_FAINT = 6, + GHOSTTY_SGR_ATTR_UNDERLINE = 7, + GHOSTTY_SGR_ATTR_RESET_UNDERLINE = 8, + GHOSTTY_SGR_ATTR_UNDERLINE_COLOR = 9, + GHOSTTY_SGR_ATTR_UNDERLINE_COLOR_256 = 10, + GHOSTTY_SGR_ATTR_RESET_UNDERLINE_COLOR = 11, + GHOSTTY_SGR_ATTR_OVERLINE = 12, + GHOSTTY_SGR_ATTR_RESET_OVERLINE = 13, + GHOSTTY_SGR_ATTR_BLINK = 14, + GHOSTTY_SGR_ATTR_RESET_BLINK = 15, + GHOSTTY_SGR_ATTR_INVERSE = 16, + GHOSTTY_SGR_ATTR_RESET_INVERSE = 17, + GHOSTTY_SGR_ATTR_INVISIBLE = 18, + GHOSTTY_SGR_ATTR_RESET_INVISIBLE = 19, + GHOSTTY_SGR_ATTR_STRIKETHROUGH = 20, + GHOSTTY_SGR_ATTR_RESET_STRIKETHROUGH = 21, + GHOSTTY_SGR_ATTR_DIRECT_COLOR_FG = 22, + GHOSTTY_SGR_ATTR_DIRECT_COLOR_BG = 23, + GHOSTTY_SGR_ATTR_BG_8 = 24, + GHOSTTY_SGR_ATTR_FG_8 = 25, + GHOSTTY_SGR_ATTR_RESET_FG = 26, + GHOSTTY_SGR_ATTR_RESET_BG = 27, + GHOSTTY_SGR_ATTR_BRIGHT_BG_8 = 28, + GHOSTTY_SGR_ATTR_BRIGHT_FG_8 = 29, + GHOSTTY_SGR_ATTR_BG_256 = 30, + GHOSTTY_SGR_ATTR_FG_256 = 31, +} GhosttySgrAttributeTag; + +/** + * Underline style types. + * + * @ingroup sgr + */ +typedef enum { + GHOSTTY_SGR_UNDERLINE_NONE = 0, + GHOSTTY_SGR_UNDERLINE_SINGLE = 1, + GHOSTTY_SGR_UNDERLINE_DOUBLE = 2, + GHOSTTY_SGR_UNDERLINE_CURLY = 3, + GHOSTTY_SGR_UNDERLINE_DOTTED = 4, + GHOSTTY_SGR_UNDERLINE_DASHED = 5, +} GhosttySgrUnderline; + +/** + * Unknown SGR attribute data. + * + * Contains the full parameter list and the partial list where parsing + * encountered an unknown or invalid sequence. + * + * @ingroup sgr + */ +typedef struct { + const uint16_t* full_ptr; + size_t full_len; + const uint16_t* partial_ptr; + size_t partial_len; +} GhosttySgrUnknown; + +/** + * SGR attribute value union. + * + * This union contains all possible attribute values. Use the tag field + * to determine which union member is active. Attributes without associated + * data (like bold, italic) don't use the union value. + * + * @ingroup sgr + */ +typedef union { + GhosttySgrUnknown unknown; + GhosttySgrUnderline underline; + GhosttyColorRgb underline_color; + GhosttyColorPaletteIndex underline_color_256; + GhosttyColorRgb direct_color_fg; + GhosttyColorRgb direct_color_bg; + GhosttyColorPaletteIndex bg_8; + GhosttyColorPaletteIndex fg_8; + GhosttyColorPaletteIndex bright_bg_8; + GhosttyColorPaletteIndex bright_fg_8; + GhosttyColorPaletteIndex bg_256; + GhosttyColorPaletteIndex fg_256; + uint64_t _padding[8]; +} GhosttySgrAttributeValue; + +/** + * SGR attribute (tagged union). + * + * A complete SGR attribute with both its type tag and associated value. + * Always check the tag field to determine which value union member is valid. + * + * Attributes without associated data (e.g., GHOSTTY_SGR_ATTR_BOLD) can be + * identified by tag alone; the value union is not used for these and + * the memory in the value field is undefined. + * + * @ingroup sgr + */ +typedef struct { + GhosttySgrAttributeTag tag; + GhosttySgrAttributeValue value; +} GhosttySgrAttribute; + +/** + * Create a new SGR parser instance. + * + * Creates a new SGR (Select Graphic Rendition) parser using the provided + * allocator. The parser must be freed using ghostty_sgr_free() when + * no longer needed. + * + * @param allocator Pointer to the allocator to use for memory management, or + * NULL to use the default allocator + * @param parser Pointer to store the created parser handle + * @return GHOSTTY_SUCCESS on success, or an error code on failure + * + * @ingroup sgr + */ +GhosttyResult ghostty_sgr_new(const GhosttyAllocator* allocator, + GhosttySgrParser* parser); + +/** + * Free an SGR parser instance. + * + * Releases all resources associated with the SGR parser. After this call, + * the parser handle becomes invalid and must not be used. This includes + * any attributes previously returned by ghostty_sgr_next(). + * + * @param parser The parser handle to free (may be NULL) + * + * @ingroup sgr + */ +void ghostty_sgr_free(GhosttySgrParser parser); + +/** + * Reset an SGR parser instance to the beginning of the parameter list. + * + * Resets the parser's iteration state without clearing the parameters. + * After calling this, ghostty_sgr_next() will start from the beginning + * of the parameter list again. + * + * @param parser The parser handle to reset, must not be NULL + * + * @ingroup sgr + */ +void ghostty_sgr_reset(GhosttySgrParser parser); + +/** + * Set SGR parameters for parsing. + * + * Sets the SGR parameter list to parse. Parameters are the numeric values + * from a CSI SGR sequence (e.g., for `ESC[1;31m`, params would be {1, 31}). + * + * The separators array optionally specifies the separator type for each + * parameter position. Each byte should be either ';' for semicolon or ':' + * for colon. This is needed for certain color formats that use colon + * separators (e.g., `ESC[4:3m` for curly underline). Any invalid separator + * values are treated as semicolons. The separators array must have the same + * length as the params array, if it is not NULL. + * + * If separators is NULL, all parameters are assumed to be semicolon-separated. + * + * This function makes an internal copy of the parameter and separator data, + * so the caller can safely free or modify the input arrays after this call. + * + * After calling this function, the parser is automatically reset and ready + * to iterate from the beginning. + * + * @param parser The parser handle, must not be NULL + * @param params Array of SGR parameter values + * @param separators Optional array of separator characters (';' or ':'), or + * NULL + * @param len Number of parameters (and separators if provided) + * @return GHOSTTY_SUCCESS on success, or an error code on failure + * + * @ingroup sgr + */ +GhosttyResult ghostty_sgr_set_params(GhosttySgrParser parser, + const uint16_t* params, + const char* separators, + size_t len); + +/** + * Get the next SGR attribute. + * + * Parses and returns the next attribute from the parameter list. + * Call this function repeatedly until it returns false to process + * all attributes in the sequence. + * + * @param parser The parser handle, must not be NULL + * @param attr Pointer to store the next attribute + * @return true if an attribute was returned, false if no more attributes + * + * @ingroup sgr + */ +bool ghostty_sgr_next(GhosttySgrParser parser, GhosttySgrAttribute* attr); + +/** + * Get the full parameter list from an unknown SGR attribute. + * + * This function retrieves the full parameter list that was provided to the + * parser when an unknown attribute was encountered. Primarily useful in + * WebAssembly environments where accessing struct fields directly is difficult. + * + * @param unknown The unknown attribute data + * @param ptr Pointer to store the pointer to the parameter array (may be NULL) + * @return The length of the full parameter array + * + * @ingroup sgr + */ +size_t ghostty_sgr_unknown_full(GhosttySgrUnknown unknown, + const uint16_t** ptr); + +/** + * Get the partial parameter list from an unknown SGR attribute. + * + * This function retrieves the partial parameter list where parsing stopped + * when an unknown attribute was encountered. Primarily useful in WebAssembly + * environments where accessing struct fields directly is difficult. + * + * @param unknown The unknown attribute data + * @param ptr Pointer to store the pointer to the parameter array (may be NULL) + * @return The length of the partial parameter array + * + * @ingroup sgr + */ +size_t ghostty_sgr_unknown_partial(GhosttySgrUnknown unknown, + const uint16_t** ptr); + +/** + * Get the tag from an SGR attribute. + * + * This function extracts the tag that identifies which type of attribute + * this is. Primarily useful in WebAssembly environments where accessing + * struct fields directly is difficult. + * + * @param attr The SGR attribute + * @return The attribute tag + * + * @ingroup sgr + */ +GhosttySgrAttributeTag ghostty_sgr_attribute_tag(GhosttySgrAttribute attr); + +/** + * Get the value from an SGR attribute. + * + * This function returns a pointer to the value union from an SGR attribute. Use + * the tag to determine which field of the union is valid. Primarily useful in + * WebAssembly environments where accessing struct fields directly is difficult. + * + * @param attr Pointer to the SGR attribute + * @return Pointer to the attribute value union + * + * @ingroup sgr + */ +GhosttySgrAttributeValue* ghostty_sgr_attribute_value( + GhosttySgrAttribute* attr); + +#ifdef __wasm__ +/** + * Allocate memory for an SGR attribute (WebAssembly only). + * + * This is a convenience function for WebAssembly environments to allocate + * memory for an SGR attribute structure that can be passed to ghostty_sgr_next. + * + * @return Pointer to the allocated attribute structure + * + * @ingroup wasm + */ +GhosttySgrAttribute* ghostty_wasm_alloc_sgr_attribute(void); + +/** + * Free memory for an SGR attribute (WebAssembly only). + * + * Frees memory allocated by ghostty_wasm_alloc_sgr_attribute. + * + * @param attr Pointer to the attribute structure to free + * + * @ingroup wasm + */ +void ghostty_wasm_free_sgr_attribute(GhosttySgrAttribute* attr); +#endif + +#ifdef __cplusplus +} +#endif + +/** @} */ + +#endif /* GHOSTTY_VT_SGR_H */ diff --git a/apps/mobile/modules/t3-terminal/Vendor/libghostty/GhosttyKit.xcframework/ios-arm64-simulator/Headers/ghostty/vt/wasm.h b/apps/mobile/modules/t3-terminal/Vendor/libghostty/GhosttyKit.xcframework/ios-arm64-simulator/Headers/ghostty/vt/wasm.h new file mode 100644 index 0000000000..37a8263265 --- /dev/null +++ b/apps/mobile/modules/t3-terminal/Vendor/libghostty/GhosttyKit.xcframework/ios-arm64-simulator/Headers/ghostty/vt/wasm.h @@ -0,0 +1,159 @@ +/** + * @file wasm.h + * + * WebAssembly utility functions for libghostty-vt. + */ + +#ifndef GHOSTTY_VT_WASM_H +#define GHOSTTY_VT_WASM_H + +#ifdef __wasm__ + +#include +#include + +/** @defgroup wasm WebAssembly Utilities + * + * Convenience functions for allocating various types in WebAssembly builds. + * **These are only available the libghostty-vt wasm module.** + * + * Ghostty relies on pointers to various types for ABI compatibility, and + * creating those pointers in Wasm can be tedious. These functions provide + * a purely additive set of utilities that simplify memory management in + * Wasm environments without changing the core C library API. + * + * @note These functions always use the default allocator. If you need + * custom allocation strategies, you should allocate types manually using + * your custom allocator. This is a very rare use case in the WebAssembly + * world so these are optimized for simplicity. + * + * ## Example Usage + * + * Here's a simple example of using the Wasm utilities with the key encoder: + * + * @code + * const { exports } = wasmInstance; + * const view = new DataView(wasmMemory.buffer); + * + * // Create key encoder + * const encoderPtr = exports.ghostty_wasm_alloc_opaque(); + * exports.ghostty_key_encoder_new(null, encoderPtr); + * const encoder = view.getUint32(encoder, true); + * + * // Configure encoder with Kitty protocol flags + * const flagsPtr = exports.ghostty_wasm_alloc_u8(); + * view.setUint8(flagsPtr, 0x1F); + * exports.ghostty_key_encoder_setopt(encoder, 5, flagsPtr); + * + * // Allocate output buffer and size pointer + * const bufferSize = 32; + * const bufPtr = exports.ghostty_wasm_alloc_u8_array(bufferSize); + * const writtenPtr = exports.ghostty_wasm_alloc_usize(); + * + * // Encode the key event + * exports.ghostty_key_encoder_encode( + * encoder, eventPtr, bufPtr, bufferSize, writtenPtr + * ); + * + * // Read encoded output + * const bytesWritten = view.getUint32(writtenPtr, true); + * const encoded = new Uint8Array(wasmMemory.buffer, bufPtr, bytesWritten); + * @endcode + * + * @remark The code above is pretty ugly! This is the lowest level interface + * to the libghostty-vt Wasm module. In practice, this should be wrapped + * in a higher-level API that abstracts away all this. + * + * @{ + */ + +/** + * Allocate an opaque pointer. This can be used for any opaque pointer + * types such as GhosttyKeyEncoder, GhosttyKeyEvent, etc. + * + * @return Pointer to allocated opaque pointer, or NULL if allocation failed + * @ingroup wasm + */ +void** ghostty_wasm_alloc_opaque(void); + +/** + * Free an opaque pointer allocated by ghostty_wasm_alloc_opaque(). + * + * @param ptr Pointer to free, or NULL (NULL is safely ignored) + * @ingroup wasm + */ +void ghostty_wasm_free_opaque(void **ptr); + +/** + * Allocate an array of uint8_t values. + * + * @param len Number of uint8_t elements to allocate + * @return Pointer to allocated array, or NULL if allocation failed + * @ingroup wasm + */ +uint8_t* ghostty_wasm_alloc_u8_array(size_t len); + +/** + * Free an array allocated by ghostty_wasm_alloc_u8_array(). + * + * @param ptr Pointer to the array to free, or NULL (NULL is safely ignored) + * @param len Length of the array (must match the length passed to alloc) + * @ingroup wasm + */ +void ghostty_wasm_free_u8_array(uint8_t *ptr, size_t len); + +/** + * Allocate an array of uint16_t values. + * + * @param len Number of uint16_t elements to allocate + * @return Pointer to allocated array, or NULL if allocation failed + * @ingroup wasm + */ +uint16_t* ghostty_wasm_alloc_u16_array(size_t len); + +/** + * Free an array allocated by ghostty_wasm_alloc_u16_array(). + * + * @param ptr Pointer to the array to free, or NULL (NULL is safely ignored) + * @param len Length of the array (must match the length passed to alloc) + * @ingroup wasm + */ +void ghostty_wasm_free_u16_array(uint16_t *ptr, size_t len); + +/** + * Allocate a single uint8_t value. + * + * @return Pointer to allocated uint8_t, or NULL if allocation failed + * @ingroup wasm + */ +uint8_t* ghostty_wasm_alloc_u8(void); + +/** + * Free a uint8_t allocated by ghostty_wasm_alloc_u8(). + * + * @param ptr Pointer to free, or NULL (NULL is safely ignored) + * @ingroup wasm + */ +void ghostty_wasm_free_u8(uint8_t *ptr); + +/** + * Allocate a single size_t value. + * + * @return Pointer to allocated size_t, or NULL if allocation failed + * @ingroup wasm + */ +size_t* ghostty_wasm_alloc_usize(void); + +/** + * Free a size_t allocated by ghostty_wasm_alloc_usize(). + * + * @param ptr Pointer to free, or NULL (NULL is safely ignored) + * @ingroup wasm + */ +void ghostty_wasm_free_usize(size_t *ptr); + +/** @} */ + +#endif /* __wasm__ */ + +#endif /* GHOSTTY_VT_WASM_H */ diff --git a/apps/mobile/modules/t3-terminal/Vendor/libghostty/GhosttyKit.xcframework/ios-arm64-simulator/Headers/module.modulemap b/apps/mobile/modules/t3-terminal/Vendor/libghostty/GhosttyKit.xcframework/ios-arm64-simulator/Headers/module.modulemap new file mode 100644 index 0000000000..8961f5c04b --- /dev/null +++ b/apps/mobile/modules/t3-terminal/Vendor/libghostty/GhosttyKit.xcframework/ios-arm64-simulator/Headers/module.modulemap @@ -0,0 +1,7 @@ +// This makes Ghostty available to the XCode build for the macOS app. +// We append "Kit" to it not to be cute, but because targets have to have +// unique names and we use Ghostty for other things. +module GhosttyKit { + umbrella header "ghostty.h" + export * +} diff --git a/apps/mobile/modules/t3-terminal/Vendor/libghostty/GhosttyKit.xcframework/ios-arm64-simulator/libghostty-fat.a b/apps/mobile/modules/t3-terminal/Vendor/libghostty/GhosttyKit.xcframework/ios-arm64-simulator/libghostty-fat.a new file mode 100644 index 0000000000..ecd5a2016b Binary files /dev/null and b/apps/mobile/modules/t3-terminal/Vendor/libghostty/GhosttyKit.xcframework/ios-arm64-simulator/libghostty-fat.a differ diff --git a/apps/mobile/modules/t3-terminal/Vendor/libghostty/GhosttyKit.xcframework/ios-arm64/Headers/ghostty.h b/apps/mobile/modules/t3-terminal/Vendor/libghostty/GhosttyKit.xcframework/ios-arm64/Headers/ghostty.h new file mode 100644 index 0000000000..08b88d595b --- /dev/null +++ b/apps/mobile/modules/t3-terminal/Vendor/libghostty/GhosttyKit.xcframework/ios-arm64/Headers/ghostty.h @@ -0,0 +1,1187 @@ +// Ghostty embedding API. The documentation for the embedding API is +// only within the Zig source files that define the implementations. This +// isn't meant to be a general purpose embedding API (yet) so there hasn't +// been documentation or example work beyond that. +// +// The only consumer of this API is the macOS app, but the API is built to +// be more general purpose. +#ifndef GHOSTTY_H +#define GHOSTTY_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include +#include +#include + +//------------------------------------------------------------------- +// Macros + +#define GHOSTTY_SUCCESS 0 + +//------------------------------------------------------------------- +// Types + +// Opaque types +typedef void* ghostty_app_t; +typedef void* ghostty_config_t; +typedef void* ghostty_surface_t; +typedef void* ghostty_inspector_t; + +// All the types below are fully defined and must be kept in sync with +// their Zig counterparts. Any changes to these types MUST have an associated +// Zig change. +typedef enum { + GHOSTTY_PLATFORM_INVALID, + GHOSTTY_PLATFORM_MACOS, + GHOSTTY_PLATFORM_IOS, +} ghostty_platform_e; + +// Callback for custom I/O write handler. +typedef void (*ghostty_surface_write_fn)(void* userdata, + const uint8_t* data, + size_t len); + +typedef enum { + GHOSTTY_CLIPBOARD_STANDARD, + GHOSTTY_CLIPBOARD_SELECTION, +} ghostty_clipboard_e; + +typedef struct { + const char *mime; + const char *data; +} ghostty_clipboard_content_s; + +typedef enum { + GHOSTTY_CLIPBOARD_REQUEST_PASTE, + GHOSTTY_CLIPBOARD_REQUEST_OSC_52_READ, + GHOSTTY_CLIPBOARD_REQUEST_OSC_52_WRITE, +} ghostty_clipboard_request_e; + +typedef enum { + GHOSTTY_MOUSE_RELEASE, + GHOSTTY_MOUSE_PRESS, +} ghostty_input_mouse_state_e; + +typedef enum { + GHOSTTY_MOUSE_UNKNOWN, + GHOSTTY_MOUSE_LEFT, + GHOSTTY_MOUSE_RIGHT, + GHOSTTY_MOUSE_MIDDLE, + GHOSTTY_MOUSE_FOUR, + GHOSTTY_MOUSE_FIVE, + GHOSTTY_MOUSE_SIX, + GHOSTTY_MOUSE_SEVEN, + GHOSTTY_MOUSE_EIGHT, + GHOSTTY_MOUSE_NINE, + GHOSTTY_MOUSE_TEN, + GHOSTTY_MOUSE_ELEVEN, +} ghostty_input_mouse_button_e; + +typedef enum { + GHOSTTY_MOUSE_MOMENTUM_NONE, + GHOSTTY_MOUSE_MOMENTUM_BEGAN, + GHOSTTY_MOUSE_MOMENTUM_STATIONARY, + GHOSTTY_MOUSE_MOMENTUM_CHANGED, + GHOSTTY_MOUSE_MOMENTUM_ENDED, + GHOSTTY_MOUSE_MOMENTUM_CANCELLED, + GHOSTTY_MOUSE_MOMENTUM_MAY_BEGIN, +} ghostty_input_mouse_momentum_e; + +typedef enum { + GHOSTTY_COLOR_SCHEME_LIGHT = 0, + GHOSTTY_COLOR_SCHEME_DARK = 1, +} ghostty_color_scheme_e; + +// This is a packed struct (see src/input/mouse.zig) but the C standard +// afaik doesn't let us reliably define packed structs so we build it up +// from scratch. +typedef int ghostty_input_scroll_mods_t; + +typedef enum { + GHOSTTY_MODS_NONE = 0, + GHOSTTY_MODS_SHIFT = 1 << 0, + GHOSTTY_MODS_CTRL = 1 << 1, + GHOSTTY_MODS_ALT = 1 << 2, + GHOSTTY_MODS_SUPER = 1 << 3, + GHOSTTY_MODS_CAPS = 1 << 4, + GHOSTTY_MODS_NUM = 1 << 5, + GHOSTTY_MODS_SHIFT_RIGHT = 1 << 6, + GHOSTTY_MODS_CTRL_RIGHT = 1 << 7, + GHOSTTY_MODS_ALT_RIGHT = 1 << 8, + GHOSTTY_MODS_SUPER_RIGHT = 1 << 9, +} ghostty_input_mods_e; + +typedef enum { + GHOSTTY_BINDING_FLAGS_CONSUMED = 1 << 0, + GHOSTTY_BINDING_FLAGS_ALL = 1 << 1, + GHOSTTY_BINDING_FLAGS_GLOBAL = 1 << 2, + GHOSTTY_BINDING_FLAGS_PERFORMABLE = 1 << 3, +} ghostty_binding_flags_e; + +typedef enum { + GHOSTTY_ACTION_RELEASE, + GHOSTTY_ACTION_PRESS, + GHOSTTY_ACTION_REPEAT, +} ghostty_input_action_e; + +// Based on: https://www.w3.org/TR/uievents-code/ +typedef enum { + GHOSTTY_KEY_UNIDENTIFIED, + + // "Writing System Keys" § 3.1.1 + GHOSTTY_KEY_BACKQUOTE, + GHOSTTY_KEY_BACKSLASH, + GHOSTTY_KEY_BRACKET_LEFT, + GHOSTTY_KEY_BRACKET_RIGHT, + GHOSTTY_KEY_COMMA, + GHOSTTY_KEY_DIGIT_0, + GHOSTTY_KEY_DIGIT_1, + GHOSTTY_KEY_DIGIT_2, + GHOSTTY_KEY_DIGIT_3, + GHOSTTY_KEY_DIGIT_4, + GHOSTTY_KEY_DIGIT_5, + GHOSTTY_KEY_DIGIT_6, + GHOSTTY_KEY_DIGIT_7, + GHOSTTY_KEY_DIGIT_8, + GHOSTTY_KEY_DIGIT_9, + GHOSTTY_KEY_EQUAL, + GHOSTTY_KEY_INTL_BACKSLASH, + GHOSTTY_KEY_INTL_RO, + GHOSTTY_KEY_INTL_YEN, + GHOSTTY_KEY_A, + GHOSTTY_KEY_B, + GHOSTTY_KEY_C, + GHOSTTY_KEY_D, + GHOSTTY_KEY_E, + GHOSTTY_KEY_F, + GHOSTTY_KEY_G, + GHOSTTY_KEY_H, + GHOSTTY_KEY_I, + GHOSTTY_KEY_J, + GHOSTTY_KEY_K, + GHOSTTY_KEY_L, + GHOSTTY_KEY_M, + GHOSTTY_KEY_N, + GHOSTTY_KEY_O, + GHOSTTY_KEY_P, + GHOSTTY_KEY_Q, + GHOSTTY_KEY_R, + GHOSTTY_KEY_S, + GHOSTTY_KEY_T, + GHOSTTY_KEY_U, + GHOSTTY_KEY_V, + GHOSTTY_KEY_W, + GHOSTTY_KEY_X, + GHOSTTY_KEY_Y, + GHOSTTY_KEY_Z, + GHOSTTY_KEY_MINUS, + GHOSTTY_KEY_PERIOD, + GHOSTTY_KEY_QUOTE, + GHOSTTY_KEY_SEMICOLON, + GHOSTTY_KEY_SLASH, + + // "Functional Keys" § 3.1.2 + GHOSTTY_KEY_ALT_LEFT, + GHOSTTY_KEY_ALT_RIGHT, + GHOSTTY_KEY_BACKSPACE, + GHOSTTY_KEY_CAPS_LOCK, + GHOSTTY_KEY_CONTEXT_MENU, + GHOSTTY_KEY_CONTROL_LEFT, + GHOSTTY_KEY_CONTROL_RIGHT, + GHOSTTY_KEY_ENTER, + GHOSTTY_KEY_META_LEFT, + GHOSTTY_KEY_META_RIGHT, + GHOSTTY_KEY_SHIFT_LEFT, + GHOSTTY_KEY_SHIFT_RIGHT, + GHOSTTY_KEY_SPACE, + GHOSTTY_KEY_TAB, + GHOSTTY_KEY_CONVERT, + GHOSTTY_KEY_KANA_MODE, + GHOSTTY_KEY_NON_CONVERT, + + // "Control Pad Section" § 3.2 + GHOSTTY_KEY_DELETE, + GHOSTTY_KEY_END, + GHOSTTY_KEY_HELP, + GHOSTTY_KEY_HOME, + GHOSTTY_KEY_INSERT, + GHOSTTY_KEY_PAGE_DOWN, + GHOSTTY_KEY_PAGE_UP, + + // "Arrow Pad Section" § 3.3 + GHOSTTY_KEY_ARROW_DOWN, + GHOSTTY_KEY_ARROW_LEFT, + GHOSTTY_KEY_ARROW_RIGHT, + GHOSTTY_KEY_ARROW_UP, + + // "Numpad Section" § 3.4 + GHOSTTY_KEY_NUM_LOCK, + GHOSTTY_KEY_NUMPAD_0, + GHOSTTY_KEY_NUMPAD_1, + GHOSTTY_KEY_NUMPAD_2, + GHOSTTY_KEY_NUMPAD_3, + GHOSTTY_KEY_NUMPAD_4, + GHOSTTY_KEY_NUMPAD_5, + GHOSTTY_KEY_NUMPAD_6, + GHOSTTY_KEY_NUMPAD_7, + GHOSTTY_KEY_NUMPAD_8, + GHOSTTY_KEY_NUMPAD_9, + GHOSTTY_KEY_NUMPAD_ADD, + GHOSTTY_KEY_NUMPAD_BACKSPACE, + GHOSTTY_KEY_NUMPAD_CLEAR, + GHOSTTY_KEY_NUMPAD_CLEAR_ENTRY, + GHOSTTY_KEY_NUMPAD_COMMA, + GHOSTTY_KEY_NUMPAD_DECIMAL, + GHOSTTY_KEY_NUMPAD_DIVIDE, + GHOSTTY_KEY_NUMPAD_ENTER, + GHOSTTY_KEY_NUMPAD_EQUAL, + GHOSTTY_KEY_NUMPAD_MEMORY_ADD, + GHOSTTY_KEY_NUMPAD_MEMORY_CLEAR, + GHOSTTY_KEY_NUMPAD_MEMORY_RECALL, + GHOSTTY_KEY_NUMPAD_MEMORY_STORE, + GHOSTTY_KEY_NUMPAD_MEMORY_SUBTRACT, + GHOSTTY_KEY_NUMPAD_MULTIPLY, + GHOSTTY_KEY_NUMPAD_PAREN_LEFT, + GHOSTTY_KEY_NUMPAD_PAREN_RIGHT, + GHOSTTY_KEY_NUMPAD_SUBTRACT, + GHOSTTY_KEY_NUMPAD_SEPARATOR, + GHOSTTY_KEY_NUMPAD_UP, + GHOSTTY_KEY_NUMPAD_DOWN, + GHOSTTY_KEY_NUMPAD_RIGHT, + GHOSTTY_KEY_NUMPAD_LEFT, + GHOSTTY_KEY_NUMPAD_BEGIN, + GHOSTTY_KEY_NUMPAD_HOME, + GHOSTTY_KEY_NUMPAD_END, + GHOSTTY_KEY_NUMPAD_INSERT, + GHOSTTY_KEY_NUMPAD_DELETE, + GHOSTTY_KEY_NUMPAD_PAGE_UP, + GHOSTTY_KEY_NUMPAD_PAGE_DOWN, + + // "Function Section" § 3.5 + GHOSTTY_KEY_ESCAPE, + GHOSTTY_KEY_F1, + GHOSTTY_KEY_F2, + GHOSTTY_KEY_F3, + GHOSTTY_KEY_F4, + GHOSTTY_KEY_F5, + GHOSTTY_KEY_F6, + GHOSTTY_KEY_F7, + GHOSTTY_KEY_F8, + GHOSTTY_KEY_F9, + GHOSTTY_KEY_F10, + GHOSTTY_KEY_F11, + GHOSTTY_KEY_F12, + GHOSTTY_KEY_F13, + GHOSTTY_KEY_F14, + GHOSTTY_KEY_F15, + GHOSTTY_KEY_F16, + GHOSTTY_KEY_F17, + GHOSTTY_KEY_F18, + GHOSTTY_KEY_F19, + GHOSTTY_KEY_F20, + GHOSTTY_KEY_F21, + GHOSTTY_KEY_F22, + GHOSTTY_KEY_F23, + GHOSTTY_KEY_F24, + GHOSTTY_KEY_F25, + GHOSTTY_KEY_FN, + GHOSTTY_KEY_FN_LOCK, + GHOSTTY_KEY_PRINT_SCREEN, + GHOSTTY_KEY_SCROLL_LOCK, + GHOSTTY_KEY_PAUSE, + + // "Media Keys" § 3.6 + GHOSTTY_KEY_BROWSER_BACK, + GHOSTTY_KEY_BROWSER_FAVORITES, + GHOSTTY_KEY_BROWSER_FORWARD, + GHOSTTY_KEY_BROWSER_HOME, + GHOSTTY_KEY_BROWSER_REFRESH, + GHOSTTY_KEY_BROWSER_SEARCH, + GHOSTTY_KEY_BROWSER_STOP, + GHOSTTY_KEY_EJECT, + GHOSTTY_KEY_LAUNCH_APP_1, + GHOSTTY_KEY_LAUNCH_APP_2, + GHOSTTY_KEY_LAUNCH_MAIL, + GHOSTTY_KEY_MEDIA_PLAY_PAUSE, + GHOSTTY_KEY_MEDIA_SELECT, + GHOSTTY_KEY_MEDIA_STOP, + GHOSTTY_KEY_MEDIA_TRACK_NEXT, + GHOSTTY_KEY_MEDIA_TRACK_PREVIOUS, + GHOSTTY_KEY_POWER, + GHOSTTY_KEY_SLEEP, + GHOSTTY_KEY_AUDIO_VOLUME_DOWN, + GHOSTTY_KEY_AUDIO_VOLUME_MUTE, + GHOSTTY_KEY_AUDIO_VOLUME_UP, + GHOSTTY_KEY_WAKE_UP, + + // "Legacy, Non-standard, and Special Keys" § 3.7 + GHOSTTY_KEY_COPY, + GHOSTTY_KEY_CUT, + GHOSTTY_KEY_PASTE, +} ghostty_input_key_e; + +typedef struct { + ghostty_input_action_e action; + ghostty_input_mods_e mods; + ghostty_input_mods_e consumed_mods; + uint32_t keycode; + const char* text; + uint32_t unshifted_codepoint; + bool composing; +} ghostty_input_key_s; + +typedef enum { + GHOSTTY_TRIGGER_PHYSICAL, + GHOSTTY_TRIGGER_UNICODE, + GHOSTTY_TRIGGER_CATCH_ALL, +} ghostty_input_trigger_tag_e; + +typedef union { + ghostty_input_key_e translated; + ghostty_input_key_e physical; + uint32_t unicode; + // catch_all has no payload +} ghostty_input_trigger_key_u; + +typedef struct { + ghostty_input_trigger_tag_e tag; + ghostty_input_trigger_key_u key; + ghostty_input_mods_e mods; +} ghostty_input_trigger_s; + +typedef struct { + const char* action_key; + const char* action; + const char* title; + const char* description; +} ghostty_command_s; + +typedef enum { + GHOSTTY_BUILD_MODE_DEBUG, + GHOSTTY_BUILD_MODE_RELEASE_SAFE, + GHOSTTY_BUILD_MODE_RELEASE_FAST, + GHOSTTY_BUILD_MODE_RELEASE_SMALL, +} ghostty_build_mode_e; + +typedef struct { + ghostty_build_mode_e build_mode; + const char* version; + uintptr_t version_len; +} ghostty_info_s; + +typedef struct { + const char* message; +} ghostty_diagnostic_s; + +typedef struct { + const char* ptr; + uintptr_t len; + bool sentinel; +} ghostty_string_s; + +typedef struct { + double tl_px_x; + double tl_px_y; + uint32_t offset_start; + uint32_t offset_len; + const char* text; + uintptr_t text_len; +} ghostty_text_s; + +typedef enum { + GHOSTTY_POINT_ACTIVE, + GHOSTTY_POINT_VIEWPORT, + GHOSTTY_POINT_SCREEN, + GHOSTTY_POINT_SURFACE, +} ghostty_point_tag_e; + +typedef enum { + GHOSTTY_POINT_COORD_EXACT, + GHOSTTY_POINT_COORD_TOP_LEFT, + GHOSTTY_POINT_COORD_BOTTOM_RIGHT, +} ghostty_point_coord_e; + +typedef struct { + ghostty_point_tag_e tag; + ghostty_point_coord_e coord; + uint32_t x; + uint32_t y; +} ghostty_point_s; + +typedef struct { + ghostty_point_s top_left; + ghostty_point_s bottom_right; + bool rectangle; +} ghostty_selection_s; + +typedef struct { + const char* key; + const char* value; +} ghostty_env_var_s; + +typedef struct { + void* nsview; +} ghostty_platform_macos_s; + +typedef struct { + void* uiview; +} ghostty_platform_ios_s; + +typedef union { + ghostty_platform_macos_s macos; + ghostty_platform_ios_s ios; +} ghostty_platform_u; + +typedef enum { + GHOSTTY_SURFACE_CONTEXT_WINDOW = 0, + GHOSTTY_SURFACE_CONTEXT_TAB = 1, + GHOSTTY_SURFACE_CONTEXT_SPLIT = 2, +} ghostty_surface_context_e; + +typedef struct { + ghostty_platform_e platform_tag; + ghostty_platform_u platform; + void* userdata; + double scale_factor; + float font_size; + const char* working_directory; + const char* command; + ghostty_env_var_s* env_vars; + size_t env_var_count; + const char* initial_input; + bool wait_after_command; + ghostty_surface_context_e context; + bool use_custom_io; +} ghostty_surface_config_s; + +typedef struct { + uint16_t columns; + uint16_t rows; + uint32_t width_px; + uint32_t height_px; + uint32_t cell_width_px; + uint32_t cell_height_px; +} ghostty_surface_size_s; + +// Config types + +// config.Path +typedef struct { + const char* path; + bool optional; +} ghostty_config_path_s; + +// config.Color +typedef struct { + uint8_t r; + uint8_t g; + uint8_t b; +} ghostty_config_color_s; + +// config.ColorList +typedef struct { + const ghostty_config_color_s* colors; + size_t len; +} ghostty_config_color_list_s; + +// config.RepeatableCommand +typedef struct { + const ghostty_command_s* commands; + size_t len; +} ghostty_config_command_list_s; + +// config.Palette +typedef struct { + ghostty_config_color_s colors[256]; +} ghostty_config_palette_s; + +// config.QuickTerminalSize +typedef enum { + GHOSTTY_QUICK_TERMINAL_SIZE_NONE, + GHOSTTY_QUICK_TERMINAL_SIZE_PERCENTAGE, + GHOSTTY_QUICK_TERMINAL_SIZE_PIXELS, +} ghostty_quick_terminal_size_tag_e; + +typedef union { + float percentage; + uint32_t pixels; +} ghostty_quick_terminal_size_value_u; + +typedef struct { + ghostty_quick_terminal_size_tag_e tag; + ghostty_quick_terminal_size_value_u value; +} ghostty_quick_terminal_size_s; + +typedef struct { + ghostty_quick_terminal_size_s primary; + ghostty_quick_terminal_size_s secondary; +} ghostty_config_quick_terminal_size_s; + +// config.Fullscreen +typedef enum { + GHOSTTY_CONFIG_FULLSCREEN_FALSE, + GHOSTTY_CONFIG_FULLSCREEN_TRUE, + GHOSTTY_CONFIG_FULLSCREEN_NON_NATIVE, + GHOSTTY_CONFIG_FULLSCREEN_NON_NATIVE_VISIBLE_MENU, + GHOSTTY_CONFIG_FULLSCREEN_NON_NATIVE_PADDED_NOTCH, +} ghostty_config_fullscreen_e; + +// apprt.Target.Key +typedef enum { + GHOSTTY_TARGET_APP, + GHOSTTY_TARGET_SURFACE, +} ghostty_target_tag_e; + +typedef union { + ghostty_surface_t surface; +} ghostty_target_u; + +typedef struct { + ghostty_target_tag_e tag; + ghostty_target_u target; +} ghostty_target_s; + +// apprt.action.SplitDirection +typedef enum { + GHOSTTY_SPLIT_DIRECTION_RIGHT, + GHOSTTY_SPLIT_DIRECTION_DOWN, + GHOSTTY_SPLIT_DIRECTION_LEFT, + GHOSTTY_SPLIT_DIRECTION_UP, +} ghostty_action_split_direction_e; + +// apprt.action.GotoSplit +typedef enum { + GHOSTTY_GOTO_SPLIT_PREVIOUS, + GHOSTTY_GOTO_SPLIT_NEXT, + GHOSTTY_GOTO_SPLIT_UP, + GHOSTTY_GOTO_SPLIT_LEFT, + GHOSTTY_GOTO_SPLIT_DOWN, + GHOSTTY_GOTO_SPLIT_RIGHT, +} ghostty_action_goto_split_e; + +// apprt.action.GotoWindow +typedef enum { + GHOSTTY_GOTO_WINDOW_PREVIOUS, + GHOSTTY_GOTO_WINDOW_NEXT, +} ghostty_action_goto_window_e; + +// apprt.action.ResizeSplit.Direction +typedef enum { + GHOSTTY_RESIZE_SPLIT_UP, + GHOSTTY_RESIZE_SPLIT_DOWN, + GHOSTTY_RESIZE_SPLIT_LEFT, + GHOSTTY_RESIZE_SPLIT_RIGHT, +} ghostty_action_resize_split_direction_e; + +// apprt.action.ResizeSplit +typedef struct { + uint16_t amount; + ghostty_action_resize_split_direction_e direction; +} ghostty_action_resize_split_s; + +// apprt.action.MoveTab +typedef struct { + ssize_t amount; +} ghostty_action_move_tab_s; + +// apprt.action.GotoTab +typedef enum { + GHOSTTY_GOTO_TAB_PREVIOUS = -1, + GHOSTTY_GOTO_TAB_NEXT = -2, + GHOSTTY_GOTO_TAB_LAST = -3, +} ghostty_action_goto_tab_e; + +// apprt.action.Fullscreen +typedef enum { + GHOSTTY_FULLSCREEN_NATIVE, + GHOSTTY_FULLSCREEN_MACOS_NON_NATIVE, + GHOSTTY_FULLSCREEN_MACOS_NON_NATIVE_VISIBLE_MENU, + GHOSTTY_FULLSCREEN_MACOS_NON_NATIVE_PADDED_NOTCH, +} ghostty_action_fullscreen_e; + +// apprt.action.FloatWindow +typedef enum { + GHOSTTY_FLOAT_WINDOW_ON, + GHOSTTY_FLOAT_WINDOW_OFF, + GHOSTTY_FLOAT_WINDOW_TOGGLE, +} ghostty_action_float_window_e; + +// apprt.action.SecureInput +typedef enum { + GHOSTTY_SECURE_INPUT_ON, + GHOSTTY_SECURE_INPUT_OFF, + GHOSTTY_SECURE_INPUT_TOGGLE, +} ghostty_action_secure_input_e; + +// apprt.action.Inspector +typedef enum { + GHOSTTY_INSPECTOR_TOGGLE, + GHOSTTY_INSPECTOR_SHOW, + GHOSTTY_INSPECTOR_HIDE, +} ghostty_action_inspector_e; + +// apprt.action.QuitTimer +typedef enum { + GHOSTTY_QUIT_TIMER_START, + GHOSTTY_QUIT_TIMER_STOP, +} ghostty_action_quit_timer_e; + +// apprt.action.Readonly +typedef enum { + GHOSTTY_READONLY_OFF, + GHOSTTY_READONLY_ON, +} ghostty_action_readonly_e; + +// apprt.action.DesktopNotification.C +typedef struct { + const char* title; + const char* body; +} ghostty_action_desktop_notification_s; + +// apprt.action.SetTitle.C +typedef struct { + const char* title; +} ghostty_action_set_title_s; + +// apprt.action.PromptTitle +typedef enum { + GHOSTTY_PROMPT_TITLE_SURFACE, + GHOSTTY_PROMPT_TITLE_TAB, +} ghostty_action_prompt_title_e; + +// apprt.action.Pwd.C +typedef struct { + const char* pwd; +} ghostty_action_pwd_s; + +// terminal.MouseShape +typedef enum { + GHOSTTY_MOUSE_SHAPE_DEFAULT, + GHOSTTY_MOUSE_SHAPE_CONTEXT_MENU, + GHOSTTY_MOUSE_SHAPE_HELP, + GHOSTTY_MOUSE_SHAPE_POINTER, + GHOSTTY_MOUSE_SHAPE_PROGRESS, + GHOSTTY_MOUSE_SHAPE_WAIT, + GHOSTTY_MOUSE_SHAPE_CELL, + GHOSTTY_MOUSE_SHAPE_CROSSHAIR, + GHOSTTY_MOUSE_SHAPE_TEXT, + GHOSTTY_MOUSE_SHAPE_VERTICAL_TEXT, + GHOSTTY_MOUSE_SHAPE_ALIAS, + GHOSTTY_MOUSE_SHAPE_COPY, + GHOSTTY_MOUSE_SHAPE_MOVE, + GHOSTTY_MOUSE_SHAPE_NO_DROP, + GHOSTTY_MOUSE_SHAPE_NOT_ALLOWED, + GHOSTTY_MOUSE_SHAPE_GRAB, + GHOSTTY_MOUSE_SHAPE_GRABBING, + GHOSTTY_MOUSE_SHAPE_ALL_SCROLL, + GHOSTTY_MOUSE_SHAPE_COL_RESIZE, + GHOSTTY_MOUSE_SHAPE_ROW_RESIZE, + GHOSTTY_MOUSE_SHAPE_N_RESIZE, + GHOSTTY_MOUSE_SHAPE_E_RESIZE, + GHOSTTY_MOUSE_SHAPE_S_RESIZE, + GHOSTTY_MOUSE_SHAPE_W_RESIZE, + GHOSTTY_MOUSE_SHAPE_NE_RESIZE, + GHOSTTY_MOUSE_SHAPE_NW_RESIZE, + GHOSTTY_MOUSE_SHAPE_SE_RESIZE, + GHOSTTY_MOUSE_SHAPE_SW_RESIZE, + GHOSTTY_MOUSE_SHAPE_EW_RESIZE, + GHOSTTY_MOUSE_SHAPE_NS_RESIZE, + GHOSTTY_MOUSE_SHAPE_NESW_RESIZE, + GHOSTTY_MOUSE_SHAPE_NWSE_RESIZE, + GHOSTTY_MOUSE_SHAPE_ZOOM_IN, + GHOSTTY_MOUSE_SHAPE_ZOOM_OUT, +} ghostty_action_mouse_shape_e; + +// apprt.action.MouseVisibility +typedef enum { + GHOSTTY_MOUSE_VISIBLE, + GHOSTTY_MOUSE_HIDDEN, +} ghostty_action_mouse_visibility_e; + +// apprt.action.MouseOverLink +typedef struct { + const char* url; + size_t len; +} ghostty_action_mouse_over_link_s; + +// apprt.action.SizeLimit +typedef struct { + uint32_t min_width; + uint32_t min_height; + uint32_t max_width; + uint32_t max_height; +} ghostty_action_size_limit_s; + +// apprt.action.InitialSize +typedef struct { + uint32_t width; + uint32_t height; +} ghostty_action_initial_size_s; + +// apprt.action.CellSize +typedef struct { + uint32_t width; + uint32_t height; +} ghostty_action_cell_size_s; + +// renderer.Health +typedef enum { + GHOSTTY_RENDERER_HEALTH_HEALTHY, + GHOSTTY_RENDERER_HEALTH_UNHEALTHY, +} ghostty_action_renderer_health_e; + +// apprt.action.KeySequence +typedef struct { + bool active; + ghostty_input_trigger_s trigger; +} ghostty_action_key_sequence_s; + +// apprt.action.KeyTable.Tag +typedef enum { + GHOSTTY_KEY_TABLE_ACTIVATE, + GHOSTTY_KEY_TABLE_DEACTIVATE, + GHOSTTY_KEY_TABLE_DEACTIVATE_ALL, +} ghostty_action_key_table_tag_e; + +// apprt.action.KeyTable.CValue +typedef union { + struct { + const char *name; + size_t len; + } activate; +} ghostty_action_key_table_u; + +// apprt.action.KeyTable.C +typedef struct { + ghostty_action_key_table_tag_e tag; + ghostty_action_key_table_u value; +} ghostty_action_key_table_s; + +// apprt.action.ColorKind +typedef enum { + GHOSTTY_ACTION_COLOR_KIND_FOREGROUND = -1, + GHOSTTY_ACTION_COLOR_KIND_BACKGROUND = -2, + GHOSTTY_ACTION_COLOR_KIND_CURSOR = -3, +} ghostty_action_color_kind_e; + +// apprt.action.ColorChange +typedef struct { + ghostty_action_color_kind_e kind; + uint8_t r; + uint8_t g; + uint8_t b; +} ghostty_action_color_change_s; + +// apprt.action.ConfigChange +typedef struct { + ghostty_config_t config; +} ghostty_action_config_change_s; + +// apprt.action.ReloadConfig +typedef struct { + bool soft; +} ghostty_action_reload_config_s; + +// apprt.action.OpenUrlKind +typedef enum { + GHOSTTY_ACTION_OPEN_URL_KIND_UNKNOWN, + GHOSTTY_ACTION_OPEN_URL_KIND_TEXT, + GHOSTTY_ACTION_OPEN_URL_KIND_HTML, +} ghostty_action_open_url_kind_e; + +// apprt.action.OpenUrl.C +typedef struct { + ghostty_action_open_url_kind_e kind; + const char* url; + uintptr_t len; +} ghostty_action_open_url_s; + +// apprt.action.CloseTabMode +typedef enum { + GHOSTTY_ACTION_CLOSE_TAB_MODE_THIS, + GHOSTTY_ACTION_CLOSE_TAB_MODE_OTHER, + GHOSTTY_ACTION_CLOSE_TAB_MODE_RIGHT, +} ghostty_action_close_tab_mode_e; + +// apprt.surface.Message.ChildExited +typedef struct { + uint32_t exit_code; + uint64_t timetime_ms; +} ghostty_surface_message_childexited_s; + +// terminal.osc.Command.ProgressReport.State +typedef enum { + GHOSTTY_PROGRESS_STATE_REMOVE, + GHOSTTY_PROGRESS_STATE_SET, + GHOSTTY_PROGRESS_STATE_ERROR, + GHOSTTY_PROGRESS_STATE_INDETERMINATE, + GHOSTTY_PROGRESS_STATE_PAUSE, +} ghostty_action_progress_report_state_e; + +// terminal.osc.Command.ProgressReport.C +typedef struct { + ghostty_action_progress_report_state_e state; + // -1 if no progress was reported, otherwise 0-100 indicating percent + // completeness. + int8_t progress; +} ghostty_action_progress_report_s; + +// apprt.action.CommandFinished.C +typedef struct { + // -1 if no exit code was reported, otherwise 0-255 + int16_t exit_code; + // number of nanoseconds that command was running for + uint64_t duration; +} ghostty_action_command_finished_s; + +// apprt.action.StartSearch.C +typedef struct { + const char* needle; +} ghostty_action_start_search_s; + +// apprt.action.SearchTotal +typedef struct { + ssize_t total; +} ghostty_action_search_total_s; + +// apprt.action.SearchSelected +typedef struct { + ssize_t selected; +} ghostty_action_search_selected_s; + +// terminal.Scrollbar +typedef struct { + uint64_t total; + uint64_t offset; + uint64_t len; +} ghostty_action_scrollbar_s; + +// apprt.Action.Key +typedef enum { + GHOSTTY_ACTION_QUIT, + GHOSTTY_ACTION_NEW_WINDOW, + GHOSTTY_ACTION_NEW_TAB, + GHOSTTY_ACTION_CLOSE_TAB, + GHOSTTY_ACTION_NEW_SPLIT, + GHOSTTY_ACTION_CLOSE_ALL_WINDOWS, + GHOSTTY_ACTION_TOGGLE_MAXIMIZE, + GHOSTTY_ACTION_TOGGLE_FULLSCREEN, + GHOSTTY_ACTION_TOGGLE_TAB_OVERVIEW, + GHOSTTY_ACTION_TOGGLE_WINDOW_DECORATIONS, + GHOSTTY_ACTION_TOGGLE_QUICK_TERMINAL, + GHOSTTY_ACTION_TOGGLE_COMMAND_PALETTE, + GHOSTTY_ACTION_TOGGLE_VISIBILITY, + GHOSTTY_ACTION_TOGGLE_BACKGROUND_OPACITY, + GHOSTTY_ACTION_MOVE_TAB, + GHOSTTY_ACTION_GOTO_TAB, + GHOSTTY_ACTION_GOTO_SPLIT, + GHOSTTY_ACTION_GOTO_WINDOW, + GHOSTTY_ACTION_RESIZE_SPLIT, + GHOSTTY_ACTION_EQUALIZE_SPLITS, + GHOSTTY_ACTION_TOGGLE_SPLIT_ZOOM, + GHOSTTY_ACTION_PRESENT_TERMINAL, + GHOSTTY_ACTION_SIZE_LIMIT, + GHOSTTY_ACTION_RESET_WINDOW_SIZE, + GHOSTTY_ACTION_INITIAL_SIZE, + GHOSTTY_ACTION_CELL_SIZE, + GHOSTTY_ACTION_SCROLLBAR, + GHOSTTY_ACTION_RENDER, + GHOSTTY_ACTION_INSPECTOR, + GHOSTTY_ACTION_SHOW_GTK_INSPECTOR, + GHOSTTY_ACTION_RENDER_INSPECTOR, + GHOSTTY_ACTION_DESKTOP_NOTIFICATION, + GHOSTTY_ACTION_SET_TITLE, + GHOSTTY_ACTION_PROMPT_TITLE, + GHOSTTY_ACTION_PWD, + GHOSTTY_ACTION_MOUSE_SHAPE, + GHOSTTY_ACTION_MOUSE_VISIBILITY, + GHOSTTY_ACTION_MOUSE_OVER_LINK, + GHOSTTY_ACTION_RENDERER_HEALTH, + GHOSTTY_ACTION_OPEN_CONFIG, + GHOSTTY_ACTION_QUIT_TIMER, + GHOSTTY_ACTION_FLOAT_WINDOW, + GHOSTTY_ACTION_SECURE_INPUT, + GHOSTTY_ACTION_KEY_SEQUENCE, + GHOSTTY_ACTION_KEY_TABLE, + GHOSTTY_ACTION_COLOR_CHANGE, + GHOSTTY_ACTION_RELOAD_CONFIG, + GHOSTTY_ACTION_CONFIG_CHANGE, + GHOSTTY_ACTION_CLOSE_WINDOW, + GHOSTTY_ACTION_RING_BELL, + GHOSTTY_ACTION_UNDO, + GHOSTTY_ACTION_REDO, + GHOSTTY_ACTION_CHECK_FOR_UPDATES, + GHOSTTY_ACTION_OPEN_URL, + GHOSTTY_ACTION_SHOW_CHILD_EXITED, + GHOSTTY_ACTION_PROGRESS_REPORT, + GHOSTTY_ACTION_SHOW_ON_SCREEN_KEYBOARD, + GHOSTTY_ACTION_COMMAND_FINISHED, + GHOSTTY_ACTION_START_SEARCH, + GHOSTTY_ACTION_END_SEARCH, + GHOSTTY_ACTION_SEARCH_TOTAL, + GHOSTTY_ACTION_SEARCH_SELECTED, + GHOSTTY_ACTION_READONLY, + GHOSTTY_ACTION_COPY_TITLE_TO_CLIPBOARD, +} ghostty_action_tag_e; + +typedef union { + ghostty_action_split_direction_e new_split; + ghostty_action_fullscreen_e toggle_fullscreen; + ghostty_action_move_tab_s move_tab; + ghostty_action_goto_tab_e goto_tab; + ghostty_action_goto_split_e goto_split; + ghostty_action_goto_window_e goto_window; + ghostty_action_resize_split_s resize_split; + ghostty_action_size_limit_s size_limit; + ghostty_action_initial_size_s initial_size; + ghostty_action_cell_size_s cell_size; + ghostty_action_scrollbar_s scrollbar; + ghostty_action_inspector_e inspector; + ghostty_action_desktop_notification_s desktop_notification; + ghostty_action_set_title_s set_title; + ghostty_action_prompt_title_e prompt_title; + ghostty_action_pwd_s pwd; + ghostty_action_mouse_shape_e mouse_shape; + ghostty_action_mouse_visibility_e mouse_visibility; + ghostty_action_mouse_over_link_s mouse_over_link; + ghostty_action_renderer_health_e renderer_health; + ghostty_action_quit_timer_e quit_timer; + ghostty_action_float_window_e float_window; + ghostty_action_secure_input_e secure_input; + ghostty_action_key_sequence_s key_sequence; + ghostty_action_key_table_s key_table; + ghostty_action_color_change_s color_change; + ghostty_action_reload_config_s reload_config; + ghostty_action_config_change_s config_change; + ghostty_action_open_url_s open_url; + ghostty_action_close_tab_mode_e close_tab_mode; + ghostty_surface_message_childexited_s child_exited; + ghostty_action_progress_report_s progress_report; + ghostty_action_command_finished_s command_finished; + ghostty_action_start_search_s start_search; + ghostty_action_search_total_s search_total; + ghostty_action_search_selected_s search_selected; + ghostty_action_readonly_e readonly; +} ghostty_action_u; + +typedef struct { + ghostty_action_tag_e tag; + ghostty_action_u action; +} ghostty_action_s; + +typedef void (*ghostty_runtime_wakeup_cb)(void*); +typedef void (*ghostty_runtime_read_clipboard_cb)(void*, + ghostty_clipboard_e, + void*); +typedef void (*ghostty_runtime_confirm_read_clipboard_cb)( + void*, + const char*, + void*, + ghostty_clipboard_request_e); +typedef void (*ghostty_runtime_write_clipboard_cb)(void*, + ghostty_clipboard_e, + const ghostty_clipboard_content_s*, + size_t, + bool); +typedef void (*ghostty_runtime_close_surface_cb)(void*, bool); +typedef bool (*ghostty_runtime_action_cb)(ghostty_app_t, + ghostty_target_s, + ghostty_action_s); + +typedef struct { + void* userdata; + bool supports_selection_clipboard; + ghostty_runtime_wakeup_cb wakeup_cb; + ghostty_runtime_action_cb action_cb; + ghostty_runtime_read_clipboard_cb read_clipboard_cb; + ghostty_runtime_confirm_read_clipboard_cb confirm_read_clipboard_cb; + ghostty_runtime_write_clipboard_cb write_clipboard_cb; + ghostty_runtime_close_surface_cb close_surface_cb; +} ghostty_runtime_config_s; + +// apprt.ipc.Target.Key +typedef enum { + GHOSTTY_IPC_TARGET_CLASS, + GHOSTTY_IPC_TARGET_DETECT, +} ghostty_ipc_target_tag_e; + +typedef union { + char *klass; +} ghostty_ipc_target_u; + +typedef struct { + ghostty_ipc_target_tag_e tag; + ghostty_ipc_target_u target; +} chostty_ipc_target_s; + +// apprt.ipc.Action.NewWindow +typedef struct { + // This should be a null terminated list of strings. + const char **arguments; +} ghostty_ipc_action_new_window_s; + +typedef union { + ghostty_ipc_action_new_window_s new_window; +} ghostty_ipc_action_u; + +// apprt.ipc.Action.Key +typedef enum { + GHOSTTY_IPC_ACTION_NEW_WINDOW, +} ghostty_ipc_action_tag_e; + +//------------------------------------------------------------------- +// Published API + +int ghostty_init(uintptr_t, char**); +void ghostty_cli_try_action(void); +ghostty_info_s ghostty_info(void); +const char* ghostty_translate(const char*); +void ghostty_string_free(ghostty_string_s); + +ghostty_config_t ghostty_config_new(); +void ghostty_config_free(ghostty_config_t); +ghostty_config_t ghostty_config_clone(ghostty_config_t); +void ghostty_config_load_cli_args(ghostty_config_t); +void ghostty_config_load_file(ghostty_config_t, const char*); +void ghostty_config_load_default_files(ghostty_config_t); +void ghostty_config_load_recursive_files(ghostty_config_t); +void ghostty_config_finalize(ghostty_config_t); +bool ghostty_config_get(ghostty_config_t, void*, const char*, uintptr_t); +ghostty_input_trigger_s ghostty_config_trigger(ghostty_config_t, + const char*, + uintptr_t); +uint32_t ghostty_config_diagnostics_count(ghostty_config_t); +ghostty_diagnostic_s ghostty_config_get_diagnostic(ghostty_config_t, uint32_t); +ghostty_string_s ghostty_config_open_path(void); + +ghostty_app_t ghostty_app_new(const ghostty_runtime_config_s*, + ghostty_config_t); +void ghostty_app_free(ghostty_app_t); +void ghostty_app_tick(ghostty_app_t); +void* ghostty_app_userdata(ghostty_app_t); +void ghostty_app_set_focus(ghostty_app_t, bool); +bool ghostty_app_key(ghostty_app_t, ghostty_input_key_s); +bool ghostty_app_key_is_binding(ghostty_app_t, ghostty_input_key_s); +void ghostty_app_keyboard_changed(ghostty_app_t); +void ghostty_app_open_config(ghostty_app_t); +void ghostty_app_update_config(ghostty_app_t, ghostty_config_t); +bool ghostty_app_needs_confirm_quit(ghostty_app_t); +bool ghostty_app_has_global_keybinds(ghostty_app_t); +void ghostty_app_set_color_scheme(ghostty_app_t, ghostty_color_scheme_e); + +ghostty_surface_config_s ghostty_surface_config_new(); + +ghostty_surface_t ghostty_surface_new(ghostty_app_t, + const ghostty_surface_config_s*); +void ghostty_surface_free(ghostty_surface_t); +void* ghostty_surface_userdata(ghostty_surface_t); +ghostty_app_t ghostty_surface_app(ghostty_surface_t); +ghostty_surface_config_s ghostty_surface_inherited_config(ghostty_surface_t, ghostty_surface_context_e); +void ghostty_surface_update_config(ghostty_surface_t, ghostty_config_t); +bool ghostty_surface_needs_confirm_quit(ghostty_surface_t); +bool ghostty_surface_process_exited(ghostty_surface_t); +void ghostty_surface_refresh(ghostty_surface_t); +void ghostty_surface_draw(ghostty_surface_t); +// Custom I/O API - feed output into the terminal and receive writes. +void ghostty_surface_feed_data(ghostty_surface_t, const uint8_t*, size_t); +void ghostty_surface_set_write_callback(ghostty_surface_t, + ghostty_surface_write_fn, + void*); +void ghostty_surface_set_content_scale(ghostty_surface_t, double, double); +void ghostty_surface_set_focus(ghostty_surface_t, bool); +void ghostty_surface_set_occlusion(ghostty_surface_t, bool); +void ghostty_surface_set_size(ghostty_surface_t, uint32_t, uint32_t); +ghostty_surface_size_s ghostty_surface_size(ghostty_surface_t); +void ghostty_surface_set_color_scheme(ghostty_surface_t, + ghostty_color_scheme_e); +ghostty_input_mods_e ghostty_surface_key_translation_mods(ghostty_surface_t, + ghostty_input_mods_e); +bool ghostty_surface_key(ghostty_surface_t, ghostty_input_key_s); +bool ghostty_surface_key_is_binding(ghostty_surface_t, + ghostty_input_key_s, + ghostty_binding_flags_e*); +void ghostty_surface_text(ghostty_surface_t, const char*, uintptr_t); +void ghostty_surface_preedit(ghostty_surface_t, const char*, uintptr_t); +bool ghostty_surface_mouse_captured(ghostty_surface_t); +bool ghostty_surface_mouse_button(ghostty_surface_t, + ghostty_input_mouse_state_e, + ghostty_input_mouse_button_e, + ghostty_input_mods_e); +void ghostty_surface_mouse_pos(ghostty_surface_t, + double, + double, + ghostty_input_mods_e); +void ghostty_surface_mouse_scroll(ghostty_surface_t, + double, + double, + ghostty_input_scroll_mods_t); +void ghostty_surface_mouse_pressure(ghostty_surface_t, uint32_t, double); +void ghostty_surface_ime_point(ghostty_surface_t, double*, double*, double*, double*); +void ghostty_surface_request_close(ghostty_surface_t); +void ghostty_surface_split(ghostty_surface_t, ghostty_action_split_direction_e); +void ghostty_surface_split_focus(ghostty_surface_t, + ghostty_action_goto_split_e); +void ghostty_surface_split_resize(ghostty_surface_t, + ghostty_action_resize_split_direction_e, + uint16_t); +void ghostty_surface_split_equalize(ghostty_surface_t); +bool ghostty_surface_binding_action(ghostty_surface_t, const char*, uintptr_t); +void ghostty_surface_complete_clipboard_request(ghostty_surface_t, + const char*, + void*, + bool); +bool ghostty_surface_has_selection(ghostty_surface_t); +bool ghostty_surface_read_selection(ghostty_surface_t, ghostty_text_s*); +bool ghostty_surface_read_text(ghostty_surface_t, + ghostty_selection_s, + ghostty_text_s*); +void ghostty_surface_free_text(ghostty_surface_t, ghostty_text_s*); + +#ifdef __APPLE__ +void ghostty_surface_set_display_id(ghostty_surface_t, uint32_t); +void* ghostty_surface_quicklook_font(ghostty_surface_t); +bool ghostty_surface_quicklook_word(ghostty_surface_t, ghostty_text_s*); +#endif + +ghostty_inspector_t ghostty_surface_inspector(ghostty_surface_t); +void ghostty_inspector_free(ghostty_surface_t); +void ghostty_inspector_set_focus(ghostty_inspector_t, bool); +void ghostty_inspector_set_content_scale(ghostty_inspector_t, double, double); +void ghostty_inspector_set_size(ghostty_inspector_t, uint32_t, uint32_t); +void ghostty_inspector_mouse_button(ghostty_inspector_t, + ghostty_input_mouse_state_e, + ghostty_input_mouse_button_e, + ghostty_input_mods_e); +void ghostty_inspector_mouse_pos(ghostty_inspector_t, double, double); +void ghostty_inspector_mouse_scroll(ghostty_inspector_t, + double, + double, + ghostty_input_scroll_mods_t); +void ghostty_inspector_key(ghostty_inspector_t, + ghostty_input_action_e, + ghostty_input_key_e, + ghostty_input_mods_e); +void ghostty_inspector_text(ghostty_inspector_t, const char*); + +#ifdef __APPLE__ +bool ghostty_inspector_metal_init(ghostty_inspector_t, void*); +void ghostty_inspector_metal_render(ghostty_inspector_t, void*, void*); +bool ghostty_inspector_metal_shutdown(ghostty_inspector_t); +#endif + +// APIs I'd like to get rid of eventually but are still needed for now. +// Don't use these unless you know what you're doing. +void ghostty_set_window_background_blur(ghostty_app_t, void*); + +// Benchmark API, if available. +bool ghostty_benchmark_cli(const char*, const char*); + +#ifdef __cplusplus +} +#endif + +#endif /* GHOSTTY_H */ diff --git a/apps/mobile/modules/t3-terminal/Vendor/libghostty/GhosttyKit.xcframework/ios-arm64/Headers/ghostty/vt.h b/apps/mobile/modules/t3-terminal/Vendor/libghostty/GhosttyKit.xcframework/ios-arm64/Headers/ghostty/vt.h new file mode 100644 index 0000000000..4f8fef88ec --- /dev/null +++ b/apps/mobile/modules/t3-terminal/Vendor/libghostty/GhosttyKit.xcframework/ios-arm64/Headers/ghostty/vt.h @@ -0,0 +1,87 @@ +/** + * @file vt.h + * + * libghostty-vt - Virtual terminal emulator library + * + * This library provides functionality for parsing and handling terminal + * escape sequences as well as maintaining terminal state such as styles, + * cursor position, screen, scrollback, and more. + * + * WARNING: This is an incomplete, work-in-progress API. It is not yet + * stable and is definitely going to change. + */ + +/** + * @mainpage libghostty-vt - Virtual Terminal Emulator Library + * + * libghostty-vt is a C library which implements a modern terminal emulator, + * extracted from the [Ghostty](https://ghostty.org) terminal emulator. + * + * libghostty-vt contains the logic for handling the core parts of a terminal + * emulator: parsing terminal escape sequences, maintaining terminal state, + * encoding input events, etc. It can handle scrollback, line wrapping, + * reflow on resize, and more. + * + * @warning This library is currently in development and the API is not yet stable. + * Breaking changes are expected in future versions. Use with caution in production code. + * + * @section groups_sec API Reference + * + * The API is organized into the following groups: + * - @ref key "Key Encoding" - Encode key events into terminal sequences + * - @ref osc "OSC Parser" - Parse OSC (Operating System Command) sequences + * - @ref sgr "SGR Parser" - Parse SGR (Select Graphic Rendition) sequences + * - @ref paste "Paste Utilities" - Validate paste data safety + * - @ref allocator "Memory Management" - Memory management and custom allocators + * - @ref wasm "WebAssembly Utilities" - WebAssembly convenience functions + * + * @section examples_sec Examples + * + * Complete working examples: + * - @ref c-vt/src/main.c - OSC parser example + * - @ref c-vt-key-encode/src/main.c - Key encoding example + * - @ref c-vt-paste/src/main.c - Paste safety check example + * - @ref c-vt-sgr/src/main.c - SGR parser example + * + */ + +/** @example c-vt/src/main.c + * This example demonstrates how to use the OSC parser to parse an OSC sequence, + * extract command information, and retrieve command-specific data like window titles. + */ + +/** @example c-vt-key-encode/src/main.c + * This example demonstrates how to use the key encoder to convert key events + * into terminal escape sequences using the Kitty keyboard protocol. + */ + +/** @example c-vt-paste/src/main.c + * This example demonstrates how to use the paste utilities to check if + * paste data is safe before sending it to the terminal. + */ + +/** @example c-vt-sgr/src/main.c + * This example demonstrates how to use the SGR parser to parse terminal + * styling sequences and extract text attributes like colors and underline styles. + */ + +#ifndef GHOSTTY_VT_H +#define GHOSTTY_VT_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include +#include +#include +#include +#include +#include + +#ifdef __cplusplus +} +#endif + +#endif /* GHOSTTY_VT_H */ diff --git a/apps/mobile/modules/t3-terminal/Vendor/libghostty/GhosttyKit.xcframework/ios-arm64/Headers/ghostty/vt/allocator.h b/apps/mobile/modules/t3-terminal/Vendor/libghostty/GhosttyKit.xcframework/ios-arm64/Headers/ghostty/vt/allocator.h new file mode 100644 index 0000000000..4cebe91bb1 --- /dev/null +++ b/apps/mobile/modules/t3-terminal/Vendor/libghostty/GhosttyKit.xcframework/ios-arm64/Headers/ghostty/vt/allocator.h @@ -0,0 +1,196 @@ +/** + * @file allocator.h + * + * Memory management interface for libghostty-vt. + */ + +#ifndef GHOSTTY_VT_ALLOCATOR_H +#define GHOSTTY_VT_ALLOCATOR_H + +#include +#include +#include + +/** @defgroup allocator Memory Management + * + * libghostty-vt does require memory allocation for various operations, + * but is resilient to allocation failures and will gracefully handle + * out-of-memory situations by returning error codes. + * + * The exact memory management semantics are documented in the relevant + * functions and data structures. + * + * libghostty-vt uses explicit memory allocation via an allocator + * interface provided by GhosttyAllocator. The interface is based on the + * [Zig](https://ziglang.org) allocator interface, since this has been + * shown to be a flexible and powerful interface in practice and enables + * a wide variety of allocation strategies. + * + * **For the common case, you can pass NULL as the allocator for any + * function that accepts one,** and libghostty will use a default allocator. + * The default allocator will be libc malloc/free if libc is linked. + * Otherwise, a custom allocator is used (currently Zig's SMP allocator) + * that doesn't require any external dependencies. + * + * ## Basic Usage + * + * For simple use cases, you can ignore this interface entirely by passing NULL + * as the allocator parameter to functions that accept one. This will use the + * default allocator (typically libc malloc/free, if libc is linked, but + * we provide our own default allocator if libc isn't linked). + * + * To use a custom allocator: + * 1. Implement the GhosttyAllocatorVtable function pointers + * 2. Create a GhosttyAllocator struct with your vtable and context + * 3. Pass the allocator to functions that accept one + * + * @{ + */ + +/** + * Function table for custom memory allocator operations. + * + * This vtable defines the interface for a custom memory allocator. All + * function pointers must be valid and non-NULL. + * + * @ingroup allocator + * + * If you're not going to use a custom allocator, you can ignore all of + * this. All functions that take an allocator pointer allow NULL to use a + * default allocator. + * + * The interface is based on the Zig allocator interface. I'll say up front + * that it is easy to look at this interface and think "wow, this is really + * overcomplicated". The reason for this complexity is well thought out by + * the Zig folks, and it enables a diverse set of allocation strategies + * as shown by the Zig ecosystem. As a consolation, please note that many + * of the arguments are only needed for advanced use cases and can be + * safely ignored in simple implementations. For example, if you look at + * the Zig implementation of the libc allocator in `lib/std/heap.zig` + * (search for CAllocator), you'll see it is very simple. + * + * We chose to align with the Zig allocator interface because: + * + * 1. It is a proven interface that serves a wide variety of use cases + * in the real world via the Zig ecosystem. It's shown to work. + * + * 2. Our core implementation itself is Zig, and this lets us very + * cheaply and easily convert between C and Zig allocators. + * + * NOTE(mitchellh): In the future, we can have default implementations of + * resize/remap and allow those to be null. + */ +typedef struct { + /** + * Return a pointer to `len` bytes with specified `alignment`, or return + * `NULL` indicating the allocation failed. + * + * @param ctx The allocator context + * @param len Number of bytes to allocate + * @param alignment Required alignment for the allocation. Guaranteed to + * be a power of two between 1 and 16 inclusive. + * @param ret_addr First return address of the allocation call stack (0 if not provided) + * @return Pointer to allocated memory, or NULL if allocation failed + */ + void* (*alloc)(void *ctx, size_t len, uint8_t alignment, uintptr_t ret_addr); + + /** + * Attempt to expand or shrink memory in place. + * + * `memory_len` must equal the length requested from the most recent + * successful call to `alloc`, `resize`, or `remap`. `alignment` must + * equal the same value that was passed as the `alignment` parameter to + * the original `alloc` call. + * + * `new_len` must be greater than zero. + * + * @param ctx The allocator context + * @param memory Pointer to the memory block to resize + * @param memory_len Current size of the memory block + * @param alignment Alignment (must match original allocation) + * @param new_len New requested size + * @param ret_addr First return address of the allocation call stack (0 if not provided) + * @return true if resize was successful in-place, false if relocation would be required + */ + bool (*resize)(void *ctx, void *memory, size_t memory_len, uint8_t alignment, size_t new_len, uintptr_t ret_addr); + + /** + * Attempt to expand or shrink memory, allowing relocation. + * + * `memory_len` must equal the length requested from the most recent + * successful call to `alloc`, `resize`, or `remap`. `alignment` must + * equal the same value that was passed as the `alignment` parameter to + * the original `alloc` call. + * + * A non-`NULL` return value indicates the resize was successful. The + * allocation may have same address, or may have been relocated. In either + * case, the allocation now has size of `new_len`. A `NULL` return value + * indicates that the resize would be equivalent to allocating new memory, + * copying the bytes from the old memory, and then freeing the old memory. + * In such case, it is more efficient for the caller to perform the copy. + * + * `new_len` must be greater than zero. + * + * @param ctx The allocator context + * @param memory Pointer to the memory block to remap + * @param memory_len Current size of the memory block + * @param alignment Alignment (must match original allocation) + * @param new_len New requested size + * @param ret_addr First return address of the allocation call stack (0 if not provided) + * @return Pointer to resized memory (may be relocated), or NULL if manual copy is needed + */ + void* (*remap)(void *ctx, void *memory, size_t memory_len, uint8_t alignment, size_t new_len, uintptr_t ret_addr); + + /** + * Free and invalidate a region of memory. + * + * `memory_len` must equal the length requested from the most recent + * successful call to `alloc`, `resize`, or `remap`. `alignment` must + * equal the same value that was passed as the `alignment` parameter to + * the original `alloc` call. + * + * @param ctx The allocator context + * @param memory Pointer to the memory block to free + * @param memory_len Size of the memory block + * @param alignment Alignment (must match original allocation) + * @param ret_addr First return address of the allocation call stack (0 if not provided) + */ + void (*free)(void *ctx, void *memory, size_t memory_len, uint8_t alignment, uintptr_t ret_addr); +} GhosttyAllocatorVtable; + +/** + * Custom memory allocator. + * + * For functions that take an allocator pointer, a NULL pointer indicates + * that the default allocator should be used. The default allocator will + * be libc malloc/free if we're linking to libc. If libc isn't linked, + * a custom allocator is used (currently Zig's SMP allocator). + * + * @ingroup allocator + * + * Usage example: + * @code + * GhosttyAllocator allocator = { + * .vtable = &my_allocator_vtable, + * .ctx = my_allocator_state + * }; + * @endcode + */ +typedef struct GhosttyAllocator { + /** + * Opaque context pointer passed to all vtable functions. + * This allows the allocator implementation to maintain state + * or reference external resources needed for memory management. + */ + void *ctx; + + /** + * Pointer to the allocator's vtable containing function pointers + * for memory operations (alloc, resize, remap, free). + */ + const GhosttyAllocatorVtable *vtable; +} GhosttyAllocator; + +/** @} */ + +#endif /* GHOSTTY_VT_ALLOCATOR_H */ diff --git a/apps/mobile/modules/t3-terminal/Vendor/libghostty/GhosttyKit.xcframework/ios-arm64/Headers/ghostty/vt/color.h b/apps/mobile/modules/t3-terminal/Vendor/libghostty/GhosttyKit.xcframework/ios-arm64/Headers/ghostty/vt/color.h new file mode 100644 index 0000000000..0d57b8db4a --- /dev/null +++ b/apps/mobile/modules/t3-terminal/Vendor/libghostty/GhosttyKit.xcframework/ios-arm64/Headers/ghostty/vt/color.h @@ -0,0 +1,96 @@ +/** + * @file color.h + * + * Color types and utilities. + */ + +#ifndef GHOSTTY_VT_COLOR_H +#define GHOSTTY_VT_COLOR_H + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * RGB color value. + * + * @ingroup sgr + */ +typedef struct { + uint8_t r; /**< Red component (0-255) */ + uint8_t g; /**< Green component (0-255) */ + uint8_t b; /**< Blue component (0-255) */ +} GhosttyColorRgb; + +/** + * Palette color index (0-255). + * + * @ingroup sgr + */ +typedef uint8_t GhosttyColorPaletteIndex; + +/** @addtogroup sgr + * @{ + */ + +/** Black color (0) @ingroup sgr */ +#define GHOSTTY_COLOR_NAMED_BLACK 0 +/** Red color (1) @ingroup sgr */ +#define GHOSTTY_COLOR_NAMED_RED 1 +/** Green color (2) @ingroup sgr */ +#define GHOSTTY_COLOR_NAMED_GREEN 2 +/** Yellow color (3) @ingroup sgr */ +#define GHOSTTY_COLOR_NAMED_YELLOW 3 +/** Blue color (4) @ingroup sgr */ +#define GHOSTTY_COLOR_NAMED_BLUE 4 +/** Magenta color (5) @ingroup sgr */ +#define GHOSTTY_COLOR_NAMED_MAGENTA 5 +/** Cyan color (6) @ingroup sgr */ +#define GHOSTTY_COLOR_NAMED_CYAN 6 +/** White color (7) @ingroup sgr */ +#define GHOSTTY_COLOR_NAMED_WHITE 7 +/** Bright black color (8) @ingroup sgr */ +#define GHOSTTY_COLOR_NAMED_BRIGHT_BLACK 8 +/** Bright red color (9) @ingroup sgr */ +#define GHOSTTY_COLOR_NAMED_BRIGHT_RED 9 +/** Bright green color (10) @ingroup sgr */ +#define GHOSTTY_COLOR_NAMED_BRIGHT_GREEN 10 +/** Bright yellow color (11) @ingroup sgr */ +#define GHOSTTY_COLOR_NAMED_BRIGHT_YELLOW 11 +/** Bright blue color (12) @ingroup sgr */ +#define GHOSTTY_COLOR_NAMED_BRIGHT_BLUE 12 +/** Bright magenta color (13) @ingroup sgr */ +#define GHOSTTY_COLOR_NAMED_BRIGHT_MAGENTA 13 +/** Bright cyan color (14) @ingroup sgr */ +#define GHOSTTY_COLOR_NAMED_BRIGHT_CYAN 14 +/** Bright white color (15) @ingroup sgr */ +#define GHOSTTY_COLOR_NAMED_BRIGHT_WHITE 15 + +/** @} */ + +/** + * Get the RGB color components. + * + * This function extracts the individual red, green, and blue components + * from a GhosttyColorRgb value. Primarily useful in WebAssembly environments + * where accessing struct fields directly is difficult. + * + * @param color The RGB color value + * @param r Pointer to store the red component (0-255) + * @param g Pointer to store the green component (0-255) + * @param b Pointer to store the blue component (0-255) + * + * @ingroup sgr + */ +void ghostty_color_rgb_get(GhosttyColorRgb color, + uint8_t* r, + uint8_t* g, + uint8_t* b); + +#ifdef __cplusplus +} +#endif + +#endif /* GHOSTTY_VT_COLOR_H */ diff --git a/apps/mobile/modules/t3-terminal/Vendor/libghostty/GhosttyKit.xcframework/ios-arm64/Headers/ghostty/vt/key.h b/apps/mobile/modules/t3-terminal/Vendor/libghostty/GhosttyKit.xcframework/ios-arm64/Headers/ghostty/vt/key.h new file mode 100644 index 0000000000..772b5d43bc --- /dev/null +++ b/apps/mobile/modules/t3-terminal/Vendor/libghostty/GhosttyKit.xcframework/ios-arm64/Headers/ghostty/vt/key.h @@ -0,0 +1,80 @@ +/** + * @file key.h + * + * Key encoding module - encode key events into terminal escape sequences. + */ + +#ifndef GHOSTTY_VT_KEY_H +#define GHOSTTY_VT_KEY_H + +/** @defgroup key Key Encoding + * + * Utilities for encoding key events into terminal escape sequences, + * supporting both legacy encoding as well as Kitty Keyboard Protocol. + * + * ## Basic Usage + * + * 1. Create an encoder instance with ghostty_key_encoder_new() + * 2. Configure encoder options with ghostty_key_encoder_setopt(). + * 3. For each key event: + * - Create a key event with ghostty_key_event_new() + * - Set event properties (action, key, modifiers, etc.) + * - Encode with ghostty_key_encoder_encode() + * - Free the event with ghostty_key_event_free() + * - Note: You can also reuse the same key event multiple times by + * changing its properties. + * 4. Free the encoder with ghostty_key_encoder_free() when done + * + * ## Example + * + * @code{.c} + * #include + * #include + * #include + * + * int main() { + * // Create encoder + * GhosttyKeyEncoder encoder; + * GhosttyResult result = ghostty_key_encoder_new(NULL, &encoder); + * assert(result == GHOSTTY_SUCCESS); + * + * // Enable Kitty keyboard protocol with all features + * ghostty_key_encoder_setopt(encoder, GHOSTTY_KEY_ENCODER_OPT_KITTY_FLAGS, + * &(uint8_t){GHOSTTY_KITTY_KEY_ALL}); + * + * // Create and configure key event for Ctrl+C press + * GhosttyKeyEvent event; + * result = ghostty_key_event_new(NULL, &event); + * assert(result == GHOSTTY_SUCCESS); + * ghostty_key_event_set_action(event, GHOSTTY_KEY_ACTION_PRESS); + * ghostty_key_event_set_key(event, GHOSTTY_KEY_C); + * ghostty_key_event_set_mods(event, GHOSTTY_MODS_CTRL); + * + * // Encode the key event + * char buf[128]; + * size_t written = 0; + * result = ghostty_key_encoder_encode(encoder, event, buf, sizeof(buf), &written); + * assert(result == GHOSTTY_SUCCESS); + * + * // Use the encoded sequence (e.g., write to terminal) + * fwrite(buf, 1, written, stdout); + * + * // Cleanup + * ghostty_key_event_free(event); + * ghostty_key_encoder_free(encoder); + * return 0; + * } + * @endcode + * + * For a complete working example, see example/c-vt-key-encode in the + * repository. + * + * @{ + */ + +#include +#include + +/** @} */ + +#endif /* GHOSTTY_VT_KEY_H */ diff --git a/apps/mobile/modules/t3-terminal/Vendor/libghostty/GhosttyKit.xcframework/ios-arm64/Headers/ghostty/vt/key/encoder.h b/apps/mobile/modules/t3-terminal/Vendor/libghostty/GhosttyKit.xcframework/ios-arm64/Headers/ghostty/vt/key/encoder.h new file mode 100644 index 0000000000..766a294279 --- /dev/null +++ b/apps/mobile/modules/t3-terminal/Vendor/libghostty/GhosttyKit.xcframework/ios-arm64/Headers/ghostty/vt/key/encoder.h @@ -0,0 +1,221 @@ +/** + * @file encoder.h + * + * Key event encoding to terminal escape sequences. + */ + +#ifndef GHOSTTY_VT_KEY_ENCODER_H +#define GHOSTTY_VT_KEY_ENCODER_H + +#include +#include +#include +#include +#include + +/** + * Opaque handle to a key encoder instance. + * + * This handle represents a key encoder that converts key events into terminal + * escape sequences. + * + * @ingroup key + */ +typedef struct GhosttyKeyEncoder *GhosttyKeyEncoder; + +/** + * Kitty keyboard protocol flags. + * + * Bitflags representing the various modes of the Kitty keyboard protocol. + * These can be combined using bitwise OR operations. Valid values all + * start with `GHOSTTY_KITTY_KEY_`. + * + * @ingroup key + */ +typedef uint8_t GhosttyKittyKeyFlags; + +/** Kitty keyboard protocol disabled (all flags off) */ +#define GHOSTTY_KITTY_KEY_DISABLED 0 + +/** Disambiguate escape codes */ +#define GHOSTTY_KITTY_KEY_DISAMBIGUATE (1 << 0) + +/** Report key press and release events */ +#define GHOSTTY_KITTY_KEY_REPORT_EVENTS (1 << 1) + +/** Report alternate key codes */ +#define GHOSTTY_KITTY_KEY_REPORT_ALTERNATES (1 << 2) + +/** Report all key events including those normally handled by the terminal */ +#define GHOSTTY_KITTY_KEY_REPORT_ALL (1 << 3) + +/** Report associated text with key events */ +#define GHOSTTY_KITTY_KEY_REPORT_ASSOCIATED (1 << 4) + +/** All Kitty keyboard protocol flags enabled */ +#define GHOSTTY_KITTY_KEY_ALL (GHOSTTY_KITTY_KEY_DISAMBIGUATE | GHOSTTY_KITTY_KEY_REPORT_EVENTS | GHOSTTY_KITTY_KEY_REPORT_ALTERNATES | GHOSTTY_KITTY_KEY_REPORT_ALL | GHOSTTY_KITTY_KEY_REPORT_ASSOCIATED) + +/** + * macOS option key behavior. + * + * Determines whether the "option" key on macOS is treated as "alt" or not. + * See the Ghostty `macos-option-as-alt` configuration option for more details. + * + * @ingroup key + */ +typedef enum { + /** Option key is not treated as alt */ + GHOSTTY_OPTION_AS_ALT_FALSE = 0, + /** Option key is treated as alt */ + GHOSTTY_OPTION_AS_ALT_TRUE = 1, + /** Only left option key is treated as alt */ + GHOSTTY_OPTION_AS_ALT_LEFT = 2, + /** Only right option key is treated as alt */ + GHOSTTY_OPTION_AS_ALT_RIGHT = 3, +} GhosttyOptionAsAlt; + +/** + * Key encoder option identifiers. + * + * These values are used with ghostty_key_encoder_setopt() to configure + * the behavior of the key encoder. + * + * @ingroup key + */ +typedef enum { + /** Terminal DEC mode 1: cursor key application mode (value: bool) */ + GHOSTTY_KEY_ENCODER_OPT_CURSOR_KEY_APPLICATION = 0, + + /** Terminal DEC mode 66: keypad key application mode (value: bool) */ + GHOSTTY_KEY_ENCODER_OPT_KEYPAD_KEY_APPLICATION = 1, + + /** Terminal DEC mode 1035: ignore keypad with numlock (value: bool) */ + GHOSTTY_KEY_ENCODER_OPT_IGNORE_KEYPAD_WITH_NUMLOCK = 2, + + /** Terminal DEC mode 1036: alt sends escape prefix (value: bool) */ + GHOSTTY_KEY_ENCODER_OPT_ALT_ESC_PREFIX = 3, + + /** xterm modifyOtherKeys mode 2 (value: bool) */ + GHOSTTY_KEY_ENCODER_OPT_MODIFY_OTHER_KEYS_STATE_2 = 4, + + /** Kitty keyboard protocol flags (value: GhosttyKittyKeyFlags bitmask) */ + GHOSTTY_KEY_ENCODER_OPT_KITTY_FLAGS = 5, + + /** macOS option-as-alt setting (value: GhosttyOptionAsAlt) */ + GHOSTTY_KEY_ENCODER_OPT_MACOS_OPTION_AS_ALT = 6, +} GhosttyKeyEncoderOption; + +/** + * Create a new key encoder instance. + * + * Creates a new key encoder with default options. The encoder can be configured + * using ghostty_key_encoder_setopt() and must be freed using + * ghostty_key_encoder_free() when no longer needed. + * + * @param allocator Pointer to the allocator to use for memory management, or NULL to use the default allocator + * @param encoder Pointer to store the created encoder handle + * @return GHOSTTY_SUCCESS on success, or an error code on failure + * + * @ingroup key + */ +GhosttyResult ghostty_key_encoder_new(const GhosttyAllocator *allocator, GhosttyKeyEncoder *encoder); + +/** + * Free a key encoder instance. + * + * Releases all resources associated with the key encoder. After this call, + * the encoder handle becomes invalid and must not be used. + * + * @param encoder The encoder handle to free (may be NULL) + * + * @ingroup key + */ +void ghostty_key_encoder_free(GhosttyKeyEncoder encoder); + +/** + * Set an option on the key encoder. + * + * Configures the behavior of the key encoder. Options control various aspects + * of encoding such as terminal modes (cursor key application mode, keypad mode), + * protocol selection (Kitty keyboard protocol flags), and platform-specific + * behaviors (macOS option-as-alt). + * + * A null pointer value does nothing. It does not reset the value to the + * default. The setopt call will do nothing. + * + * @param encoder The encoder handle, must not be NULL + * @param option The option to set + * @param value Pointer to the value to set (type depends on the option) + * + * @ingroup key + */ +void ghostty_key_encoder_setopt(GhosttyKeyEncoder encoder, GhosttyKeyEncoderOption option, const void *value); + +/** + * Encode a key event into a terminal escape sequence. + * + * Converts a key event into the appropriate terminal escape sequence based on + * the encoder's current options. The sequence is written to the provided buffer. + * + * Not all key events produce output. For example, unmodified modifier keys + * typically don't generate escape sequences. Check the out_len parameter to + * determine if any data was written. + * + * If the output buffer is too small, this function returns GHOSTTY_OUT_OF_MEMORY + * and out_len will contain the required buffer size. The caller can then + * allocate a larger buffer and call the function again. + * + * @param encoder The encoder handle, must not be NULL + * @param event The key event to encode, must not be NULL + * @param out_buf Buffer to write the encoded sequence to + * @param out_buf_size Size of the output buffer in bytes + * @param out_len Pointer to store the number of bytes written (may be NULL) + * @return GHOSTTY_SUCCESS on success, GHOSTTY_OUT_OF_MEMORY if buffer too small, or other error code + * + * ## Example: Calculate required buffer size + * + * @code{.c} + * // Query the required size with a NULL buffer (always returns OUT_OF_MEMORY) + * size_t required = 0; + * GhosttyResult result = ghostty_key_encoder_encode(encoder, event, NULL, 0, &required); + * assert(result == GHOSTTY_OUT_OF_MEMORY); + * + * // Allocate buffer of required size + * char *buf = malloc(required); + * + * // Encode with properly sized buffer + * size_t written = 0; + * result = ghostty_key_encoder_encode(encoder, event, buf, required, &written); + * assert(result == GHOSTTY_SUCCESS); + * + * // Use the encoded sequence... + * + * free(buf); + * @endcode + * + * ## Example: Direct encoding with static buffer + * + * @code{.c} + * // Most escape sequences are short, so a static buffer often suffices + * char buf[128]; + * size_t written = 0; + * GhosttyResult result = ghostty_key_encoder_encode(encoder, event, buf, sizeof(buf), &written); + * + * if (result == GHOSTTY_SUCCESS) { + * // Write the encoded sequence to the terminal + * write(pty_fd, buf, written); + * } else if (result == GHOSTTY_OUT_OF_MEMORY) { + * // Buffer too small, written contains required size + * char *dynamic_buf = malloc(written); + * result = ghostty_key_encoder_encode(encoder, event, dynamic_buf, written, &written); + * assert(result == GHOSTTY_SUCCESS); + * write(pty_fd, dynamic_buf, written); + * free(dynamic_buf); + * } + * @endcode + * + * @ingroup key + */ +GhosttyResult ghostty_key_encoder_encode(GhosttyKeyEncoder encoder, GhosttyKeyEvent event, char *out_buf, size_t out_buf_size, size_t *out_len); + +#endif /* GHOSTTY_VT_KEY_ENCODER_H */ diff --git a/apps/mobile/modules/t3-terminal/Vendor/libghostty/GhosttyKit.xcframework/ios-arm64/Headers/ghostty/vt/key/event.h b/apps/mobile/modules/t3-terminal/Vendor/libghostty/GhosttyKit.xcframework/ios-arm64/Headers/ghostty/vt/key/event.h new file mode 100644 index 0000000000..dbd2e9f841 --- /dev/null +++ b/apps/mobile/modules/t3-terminal/Vendor/libghostty/GhosttyKit.xcframework/ios-arm64/Headers/ghostty/vt/key/event.h @@ -0,0 +1,474 @@ +/** + * @file event.h + * + * Key event representation and manipulation. + */ + +#ifndef GHOSTTY_VT_KEY_EVENT_H +#define GHOSTTY_VT_KEY_EVENT_H + +#include +#include +#include +#include +#include + +/** + * Opaque handle to a key event. + * + * This handle represents a keyboard input event containing information about + * the physical key pressed, modifiers, and generated text. + * + * @ingroup key + */ +typedef struct GhosttyKeyEvent *GhosttyKeyEvent; + +/** + * Keyboard input event types. + * + * @ingroup key + */ +typedef enum { + /** Key was released */ + GHOSTTY_KEY_ACTION_RELEASE = 0, + /** Key was pressed */ + GHOSTTY_KEY_ACTION_PRESS = 1, + /** Key is being repeated (held down) */ + GHOSTTY_KEY_ACTION_REPEAT = 2, +} GhosttyKeyAction; + +/** + * Keyboard modifier keys bitmask. + * + * A bitmask representing all keyboard modifiers. This tracks which modifier keys + * are pressed and, where supported by the platform, which side (left or right) + * of each modifier is active. + * + * Use the GHOSTTY_MODS_* constants to test and set individual modifiers. + * + * Modifier side bits are only meaningful when the corresponding modifier bit is set. + * Not all platforms support distinguishing between left and right modifier + * keys and Ghostty is built to expect that some platforms may not provide this + * information. + * + * @ingroup key + */ +typedef uint16_t GhosttyMods; + +/** Shift key is pressed */ +#define GHOSTTY_MODS_SHIFT (1 << 0) +/** Control key is pressed */ +#define GHOSTTY_MODS_CTRL (1 << 1) +/** Alt/Option key is pressed */ +#define GHOSTTY_MODS_ALT (1 << 2) +/** Super/Command/Windows key is pressed */ +#define GHOSTTY_MODS_SUPER (1 << 3) +/** Caps Lock is active */ +#define GHOSTTY_MODS_CAPS_LOCK (1 << 4) +/** Num Lock is active */ +#define GHOSTTY_MODS_NUM_LOCK (1 << 5) + +/** + * Right shift is pressed (0 = left, 1 = right). + * Only meaningful when GHOSTTY_MODS_SHIFT is set. + */ +#define GHOSTTY_MODS_SHIFT_SIDE (1 << 6) +/** + * Right ctrl is pressed (0 = left, 1 = right). + * Only meaningful when GHOSTTY_MODS_CTRL is set. + */ +#define GHOSTTY_MODS_CTRL_SIDE (1 << 7) +/** + * Right alt is pressed (0 = left, 1 = right). + * Only meaningful when GHOSTTY_MODS_ALT is set. + */ +#define GHOSTTY_MODS_ALT_SIDE (1 << 8) +/** + * Right super is pressed (0 = left, 1 = right). + * Only meaningful when GHOSTTY_MODS_SUPER is set. + */ +#define GHOSTTY_MODS_SUPER_SIDE (1 << 9) + +/** + * Physical key codes. + * + * The set of key codes that Ghostty is aware of. These represent physical keys + * on the keyboard and are layout-independent. For example, the "a" key on a US + * keyboard is the same as the "ф" key on a Russian keyboard, but both will + * report the same key_a value. + * + * Layout-dependent strings are provided separately as UTF-8 text and are produced + * by the platform. These values are based on the W3C UI Events KeyboardEvent code + * standard. See: https://www.w3.org/TR/uievents-code + * + * @ingroup key + */ +typedef enum { + GHOSTTY_KEY_UNIDENTIFIED = 0, + + // Writing System Keys (W3C § 3.1.1) + GHOSTTY_KEY_BACKQUOTE, + GHOSTTY_KEY_BACKSLASH, + GHOSTTY_KEY_BRACKET_LEFT, + GHOSTTY_KEY_BRACKET_RIGHT, + GHOSTTY_KEY_COMMA, + GHOSTTY_KEY_DIGIT_0, + GHOSTTY_KEY_DIGIT_1, + GHOSTTY_KEY_DIGIT_2, + GHOSTTY_KEY_DIGIT_3, + GHOSTTY_KEY_DIGIT_4, + GHOSTTY_KEY_DIGIT_5, + GHOSTTY_KEY_DIGIT_6, + GHOSTTY_KEY_DIGIT_7, + GHOSTTY_KEY_DIGIT_8, + GHOSTTY_KEY_DIGIT_9, + GHOSTTY_KEY_EQUAL, + GHOSTTY_KEY_INTL_BACKSLASH, + GHOSTTY_KEY_INTL_RO, + GHOSTTY_KEY_INTL_YEN, + GHOSTTY_KEY_A, + GHOSTTY_KEY_B, + GHOSTTY_KEY_C, + GHOSTTY_KEY_D, + GHOSTTY_KEY_E, + GHOSTTY_KEY_F, + GHOSTTY_KEY_G, + GHOSTTY_KEY_H, + GHOSTTY_KEY_I, + GHOSTTY_KEY_J, + GHOSTTY_KEY_K, + GHOSTTY_KEY_L, + GHOSTTY_KEY_M, + GHOSTTY_KEY_N, + GHOSTTY_KEY_O, + GHOSTTY_KEY_P, + GHOSTTY_KEY_Q, + GHOSTTY_KEY_R, + GHOSTTY_KEY_S, + GHOSTTY_KEY_T, + GHOSTTY_KEY_U, + GHOSTTY_KEY_V, + GHOSTTY_KEY_W, + GHOSTTY_KEY_X, + GHOSTTY_KEY_Y, + GHOSTTY_KEY_Z, + GHOSTTY_KEY_MINUS, + GHOSTTY_KEY_PERIOD, + GHOSTTY_KEY_QUOTE, + GHOSTTY_KEY_SEMICOLON, + GHOSTTY_KEY_SLASH, + + // Functional Keys (W3C § 3.1.2) + GHOSTTY_KEY_ALT_LEFT, + GHOSTTY_KEY_ALT_RIGHT, + GHOSTTY_KEY_BACKSPACE, + GHOSTTY_KEY_CAPS_LOCK, + GHOSTTY_KEY_CONTEXT_MENU, + GHOSTTY_KEY_CONTROL_LEFT, + GHOSTTY_KEY_CONTROL_RIGHT, + GHOSTTY_KEY_ENTER, + GHOSTTY_KEY_META_LEFT, + GHOSTTY_KEY_META_RIGHT, + GHOSTTY_KEY_SHIFT_LEFT, + GHOSTTY_KEY_SHIFT_RIGHT, + GHOSTTY_KEY_SPACE, + GHOSTTY_KEY_TAB, + GHOSTTY_KEY_CONVERT, + GHOSTTY_KEY_KANA_MODE, + GHOSTTY_KEY_NON_CONVERT, + + // Control Pad Section (W3C § 3.2) + GHOSTTY_KEY_DELETE, + GHOSTTY_KEY_END, + GHOSTTY_KEY_HELP, + GHOSTTY_KEY_HOME, + GHOSTTY_KEY_INSERT, + GHOSTTY_KEY_PAGE_DOWN, + GHOSTTY_KEY_PAGE_UP, + + // Arrow Pad Section (W3C § 3.3) + GHOSTTY_KEY_ARROW_DOWN, + GHOSTTY_KEY_ARROW_LEFT, + GHOSTTY_KEY_ARROW_RIGHT, + GHOSTTY_KEY_ARROW_UP, + + // Numpad Section (W3C § 3.4) + GHOSTTY_KEY_NUM_LOCK, + GHOSTTY_KEY_NUMPAD_0, + GHOSTTY_KEY_NUMPAD_1, + GHOSTTY_KEY_NUMPAD_2, + GHOSTTY_KEY_NUMPAD_3, + GHOSTTY_KEY_NUMPAD_4, + GHOSTTY_KEY_NUMPAD_5, + GHOSTTY_KEY_NUMPAD_6, + GHOSTTY_KEY_NUMPAD_7, + GHOSTTY_KEY_NUMPAD_8, + GHOSTTY_KEY_NUMPAD_9, + GHOSTTY_KEY_NUMPAD_ADD, + GHOSTTY_KEY_NUMPAD_BACKSPACE, + GHOSTTY_KEY_NUMPAD_CLEAR, + GHOSTTY_KEY_NUMPAD_CLEAR_ENTRY, + GHOSTTY_KEY_NUMPAD_COMMA, + GHOSTTY_KEY_NUMPAD_DECIMAL, + GHOSTTY_KEY_NUMPAD_DIVIDE, + GHOSTTY_KEY_NUMPAD_ENTER, + GHOSTTY_KEY_NUMPAD_EQUAL, + GHOSTTY_KEY_NUMPAD_MEMORY_ADD, + GHOSTTY_KEY_NUMPAD_MEMORY_CLEAR, + GHOSTTY_KEY_NUMPAD_MEMORY_RECALL, + GHOSTTY_KEY_NUMPAD_MEMORY_STORE, + GHOSTTY_KEY_NUMPAD_MEMORY_SUBTRACT, + GHOSTTY_KEY_NUMPAD_MULTIPLY, + GHOSTTY_KEY_NUMPAD_PAREN_LEFT, + GHOSTTY_KEY_NUMPAD_PAREN_RIGHT, + GHOSTTY_KEY_NUMPAD_SUBTRACT, + GHOSTTY_KEY_NUMPAD_SEPARATOR, + GHOSTTY_KEY_NUMPAD_UP, + GHOSTTY_KEY_NUMPAD_DOWN, + GHOSTTY_KEY_NUMPAD_RIGHT, + GHOSTTY_KEY_NUMPAD_LEFT, + GHOSTTY_KEY_NUMPAD_BEGIN, + GHOSTTY_KEY_NUMPAD_HOME, + GHOSTTY_KEY_NUMPAD_END, + GHOSTTY_KEY_NUMPAD_INSERT, + GHOSTTY_KEY_NUMPAD_DELETE, + GHOSTTY_KEY_NUMPAD_PAGE_UP, + GHOSTTY_KEY_NUMPAD_PAGE_DOWN, + + // Function Section (W3C § 3.5) + GHOSTTY_KEY_ESCAPE, + GHOSTTY_KEY_F1, + GHOSTTY_KEY_F2, + GHOSTTY_KEY_F3, + GHOSTTY_KEY_F4, + GHOSTTY_KEY_F5, + GHOSTTY_KEY_F6, + GHOSTTY_KEY_F7, + GHOSTTY_KEY_F8, + GHOSTTY_KEY_F9, + GHOSTTY_KEY_F10, + GHOSTTY_KEY_F11, + GHOSTTY_KEY_F12, + GHOSTTY_KEY_F13, + GHOSTTY_KEY_F14, + GHOSTTY_KEY_F15, + GHOSTTY_KEY_F16, + GHOSTTY_KEY_F17, + GHOSTTY_KEY_F18, + GHOSTTY_KEY_F19, + GHOSTTY_KEY_F20, + GHOSTTY_KEY_F21, + GHOSTTY_KEY_F22, + GHOSTTY_KEY_F23, + GHOSTTY_KEY_F24, + GHOSTTY_KEY_F25, + GHOSTTY_KEY_FN, + GHOSTTY_KEY_FN_LOCK, + GHOSTTY_KEY_PRINT_SCREEN, + GHOSTTY_KEY_SCROLL_LOCK, + GHOSTTY_KEY_PAUSE, + + // Media Keys (W3C § 3.6) + GHOSTTY_KEY_BROWSER_BACK, + GHOSTTY_KEY_BROWSER_FAVORITES, + GHOSTTY_KEY_BROWSER_FORWARD, + GHOSTTY_KEY_BROWSER_HOME, + GHOSTTY_KEY_BROWSER_REFRESH, + GHOSTTY_KEY_BROWSER_SEARCH, + GHOSTTY_KEY_BROWSER_STOP, + GHOSTTY_KEY_EJECT, + GHOSTTY_KEY_LAUNCH_APP_1, + GHOSTTY_KEY_LAUNCH_APP_2, + GHOSTTY_KEY_LAUNCH_MAIL, + GHOSTTY_KEY_MEDIA_PLAY_PAUSE, + GHOSTTY_KEY_MEDIA_SELECT, + GHOSTTY_KEY_MEDIA_STOP, + GHOSTTY_KEY_MEDIA_TRACK_NEXT, + GHOSTTY_KEY_MEDIA_TRACK_PREVIOUS, + GHOSTTY_KEY_POWER, + GHOSTTY_KEY_SLEEP, + GHOSTTY_KEY_AUDIO_VOLUME_DOWN, + GHOSTTY_KEY_AUDIO_VOLUME_MUTE, + GHOSTTY_KEY_AUDIO_VOLUME_UP, + GHOSTTY_KEY_WAKE_UP, + + // Legacy, Non-standard, and Special Keys (W3C § 3.7) + GHOSTTY_KEY_COPY, + GHOSTTY_KEY_CUT, + GHOSTTY_KEY_PASTE, +} GhosttyKey; + +/** + * Create a new key event instance. + * + * Creates a new key event with default values. The event must be freed using + * ghostty_key_event_free() when no longer needed. + * + * @param allocator Pointer to the allocator to use for memory management, or NULL to use the default allocator + * @param event Pointer to store the created key event handle + * @return GHOSTTY_SUCCESS on success, or an error code on failure + * + * @ingroup key + */ +GhosttyResult ghostty_key_event_new(const GhosttyAllocator *allocator, GhosttyKeyEvent *event); + +/** + * Free a key event instance. + * + * Releases all resources associated with the key event. After this call, + * the event handle becomes invalid and must not be used. + * + * @param event The key event handle to free (may be NULL) + * + * @ingroup key + */ +void ghostty_key_event_free(GhosttyKeyEvent event); + +/** + * Set the key action (press, release, repeat). + * + * @param event The key event handle, must not be NULL + * @param action The action to set + * + * @ingroup key + */ +void ghostty_key_event_set_action(GhosttyKeyEvent event, GhosttyKeyAction action); + +/** + * Get the key action (press, release, repeat). + * + * @param event The key event handle, must not be NULL + * @return The key action + * + * @ingroup key + */ +GhosttyKeyAction ghostty_key_event_get_action(GhosttyKeyEvent event); + +/** + * Set the physical key code. + * + * @param event The key event handle, must not be NULL + * @param key The physical key code to set + * + * @ingroup key + */ +void ghostty_key_event_set_key(GhosttyKeyEvent event, GhosttyKey key); + +/** + * Get the physical key code. + * + * @param event The key event handle, must not be NULL + * @return The physical key code + * + * @ingroup key + */ +GhosttyKey ghostty_key_event_get_key(GhosttyKeyEvent event); + +/** + * Set the modifier keys bitmask. + * + * @param event The key event handle, must not be NULL + * @param mods The modifier keys bitmask to set + * + * @ingroup key + */ +void ghostty_key_event_set_mods(GhosttyKeyEvent event, GhosttyMods mods); + +/** + * Get the modifier keys bitmask. + * + * @param event The key event handle, must not be NULL + * @return The modifier keys bitmask + * + * @ingroup key + */ +GhosttyMods ghostty_key_event_get_mods(GhosttyKeyEvent event); + +/** + * Set the consumed modifiers bitmask. + * + * @param event The key event handle, must not be NULL + * @param consumed_mods The consumed modifiers bitmask to set + * + * @ingroup key + */ +void ghostty_key_event_set_consumed_mods(GhosttyKeyEvent event, GhosttyMods consumed_mods); + +/** + * Get the consumed modifiers bitmask. + * + * @param event The key event handle, must not be NULL + * @return The consumed modifiers bitmask + * + * @ingroup key + */ +GhosttyMods ghostty_key_event_get_consumed_mods(GhosttyKeyEvent event); + +/** + * Set whether the key event is part of a composition sequence. + * + * @param event The key event handle, must not be NULL + * @param composing Whether the key event is part of a composition sequence + * + * @ingroup key + */ +void ghostty_key_event_set_composing(GhosttyKeyEvent event, bool composing); + +/** + * Get whether the key event is part of a composition sequence. + * + * @param event The key event handle, must not be NULL + * @return Whether the key event is part of a composition sequence + * + * @ingroup key + */ +bool ghostty_key_event_get_composing(GhosttyKeyEvent event); + +/** + * Set the UTF-8 text generated by the key event. + * + * The key event does NOT take ownership of the text pointer. The caller + * must ensure the string remains valid for the lifetime needed by the event. + * + * @param event The key event handle, must not be NULL + * @param utf8 The UTF-8 text to set (or NULL for empty) + * @param len Length of the UTF-8 text in bytes + * + * @ingroup key + */ +void ghostty_key_event_set_utf8(GhosttyKeyEvent event, const char *utf8, size_t len); + +/** + * Get the UTF-8 text generated by the key event. + * + * The returned pointer is valid until the event is freed or the UTF-8 text is modified. + * + * @param event The key event handle, must not be NULL + * @param len Pointer to store the length of the UTF-8 text in bytes (may be NULL) + * @return The UTF-8 text (or NULL for empty) + * + * @ingroup key + */ +const char *ghostty_key_event_get_utf8(GhosttyKeyEvent event, size_t *len); + +/** + * Set the unshifted Unicode codepoint. + * + * @param event The key event handle, must not be NULL + * @param codepoint The unshifted Unicode codepoint to set + * + * @ingroup key + */ +void ghostty_key_event_set_unshifted_codepoint(GhosttyKeyEvent event, uint32_t codepoint); + +/** + * Get the unshifted Unicode codepoint. + * + * @param event The key event handle, must not be NULL + * @return The unshifted Unicode codepoint + * + * @ingroup key + */ +uint32_t ghostty_key_event_get_unshifted_codepoint(GhosttyKeyEvent event); + +#endif /* GHOSTTY_VT_KEY_EVENT_H */ diff --git a/apps/mobile/modules/t3-terminal/Vendor/libghostty/GhosttyKit.xcframework/ios-arm64/Headers/ghostty/vt/osc.h b/apps/mobile/modules/t3-terminal/Vendor/libghostty/GhosttyKit.xcframework/ios-arm64/Headers/ghostty/vt/osc.h new file mode 100644 index 0000000000..f53077ab32 --- /dev/null +++ b/apps/mobile/modules/t3-terminal/Vendor/libghostty/GhosttyKit.xcframework/ios-arm64/Headers/ghostty/vt/osc.h @@ -0,0 +1,233 @@ +/** + * @file osc.h + * + * OSC (Operating System Command) sequence parser and command handling. + */ + +#ifndef GHOSTTY_VT_OSC_H +#define GHOSTTY_VT_OSC_H + +#include +#include +#include +#include +#include + +/** + * Opaque handle to an OSC parser instance. + * + * This handle represents an OSC (Operating System Command) parser that can + * be used to parse the contents of OSC sequences. + * + * @ingroup osc + */ +typedef struct GhosttyOscParser *GhosttyOscParser; + +/** + * Opaque handle to a single OSC command. + * + * This handle represents a parsed OSC (Operating System Command) command. + * The command can be queried for its type and associated data. + * + * @ingroup osc + */ +typedef struct GhosttyOscCommand *GhosttyOscCommand; + +/** @defgroup osc OSC Parser + * + * OSC (Operating System Command) sequence parser and command handling. + * + * The parser operates in a streaming fashion, processing input byte-by-byte + * to handle OSC sequences that may arrive in fragments across multiple reads. + * This interface makes it easy to integrate into most environments and avoids + * over-allocating buffers. + * + * ## Basic Usage + * + * 1. Create a parser instance with ghostty_osc_new() + * 2. Feed bytes to the parser using ghostty_osc_next() + * 3. Finalize parsing with ghostty_osc_end() to get the command + * 4. Query command type and extract data using ghostty_osc_command_type() + * and ghostty_osc_command_data() + * 5. Free the parser with ghostty_osc_free() when done + * + * @{ + */ + +/** + * OSC command types. + * + * @ingroup osc + */ +typedef enum { + GHOSTTY_OSC_COMMAND_INVALID = 0, + GHOSTTY_OSC_COMMAND_CHANGE_WINDOW_TITLE = 1, + GHOSTTY_OSC_COMMAND_CHANGE_WINDOW_ICON = 2, + GHOSTTY_OSC_COMMAND_SEMANTIC_PROMPT = 3, + GHOSTTY_OSC_COMMAND_CLIPBOARD_CONTENTS = 4, + GHOSTTY_OSC_COMMAND_REPORT_PWD = 5, + GHOSTTY_OSC_COMMAND_MOUSE_SHAPE = 6, + GHOSTTY_OSC_COMMAND_COLOR_OPERATION = 7, + GHOSTTY_OSC_COMMAND_KITTY_COLOR_PROTOCOL = 8, + GHOSTTY_OSC_COMMAND_SHOW_DESKTOP_NOTIFICATION = 9, + GHOSTTY_OSC_COMMAND_HYPERLINK_START = 10, + GHOSTTY_OSC_COMMAND_HYPERLINK_END = 11, + GHOSTTY_OSC_COMMAND_CONEMU_SLEEP = 12, + GHOSTTY_OSC_COMMAND_CONEMU_SHOW_MESSAGE_BOX = 13, + GHOSTTY_OSC_COMMAND_CONEMU_CHANGE_TAB_TITLE = 14, + GHOSTTY_OSC_COMMAND_CONEMU_PROGRESS_REPORT = 15, + GHOSTTY_OSC_COMMAND_CONEMU_WAIT_INPUT = 16, + GHOSTTY_OSC_COMMAND_CONEMU_GUIMACRO = 17, + GHOSTTY_OSC_COMMAND_CONEMU_RUN_PROCESS = 18, + GHOSTTY_OSC_COMMAND_CONEMU_OUTPUT_ENVIRONMENT_VARIABLE = 19, + GHOSTTY_OSC_COMMAND_CONEMU_XTERM_EMULATION = 20, + GHOSTTY_OSC_COMMAND_CONEMU_COMMENT = 21, + GHOSTTY_OSC_COMMAND_KITTY_TEXT_SIZING = 22, +} GhosttyOscCommandType; + +/** + * OSC command data types. + * + * These values specify what type of data to extract from an OSC command + * using `ghostty_osc_command_data`. + * + * @ingroup osc + */ +typedef enum { + /** Invalid data type. Never results in any data extraction. */ + GHOSTTY_OSC_DATA_INVALID = 0, + + /** + * Window title string data. + * + * Valid for: GHOSTTY_OSC_COMMAND_CHANGE_WINDOW_TITLE + * + * Output type: const char ** (pointer to null-terminated string) + * + * Lifetime: Valid until the next call to any ghostty_osc_* function with + * the same parser instance. Memory is owned by the parser. + */ + GHOSTTY_OSC_DATA_CHANGE_WINDOW_TITLE_STR = 1, +} GhosttyOscCommandData; + +/** + * Create a new OSC parser instance. + * + * Creates a new OSC (Operating System Command) parser using the provided + * allocator. The parser must be freed using ghostty_vt_osc_free() when + * no longer needed. + * + * @param allocator Pointer to the allocator to use for memory management, or NULL to use the default allocator + * @param parser Pointer to store the created parser handle + * @return GHOSTTY_SUCCESS on success, or an error code on failure + * + * @ingroup osc + */ +GhosttyResult ghostty_osc_new(const GhosttyAllocator *allocator, GhosttyOscParser *parser); + +/** + * Free an OSC parser instance. + * + * Releases all resources associated with the OSC parser. After this call, + * the parser handle becomes invalid and must not be used. + * + * @param parser The parser handle to free (may be NULL) + * + * @ingroup osc + */ +void ghostty_osc_free(GhosttyOscParser parser); + +/** + * Reset an OSC parser instance to its initial state. + * + * Resets the parser state, clearing any partially parsed OSC sequences + * and returning the parser to its initial state. This is useful for + * reusing a parser instance or recovering from parse errors. + * + * @param parser The parser handle to reset, must not be null. + * + * @ingroup osc + */ +void ghostty_osc_reset(GhosttyOscParser parser); + +/** + * Parse the next byte in an OSC sequence. + * + * Processes a single byte as part of an OSC sequence. The parser maintains + * internal state to track the progress through the sequence. Call this + * function for each byte in the sequence data. + * + * When finished pumping the parser with bytes, call ghostty_osc_end + * to get the final result. + * + * @param parser The parser handle, must not be null. + * @param byte The next byte to parse + * + * @ingroup osc + */ +void ghostty_osc_next(GhosttyOscParser parser, uint8_t byte); + +/** + * Finalize OSC parsing and retrieve the parsed command. + * + * Call this function after feeding all bytes of an OSC sequence to the parser + * using ghostty_osc_next() with the exception of the terminating character + * (ESC or ST). This function finalizes the parsing process and returns the + * parsed OSC command. + * + * The return value is never NULL. Invalid commands will return a command + * with type GHOSTTY_OSC_COMMAND_INVALID. + * + * The terminator parameter specifies the byte that terminated the OSC sequence + * (typically 0x07 for BEL or 0x5C for ST after ESC). This information is + * preserved in the parsed command so that responses can use the same terminator + * format for better compatibility with the calling program. For commands that + * do not require a response, this parameter is ignored and the resulting + * command will not retain the terminator information. + * + * The returned command handle is valid until the next call to any + * `ghostty_osc_*` function with the same parser instance with the exception + * of command introspection functions such as `ghostty_osc_command_type`. + * + * @param parser The parser handle, must not be null. + * @param terminator The terminating byte of the OSC sequence (0x07 for BEL, 0x5C for ST) + * @return Handle to the parsed OSC command + * + * @ingroup osc + */ +GhosttyOscCommand ghostty_osc_end(GhosttyOscParser parser, uint8_t terminator); + +/** + * Get the type of an OSC command. + * + * Returns the type identifier for the given OSC command. This can be used + * to determine what kind of command was parsed and what data might be + * available from it. + * + * @param command The OSC command handle to query (may be NULL) + * @return The command type, or GHOSTTY_OSC_COMMAND_INVALID if command is NULL + * + * @ingroup osc + */ +GhosttyOscCommandType ghostty_osc_command_type(GhosttyOscCommand command); + +/** + * Extract data from an OSC command. + * + * Extracts typed data from the given OSC command based on the specified + * data type. The output pointer must be of the appropriate type for the + * requested data kind. Valid command types, output types, and memory + * safety information are documented in the `GhosttyOscCommandData` enum. + * + * @param command The OSC command handle to query (may be NULL) + * @param data The type of data to extract + * @param out Pointer to store the extracted data (type depends on data parameter) + * @return true if data extraction was successful, false otherwise + * + * @ingroup osc + */ +bool ghostty_osc_command_data(GhosttyOscCommand command, GhosttyOscCommandData data, void *out); + +/** @} */ + +#endif /* GHOSTTY_VT_OSC_H */ diff --git a/apps/mobile/modules/t3-terminal/Vendor/libghostty/GhosttyKit.xcframework/ios-arm64/Headers/ghostty/vt/paste.h b/apps/mobile/modules/t3-terminal/Vendor/libghostty/GhosttyKit.xcframework/ios-arm64/Headers/ghostty/vt/paste.h new file mode 100644 index 0000000000..d90f303d43 --- /dev/null +++ b/apps/mobile/modules/t3-terminal/Vendor/libghostty/GhosttyKit.xcframework/ios-arm64/Headers/ghostty/vt/paste.h @@ -0,0 +1,75 @@ +/** + * @file paste.h + * + * Paste utilities - validate and encode paste data for terminal input. + */ + +#ifndef GHOSTTY_VT_PASTE_H +#define GHOSTTY_VT_PASTE_H + +/** @defgroup paste Paste Utilities + * + * Utilities for validating paste data safety. + * + * ## Basic Usage + * + * Use ghostty_paste_is_safe() to check if paste data contains potentially + * dangerous sequences before sending it to the terminal. + * + * ## Example + * + * @code{.c} + * #include + * #include + * #include + * + * int main() { + * const char* safe_data = "hello world"; + * const char* unsafe_data = "rm -rf /\n"; + * + * if (ghostty_paste_is_safe(safe_data, strlen(safe_data))) { + * printf("Safe to paste\n"); + * } + * + * if (!ghostty_paste_is_safe(unsafe_data, strlen(unsafe_data))) { + * printf("Unsafe! Contains newline\n"); + * } + * + * return 0; + * } + * @endcode + * + * @{ + */ + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * Check if paste data is safe to paste into the terminal. + * + * Data is considered unsafe if it contains: + * - Newlines (`\n`) which can inject commands + * - The bracketed paste end sequence (`\x1b[201~`) which can be used + * to exit bracketed paste mode and inject commands + * + * This check is conservative and considers data unsafe regardless of + * current terminal state. + * + * @param data The paste data to check (must not be NULL) + * @param len The length of the data in bytes + * @return true if the data is safe to paste, false otherwise + */ +bool ghostty_paste_is_safe(const char* data, size_t len); + +#ifdef __cplusplus +} +#endif + +/** @} */ + +#endif /* GHOSTTY_VT_PASTE_H */ diff --git a/apps/mobile/modules/t3-terminal/Vendor/libghostty/GhosttyKit.xcframework/ios-arm64/Headers/ghostty/vt/result.h b/apps/mobile/modules/t3-terminal/Vendor/libghostty/GhosttyKit.xcframework/ios-arm64/Headers/ghostty/vt/result.h new file mode 100644 index 0000000000..65938ee766 --- /dev/null +++ b/apps/mobile/modules/t3-terminal/Vendor/libghostty/GhosttyKit.xcframework/ios-arm64/Headers/ghostty/vt/result.h @@ -0,0 +1,22 @@ +/** + * @file result.h + * + * Result codes for libghostty-vt operations. + */ + +#ifndef GHOSTTY_VT_RESULT_H +#define GHOSTTY_VT_RESULT_H + +/** + * Result codes for libghostty-vt operations. + */ +typedef enum { + /** Operation completed successfully */ + GHOSTTY_SUCCESS = 0, + /** Operation failed due to failed allocation */ + GHOSTTY_OUT_OF_MEMORY = -1, + /** Operation failed due to invalid value */ + GHOSTTY_INVALID_VALUE = -2, +} GhosttyResult; + +#endif /* GHOSTTY_VT_RESULT_H */ diff --git a/apps/mobile/modules/t3-terminal/Vendor/libghostty/GhosttyKit.xcframework/ios-arm64/Headers/ghostty/vt/sgr.h b/apps/mobile/modules/t3-terminal/Vendor/libghostty/GhosttyKit.xcframework/ios-arm64/Headers/ghostty/vt/sgr.h new file mode 100644 index 0000000000..0c1afc309b --- /dev/null +++ b/apps/mobile/modules/t3-terminal/Vendor/libghostty/GhosttyKit.xcframework/ios-arm64/Headers/ghostty/vt/sgr.h @@ -0,0 +1,394 @@ +/** + * @file sgr.h + * + * SGR (Select Graphic Rendition) attribute parsing and handling. + */ + +#ifndef GHOSTTY_VT_SGR_H +#define GHOSTTY_VT_SGR_H + +/** @defgroup sgr SGR Parser + * + * SGR (Select Graphic Rendition) attribute parser. + * + * SGR sequences are the syntax used to set styling attributes such as + * bold, italic, underline, and colors for text in terminal emulators. + * For example, you may be familiar with sequences like `ESC[1;31m`. The + * `1;31` is the SGR attribute list. + * + * The parser processes SGR parameters from CSI sequences (e.g., `ESC[1;31m`) + * and returns individual text attributes like bold, italic, colors, etc. + * It supports both semicolon (`;`) and colon (`:`) separators, possibly mixed, + * and handles various color formats including 8-color, 16-color, 256-color, + * X11 named colors, and RGB in multiple formats. + * + * ## Basic Usage + * + * 1. Create a parser instance with ghostty_sgr_new() + * 2. Set SGR parameters with ghostty_sgr_set_params() + * 3. Iterate through attributes using ghostty_sgr_next() + * 4. Free the parser with ghostty_sgr_free() when done + * + * ## Example + * + * @code{.c} + * #include + * #include + * #include + * + * int main() { + * // Create parser + * GhosttySgrParser parser; + * GhosttyResult result = ghostty_sgr_new(NULL, &parser); + * assert(result == GHOSTTY_SUCCESS); + * + * // Parse "bold, red foreground" sequence: ESC[1;31m + * uint16_t params[] = {1, 31}; + * result = ghostty_sgr_set_params(parser, params, NULL, 2); + * assert(result == GHOSTTY_SUCCESS); + * + * // Iterate through attributes + * GhosttySgrAttribute attr; + * while (ghostty_sgr_next(parser, &attr)) { + * switch (attr.tag) { + * case GHOSTTY_SGR_ATTR_BOLD: + * printf("Bold enabled\n"); + * break; + * case GHOSTTY_SGR_ATTR_FG_8: + * printf("Foreground color: %d\n", attr.value.fg_8); + * break; + * default: + * break; + * } + * } + * + * // Cleanup + * ghostty_sgr_free(parser); + * return 0; + * } + * @endcode + * + * @{ + */ + +#include +#include +#include +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * Opaque handle to an SGR parser instance. + * + * This handle represents an SGR (Select Graphic Rendition) parser that can + * be used to parse SGR sequences and extract individual text attributes. + * + * @ingroup sgr + */ +typedef struct GhosttySgrParser* GhosttySgrParser; + +/** + * SGR attribute tags. + * + * These values identify the type of an SGR attribute in a tagged union. + * Use the tag to determine which field in the attribute value union to access. + * + * @ingroup sgr + */ +typedef enum { + GHOSTTY_SGR_ATTR_UNSET = 0, + GHOSTTY_SGR_ATTR_UNKNOWN = 1, + GHOSTTY_SGR_ATTR_BOLD = 2, + GHOSTTY_SGR_ATTR_RESET_BOLD = 3, + GHOSTTY_SGR_ATTR_ITALIC = 4, + GHOSTTY_SGR_ATTR_RESET_ITALIC = 5, + GHOSTTY_SGR_ATTR_FAINT = 6, + GHOSTTY_SGR_ATTR_UNDERLINE = 7, + GHOSTTY_SGR_ATTR_RESET_UNDERLINE = 8, + GHOSTTY_SGR_ATTR_UNDERLINE_COLOR = 9, + GHOSTTY_SGR_ATTR_UNDERLINE_COLOR_256 = 10, + GHOSTTY_SGR_ATTR_RESET_UNDERLINE_COLOR = 11, + GHOSTTY_SGR_ATTR_OVERLINE = 12, + GHOSTTY_SGR_ATTR_RESET_OVERLINE = 13, + GHOSTTY_SGR_ATTR_BLINK = 14, + GHOSTTY_SGR_ATTR_RESET_BLINK = 15, + GHOSTTY_SGR_ATTR_INVERSE = 16, + GHOSTTY_SGR_ATTR_RESET_INVERSE = 17, + GHOSTTY_SGR_ATTR_INVISIBLE = 18, + GHOSTTY_SGR_ATTR_RESET_INVISIBLE = 19, + GHOSTTY_SGR_ATTR_STRIKETHROUGH = 20, + GHOSTTY_SGR_ATTR_RESET_STRIKETHROUGH = 21, + GHOSTTY_SGR_ATTR_DIRECT_COLOR_FG = 22, + GHOSTTY_SGR_ATTR_DIRECT_COLOR_BG = 23, + GHOSTTY_SGR_ATTR_BG_8 = 24, + GHOSTTY_SGR_ATTR_FG_8 = 25, + GHOSTTY_SGR_ATTR_RESET_FG = 26, + GHOSTTY_SGR_ATTR_RESET_BG = 27, + GHOSTTY_SGR_ATTR_BRIGHT_BG_8 = 28, + GHOSTTY_SGR_ATTR_BRIGHT_FG_8 = 29, + GHOSTTY_SGR_ATTR_BG_256 = 30, + GHOSTTY_SGR_ATTR_FG_256 = 31, +} GhosttySgrAttributeTag; + +/** + * Underline style types. + * + * @ingroup sgr + */ +typedef enum { + GHOSTTY_SGR_UNDERLINE_NONE = 0, + GHOSTTY_SGR_UNDERLINE_SINGLE = 1, + GHOSTTY_SGR_UNDERLINE_DOUBLE = 2, + GHOSTTY_SGR_UNDERLINE_CURLY = 3, + GHOSTTY_SGR_UNDERLINE_DOTTED = 4, + GHOSTTY_SGR_UNDERLINE_DASHED = 5, +} GhosttySgrUnderline; + +/** + * Unknown SGR attribute data. + * + * Contains the full parameter list and the partial list where parsing + * encountered an unknown or invalid sequence. + * + * @ingroup sgr + */ +typedef struct { + const uint16_t* full_ptr; + size_t full_len; + const uint16_t* partial_ptr; + size_t partial_len; +} GhosttySgrUnknown; + +/** + * SGR attribute value union. + * + * This union contains all possible attribute values. Use the tag field + * to determine which union member is active. Attributes without associated + * data (like bold, italic) don't use the union value. + * + * @ingroup sgr + */ +typedef union { + GhosttySgrUnknown unknown; + GhosttySgrUnderline underline; + GhosttyColorRgb underline_color; + GhosttyColorPaletteIndex underline_color_256; + GhosttyColorRgb direct_color_fg; + GhosttyColorRgb direct_color_bg; + GhosttyColorPaletteIndex bg_8; + GhosttyColorPaletteIndex fg_8; + GhosttyColorPaletteIndex bright_bg_8; + GhosttyColorPaletteIndex bright_fg_8; + GhosttyColorPaletteIndex bg_256; + GhosttyColorPaletteIndex fg_256; + uint64_t _padding[8]; +} GhosttySgrAttributeValue; + +/** + * SGR attribute (tagged union). + * + * A complete SGR attribute with both its type tag and associated value. + * Always check the tag field to determine which value union member is valid. + * + * Attributes without associated data (e.g., GHOSTTY_SGR_ATTR_BOLD) can be + * identified by tag alone; the value union is not used for these and + * the memory in the value field is undefined. + * + * @ingroup sgr + */ +typedef struct { + GhosttySgrAttributeTag tag; + GhosttySgrAttributeValue value; +} GhosttySgrAttribute; + +/** + * Create a new SGR parser instance. + * + * Creates a new SGR (Select Graphic Rendition) parser using the provided + * allocator. The parser must be freed using ghostty_sgr_free() when + * no longer needed. + * + * @param allocator Pointer to the allocator to use for memory management, or + * NULL to use the default allocator + * @param parser Pointer to store the created parser handle + * @return GHOSTTY_SUCCESS on success, or an error code on failure + * + * @ingroup sgr + */ +GhosttyResult ghostty_sgr_new(const GhosttyAllocator* allocator, + GhosttySgrParser* parser); + +/** + * Free an SGR parser instance. + * + * Releases all resources associated with the SGR parser. After this call, + * the parser handle becomes invalid and must not be used. This includes + * any attributes previously returned by ghostty_sgr_next(). + * + * @param parser The parser handle to free (may be NULL) + * + * @ingroup sgr + */ +void ghostty_sgr_free(GhosttySgrParser parser); + +/** + * Reset an SGR parser instance to the beginning of the parameter list. + * + * Resets the parser's iteration state without clearing the parameters. + * After calling this, ghostty_sgr_next() will start from the beginning + * of the parameter list again. + * + * @param parser The parser handle to reset, must not be NULL + * + * @ingroup sgr + */ +void ghostty_sgr_reset(GhosttySgrParser parser); + +/** + * Set SGR parameters for parsing. + * + * Sets the SGR parameter list to parse. Parameters are the numeric values + * from a CSI SGR sequence (e.g., for `ESC[1;31m`, params would be {1, 31}). + * + * The separators array optionally specifies the separator type for each + * parameter position. Each byte should be either ';' for semicolon or ':' + * for colon. This is needed for certain color formats that use colon + * separators (e.g., `ESC[4:3m` for curly underline). Any invalid separator + * values are treated as semicolons. The separators array must have the same + * length as the params array, if it is not NULL. + * + * If separators is NULL, all parameters are assumed to be semicolon-separated. + * + * This function makes an internal copy of the parameter and separator data, + * so the caller can safely free or modify the input arrays after this call. + * + * After calling this function, the parser is automatically reset and ready + * to iterate from the beginning. + * + * @param parser The parser handle, must not be NULL + * @param params Array of SGR parameter values + * @param separators Optional array of separator characters (';' or ':'), or + * NULL + * @param len Number of parameters (and separators if provided) + * @return GHOSTTY_SUCCESS on success, or an error code on failure + * + * @ingroup sgr + */ +GhosttyResult ghostty_sgr_set_params(GhosttySgrParser parser, + const uint16_t* params, + const char* separators, + size_t len); + +/** + * Get the next SGR attribute. + * + * Parses and returns the next attribute from the parameter list. + * Call this function repeatedly until it returns false to process + * all attributes in the sequence. + * + * @param parser The parser handle, must not be NULL + * @param attr Pointer to store the next attribute + * @return true if an attribute was returned, false if no more attributes + * + * @ingroup sgr + */ +bool ghostty_sgr_next(GhosttySgrParser parser, GhosttySgrAttribute* attr); + +/** + * Get the full parameter list from an unknown SGR attribute. + * + * This function retrieves the full parameter list that was provided to the + * parser when an unknown attribute was encountered. Primarily useful in + * WebAssembly environments where accessing struct fields directly is difficult. + * + * @param unknown The unknown attribute data + * @param ptr Pointer to store the pointer to the parameter array (may be NULL) + * @return The length of the full parameter array + * + * @ingroup sgr + */ +size_t ghostty_sgr_unknown_full(GhosttySgrUnknown unknown, + const uint16_t** ptr); + +/** + * Get the partial parameter list from an unknown SGR attribute. + * + * This function retrieves the partial parameter list where parsing stopped + * when an unknown attribute was encountered. Primarily useful in WebAssembly + * environments where accessing struct fields directly is difficult. + * + * @param unknown The unknown attribute data + * @param ptr Pointer to store the pointer to the parameter array (may be NULL) + * @return The length of the partial parameter array + * + * @ingroup sgr + */ +size_t ghostty_sgr_unknown_partial(GhosttySgrUnknown unknown, + const uint16_t** ptr); + +/** + * Get the tag from an SGR attribute. + * + * This function extracts the tag that identifies which type of attribute + * this is. Primarily useful in WebAssembly environments where accessing + * struct fields directly is difficult. + * + * @param attr The SGR attribute + * @return The attribute tag + * + * @ingroup sgr + */ +GhosttySgrAttributeTag ghostty_sgr_attribute_tag(GhosttySgrAttribute attr); + +/** + * Get the value from an SGR attribute. + * + * This function returns a pointer to the value union from an SGR attribute. Use + * the tag to determine which field of the union is valid. Primarily useful in + * WebAssembly environments where accessing struct fields directly is difficult. + * + * @param attr Pointer to the SGR attribute + * @return Pointer to the attribute value union + * + * @ingroup sgr + */ +GhosttySgrAttributeValue* ghostty_sgr_attribute_value( + GhosttySgrAttribute* attr); + +#ifdef __wasm__ +/** + * Allocate memory for an SGR attribute (WebAssembly only). + * + * This is a convenience function for WebAssembly environments to allocate + * memory for an SGR attribute structure that can be passed to ghostty_sgr_next. + * + * @return Pointer to the allocated attribute structure + * + * @ingroup wasm + */ +GhosttySgrAttribute* ghostty_wasm_alloc_sgr_attribute(void); + +/** + * Free memory for an SGR attribute (WebAssembly only). + * + * Frees memory allocated by ghostty_wasm_alloc_sgr_attribute. + * + * @param attr Pointer to the attribute structure to free + * + * @ingroup wasm + */ +void ghostty_wasm_free_sgr_attribute(GhosttySgrAttribute* attr); +#endif + +#ifdef __cplusplus +} +#endif + +/** @} */ + +#endif /* GHOSTTY_VT_SGR_H */ diff --git a/apps/mobile/modules/t3-terminal/Vendor/libghostty/GhosttyKit.xcframework/ios-arm64/Headers/ghostty/vt/wasm.h b/apps/mobile/modules/t3-terminal/Vendor/libghostty/GhosttyKit.xcframework/ios-arm64/Headers/ghostty/vt/wasm.h new file mode 100644 index 0000000000..37a8263265 --- /dev/null +++ b/apps/mobile/modules/t3-terminal/Vendor/libghostty/GhosttyKit.xcframework/ios-arm64/Headers/ghostty/vt/wasm.h @@ -0,0 +1,159 @@ +/** + * @file wasm.h + * + * WebAssembly utility functions for libghostty-vt. + */ + +#ifndef GHOSTTY_VT_WASM_H +#define GHOSTTY_VT_WASM_H + +#ifdef __wasm__ + +#include +#include + +/** @defgroup wasm WebAssembly Utilities + * + * Convenience functions for allocating various types in WebAssembly builds. + * **These are only available the libghostty-vt wasm module.** + * + * Ghostty relies on pointers to various types for ABI compatibility, and + * creating those pointers in Wasm can be tedious. These functions provide + * a purely additive set of utilities that simplify memory management in + * Wasm environments without changing the core C library API. + * + * @note These functions always use the default allocator. If you need + * custom allocation strategies, you should allocate types manually using + * your custom allocator. This is a very rare use case in the WebAssembly + * world so these are optimized for simplicity. + * + * ## Example Usage + * + * Here's a simple example of using the Wasm utilities with the key encoder: + * + * @code + * const { exports } = wasmInstance; + * const view = new DataView(wasmMemory.buffer); + * + * // Create key encoder + * const encoderPtr = exports.ghostty_wasm_alloc_opaque(); + * exports.ghostty_key_encoder_new(null, encoderPtr); + * const encoder = view.getUint32(encoder, true); + * + * // Configure encoder with Kitty protocol flags + * const flagsPtr = exports.ghostty_wasm_alloc_u8(); + * view.setUint8(flagsPtr, 0x1F); + * exports.ghostty_key_encoder_setopt(encoder, 5, flagsPtr); + * + * // Allocate output buffer and size pointer + * const bufferSize = 32; + * const bufPtr = exports.ghostty_wasm_alloc_u8_array(bufferSize); + * const writtenPtr = exports.ghostty_wasm_alloc_usize(); + * + * // Encode the key event + * exports.ghostty_key_encoder_encode( + * encoder, eventPtr, bufPtr, bufferSize, writtenPtr + * ); + * + * // Read encoded output + * const bytesWritten = view.getUint32(writtenPtr, true); + * const encoded = new Uint8Array(wasmMemory.buffer, bufPtr, bytesWritten); + * @endcode + * + * @remark The code above is pretty ugly! This is the lowest level interface + * to the libghostty-vt Wasm module. In practice, this should be wrapped + * in a higher-level API that abstracts away all this. + * + * @{ + */ + +/** + * Allocate an opaque pointer. This can be used for any opaque pointer + * types such as GhosttyKeyEncoder, GhosttyKeyEvent, etc. + * + * @return Pointer to allocated opaque pointer, or NULL if allocation failed + * @ingroup wasm + */ +void** ghostty_wasm_alloc_opaque(void); + +/** + * Free an opaque pointer allocated by ghostty_wasm_alloc_opaque(). + * + * @param ptr Pointer to free, or NULL (NULL is safely ignored) + * @ingroup wasm + */ +void ghostty_wasm_free_opaque(void **ptr); + +/** + * Allocate an array of uint8_t values. + * + * @param len Number of uint8_t elements to allocate + * @return Pointer to allocated array, or NULL if allocation failed + * @ingroup wasm + */ +uint8_t* ghostty_wasm_alloc_u8_array(size_t len); + +/** + * Free an array allocated by ghostty_wasm_alloc_u8_array(). + * + * @param ptr Pointer to the array to free, or NULL (NULL is safely ignored) + * @param len Length of the array (must match the length passed to alloc) + * @ingroup wasm + */ +void ghostty_wasm_free_u8_array(uint8_t *ptr, size_t len); + +/** + * Allocate an array of uint16_t values. + * + * @param len Number of uint16_t elements to allocate + * @return Pointer to allocated array, or NULL if allocation failed + * @ingroup wasm + */ +uint16_t* ghostty_wasm_alloc_u16_array(size_t len); + +/** + * Free an array allocated by ghostty_wasm_alloc_u16_array(). + * + * @param ptr Pointer to the array to free, or NULL (NULL is safely ignored) + * @param len Length of the array (must match the length passed to alloc) + * @ingroup wasm + */ +void ghostty_wasm_free_u16_array(uint16_t *ptr, size_t len); + +/** + * Allocate a single uint8_t value. + * + * @return Pointer to allocated uint8_t, or NULL if allocation failed + * @ingroup wasm + */ +uint8_t* ghostty_wasm_alloc_u8(void); + +/** + * Free a uint8_t allocated by ghostty_wasm_alloc_u8(). + * + * @param ptr Pointer to free, or NULL (NULL is safely ignored) + * @ingroup wasm + */ +void ghostty_wasm_free_u8(uint8_t *ptr); + +/** + * Allocate a single size_t value. + * + * @return Pointer to allocated size_t, or NULL if allocation failed + * @ingroup wasm + */ +size_t* ghostty_wasm_alloc_usize(void); + +/** + * Free a size_t allocated by ghostty_wasm_alloc_usize(). + * + * @param ptr Pointer to free, or NULL (NULL is safely ignored) + * @ingroup wasm + */ +void ghostty_wasm_free_usize(size_t *ptr); + +/** @} */ + +#endif /* __wasm__ */ + +#endif /* GHOSTTY_VT_WASM_H */ diff --git a/apps/mobile/modules/t3-terminal/Vendor/libghostty/GhosttyKit.xcframework/ios-arm64/Headers/module.modulemap b/apps/mobile/modules/t3-terminal/Vendor/libghostty/GhosttyKit.xcframework/ios-arm64/Headers/module.modulemap new file mode 100644 index 0000000000..8961f5c04b --- /dev/null +++ b/apps/mobile/modules/t3-terminal/Vendor/libghostty/GhosttyKit.xcframework/ios-arm64/Headers/module.modulemap @@ -0,0 +1,7 @@ +// This makes Ghostty available to the XCode build for the macOS app. +// We append "Kit" to it not to be cute, but because targets have to have +// unique names and we use Ghostty for other things. +module GhosttyKit { + umbrella header "ghostty.h" + export * +} diff --git a/apps/mobile/modules/t3-terminal/Vendor/libghostty/GhosttyKit.xcframework/ios-arm64/libghostty-fat.a b/apps/mobile/modules/t3-terminal/Vendor/libghostty/GhosttyKit.xcframework/ios-arm64/libghostty-fat.a new file mode 100644 index 0000000000..1d4a14a8d7 Binary files /dev/null and b/apps/mobile/modules/t3-terminal/Vendor/libghostty/GhosttyKit.xcframework/ios-arm64/libghostty-fat.a differ diff --git a/apps/mobile/modules/t3-terminal/Vendor/libghostty/VERSION b/apps/mobile/modules/t3-terminal/Vendor/libghostty/VERSION new file mode 100644 index 0000000000..3ea8487fe0 --- /dev/null +++ b/apps/mobile/modules/t3-terminal/Vendor/libghostty/VERSION @@ -0,0 +1 @@ +268a0a9d761fb19673f05d28042488e2002300f2 diff --git a/apps/mobile/modules/t3-terminal/android/build.gradle b/apps/mobile/modules/t3-terminal/android/build.gradle new file mode 100644 index 0000000000..90c0d4fc21 --- /dev/null +++ b/apps/mobile/modules/t3-terminal/android/build.gradle @@ -0,0 +1,19 @@ +apply plugin: 'com.android.library' +apply plugin: 'org.jetbrains.kotlin.android' + +group = 'com.t3tools.terminal' +version = '0.0.0' + +android { + namespace 'expo.modules.t3terminal' + compileSdk rootProject.ext.compileSdkVersion + + defaultConfig { + minSdkVersion rootProject.ext.minSdkVersion + targetSdkVersion rootProject.ext.targetSdkVersion + } +} + +dependencies { + implementation project(':expo-modules-core') +} diff --git a/apps/mobile/modules/t3-terminal/android/src/main/AndroidManifest.xml b/apps/mobile/modules/t3-terminal/android/src/main/AndroidManifest.xml new file mode 100644 index 0000000000..94cbbcfc39 --- /dev/null +++ b/apps/mobile/modules/t3-terminal/android/src/main/AndroidManifest.xml @@ -0,0 +1 @@ + diff --git a/apps/mobile/modules/t3-terminal/android/src/main/java/expo/modules/t3terminal/T3TerminalModule.kt b/apps/mobile/modules/t3-terminal/android/src/main/java/expo/modules/t3terminal/T3TerminalModule.kt new file mode 100644 index 0000000000..abb3982be1 --- /dev/null +++ b/apps/mobile/modules/t3-terminal/android/src/main/java/expo/modules/t3terminal/T3TerminalModule.kt @@ -0,0 +1,46 @@ +package expo.modules.t3terminal + +import expo.modules.kotlin.modules.Module +import expo.modules.kotlin.modules.ModuleDefinition + +class T3TerminalModule : Module() { + override fun definition() = ModuleDefinition { + Name("T3TerminalSurface") + + View(T3TerminalView::class) { + Prop("terminalKey") { view: T3TerminalView, terminalKey: String -> + view.terminalKey = terminalKey + } + + Prop("initialBuffer") { view: T3TerminalView, initialBuffer: String -> + view.initialBuffer = initialBuffer + } + + Prop("fontSize") { view: T3TerminalView, fontSize: Double -> + view.fontSize = fontSize.toFloat() + } + + Prop("appearanceScheme") { view: T3TerminalView, appearanceScheme: String -> + view.appearanceScheme = appearanceScheme + } + + Prop("themeConfig") { view: T3TerminalView, themeConfig: String -> + view.themeConfig = themeConfig + } + + Prop("backgroundColor") { view: T3TerminalView, backgroundColor: String -> + view.backgroundColorHex = backgroundColor + } + + Prop("foregroundColor") { view: T3TerminalView, foregroundColor: String -> + view.foregroundColorHex = foregroundColor + } + + Prop("mutedForegroundColor") { view: T3TerminalView, mutedForegroundColor: String -> + view.mutedForegroundColorHex = mutedForegroundColor + } + + Events("onInput", "onResize") + } + } +} diff --git a/apps/mobile/modules/t3-terminal/android/src/main/java/expo/modules/t3terminal/T3TerminalView.kt b/apps/mobile/modules/t3-terminal/android/src/main/java/expo/modules/t3terminal/T3TerminalView.kt new file mode 100644 index 0000000000..2b785b79c4 --- /dev/null +++ b/apps/mobile/modules/t3-terminal/android/src/main/java/expo/modules/t3terminal/T3TerminalView.kt @@ -0,0 +1,210 @@ +package expo.modules.t3terminal + +import android.content.Context +import android.graphics.Color +import android.graphics.Typeface +import android.view.View +import android.view.ViewGroup +import android.view.inputmethod.InputMethodManager +import android.view.inputmethod.EditorInfo +import android.widget.EditText +import android.widget.LinearLayout +import android.widget.ScrollView +import android.widget.TextView +import androidx.core.widget.doAfterTextChanged +import expo.modules.kotlin.AppContext +import expo.modules.kotlin.views.ExpoView +import expo.modules.kotlin.viewevent.EventDispatcher +import kotlin.math.max +import kotlin.math.min + +class T3TerminalView(context: Context, appContext: AppContext) : ExpoView(context, appContext) { + private val container = LinearLayout(context) + private val scrollView = ScrollView(context) + private val textView = TextView(context) + private val inputView = EditText(context) + private val onInput by EventDispatcher() + private val onResize by EventDispatcher() + private var lastWidth = 0 + private var lastHeight = 0 + private var clearingInput = false + private var backgroundColorValue = Color.parseColor("#24292E") + private var foregroundColorValue = Color.parseColor("#D1D5DA") + private var mutedForegroundColorValue = Color.parseColor("#959DA5") + + var terminalKey: String = "" + set(value) { + field = value + contentDescription = "t3-terminal-$value" + } + + var initialBuffer: String = "" + set(value) { + field = value + textView.text = value.ifEmpty { "$ " } + scrollView.post { + scrollView.fullScroll(View.FOCUS_DOWN) + } + } + + var fontSize: Float = 12f + set(value) { + field = value + textView.textSize = value + emitResize() + } + + var appearanceScheme: String = "dark" + set(value) { + field = value + } + + var themeConfig: String = "" + + var backgroundColorHex: String = "#24292E" + set(value) { + field = value + backgroundColorValue = parseColor(value, backgroundColorValue) + applyTheme() + } + + var foregroundColorHex: String = "#D1D5DA" + set(value) { + field = value + foregroundColorValue = parseColor(value, foregroundColorValue) + applyTheme() + } + + var mutedForegroundColorHex: String = "#959DA5" + set(value) { + field = value + mutedForegroundColorValue = parseColor(value, mutedForegroundColorValue) + applyTheme() + } + + init { + applyTheme() + container.orientation = LinearLayout.VERTICAL + textView.typeface = Typeface.MONOSPACE + textView.textSize = fontSize + textView.setPadding(8, 8, 8, 8) + textView.text = "$ " + + inputView.setSingleLine(true) + inputView.setTextColor(Color.TRANSPARENT) + inputView.setHintTextColor(Color.TRANSPARENT) + inputView.setBackgroundColor(Color.TRANSPARENT) + inputView.typeface = Typeface.MONOSPACE + inputView.textSize = max(fontSize, 13f) + inputView.hint = "" + inputView.alpha = 0.02f + inputView.imeOptions = EditorInfo.IME_ACTION_SEND + inputView.setPadding(0, 0, 0, 0) + inputView.setOnFocusChangeListener { _, hasFocus -> + if (hasFocus) { + showKeyboard() + } + } + inputView.setOnEditorActionListener { view, actionId, _ -> + if (actionId != EditorInfo.IME_ACTION_SEND) return@setOnEditorActionListener false + onInput(mapOf("data" to "\n")) + true + } + inputView.setOnKeyListener { _, keyCode, event -> + if (event.action != android.view.KeyEvent.ACTION_DOWN) return@setOnKeyListener false + when (keyCode) { + android.view.KeyEvent.KEYCODE_DEL -> { + onInput(mapOf("data" to "\u007F")) + true + } + else -> false + } + } + inputView.doAfterTextChanged { editable -> + if (clearingInput) return@doAfterTextChanged + val text = editable?.toString().orEmpty() + if (text.isEmpty()) return@doAfterTextChanged + onInput(mapOf("data" to text)) + clearingInput = true + inputView.text?.clear() + clearingInput = false + } + + textView.setOnClickListener { requestKeyboardFocus() } + scrollView.setOnClickListener { requestKeyboardFocus() } + container.setOnClickListener { requestKeyboardFocus() } + isClickable = true + setOnClickListener { requestKeyboardFocus() } + + scrollView.addView( + textView, + LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT), + ) + container.addView( + scrollView, + LinearLayout.LayoutParams( + ViewGroup.LayoutParams.MATCH_PARENT, + 0, + 1f, + ), + ) + container.addView( + inputView, + LinearLayout.LayoutParams(1, 1), + ) + addView( + container, + LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT), + ) + + post { + requestKeyboardFocus() + } + } + + override fun onSizeChanged(width: Int, height: Int, oldWidth: Int, oldHeight: Int) { + super.onSizeChanged(width, height, oldWidth, oldHeight) + if (width == lastWidth && height == lastHeight) return + lastWidth = width + lastHeight = height + emitResize() + } + + private fun emitResize() { + if (width <= 0 || height <= 0) return + val density = resources.displayMetrics.scaledDensity + val fontPx = max(fontSize * density, 1f) + val cols = max(20, min(400, (width / (fontPx * 0.62f)).toInt())) + val terminalHeight = max(height - inputView.height, 0) + val rows = max(5, min(200, (terminalHeight / (fontPx * 1.35f)).toInt())) + onResize(mapOf("cols" to cols, "rows" to rows)) + } + + private fun requestKeyboardFocus() { + inputView.requestFocus() + showKeyboard() + } + + private fun applyTheme() { + setBackgroundColor(backgroundColorValue) + container.setBackgroundColor(backgroundColorValue) + scrollView.setBackgroundColor(backgroundColorValue) + textView.setTextColor(foregroundColorValue) + textView.setBackgroundColor(backgroundColorValue) + inputView.setTextColor(Color.TRANSPARENT) + inputView.setHintTextColor(mutedForegroundColorValue) + inputView.setBackgroundColor(Color.TRANSPARENT) + } + + private fun parseColor(value: String, fallback: Int): Int = + try { + Color.parseColor(value) + } catch (_: IllegalArgumentException) { + fallback + } + + private fun showKeyboard() { + val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager + imm?.showSoftInput(inputView, InputMethodManager.SHOW_IMPLICIT) + } +} diff --git a/apps/mobile/modules/t3-terminal/expo-module.config.json b/apps/mobile/modules/t3-terminal/expo-module.config.json new file mode 100644 index 0000000000..a4b0f11241 --- /dev/null +++ b/apps/mobile/modules/t3-terminal/expo-module.config.json @@ -0,0 +1,10 @@ +{ + "platforms": ["apple", "android"], + "apple": { + "modules": ["T3TerminalModule"], + "podspecPath": "T3TerminalNative.podspec" + }, + "android": { + "modules": ["expo.modules.t3terminal.T3TerminalModule"] + } +} diff --git a/apps/mobile/modules/t3-terminal/ios/T3TerminalModule.swift b/apps/mobile/modules/t3-terminal/ios/T3TerminalModule.swift new file mode 100644 index 0000000000..8f35bcc3aa --- /dev/null +++ b/apps/mobile/modules/t3-terminal/ios/T3TerminalModule.swift @@ -0,0 +1,43 @@ +import ExpoModulesCore + +public class T3TerminalModule: Module { + public func definition() -> ModuleDefinition { + Name("T3TerminalSurface") + + View(T3TerminalView.self) { + Prop("terminalKey") { (view: T3TerminalView, terminalKey: String) in + view.terminalKey = terminalKey + } + + Prop("initialBuffer") { (view: T3TerminalView, initialBuffer: String) in + view.initialBuffer = initialBuffer + } + + Prop("fontSize") { (view: T3TerminalView, fontSize: Double) in + view.fontSize = CGFloat(fontSize) + } + + Prop("appearanceScheme") { (view: T3TerminalView, appearanceScheme: String) in + view.appearanceScheme = appearanceScheme + } + + Prop("themeConfig") { (view: T3TerminalView, themeConfig: String) in + view.themeConfig = themeConfig + } + + Prop("backgroundColor") { (view: T3TerminalView, backgroundColor: String) in + view.backgroundColorHex = backgroundColor + } + + Prop("foregroundColor") { (view: T3TerminalView, foregroundColor: String) in + view.foregroundColorHex = foregroundColor + } + + Prop("mutedForegroundColor") { (view: T3TerminalView, mutedForegroundColor: String) in + view.mutedForegroundColorHex = mutedForegroundColor + } + + Events("onInput", "onResize") + } + } +} diff --git a/apps/mobile/modules/t3-terminal/ios/T3TerminalView.swift b/apps/mobile/modules/t3-terminal/ios/T3TerminalView.swift new file mode 100644 index 0000000000..c3a97a1667 --- /dev/null +++ b/apps/mobile/modules/t3-terminal/ios/T3TerminalView.swift @@ -0,0 +1,565 @@ +import ExpoModulesCore +import Foundation +import GhosttyKit +import QuartzCore +import UIKit + +private enum GhosttyRuntime { + private static let lock = NSLock() + private static var initialized = false + + static func ensureInitialized() -> Bool { + lock.lock() + defer { lock.unlock() } + + if initialized { + return true + } + + let result = ghostty_init(0, nil) + initialized = result == GHOSTTY_SUCCESS + return initialized + } +} + +private final class TerminalInputField: UITextField { + var onDeleteBackward: (() -> Void)? + + override func deleteBackward() { + onDeleteBackward?() + super.deleteBackward() + } +} + +private enum TerminalAppearanceScheme: String { + case light + case dark + + init(value: String) { + self = TerminalAppearanceScheme(rawValue: value) ?? .dark + } + + var ghosttyColorScheme: ghostty_color_scheme_e { + switch self { + case .light: + return GHOSTTY_COLOR_SCHEME_LIGHT + case .dark: + return GHOSTTY_COLOR_SCHEME_DARK + } + } +} + +private extension UIColor { + convenience init(hexString: String) { + let sanitized = hexString.replacingOccurrences(of: "#", with: "") + let value = Int(sanitized, radix: 16) ?? 0 + self.init( + red: CGFloat((value >> 16) & 0xFF) / 255, + green: CGFloat((value >> 8) & 0xFF) / 255, + blue: CGFloat(value & 0xFF) / 255, + alpha: 1 + ) + } +} + +public final class T3TerminalView: ExpoView, UITextFieldDelegate { + private static let minimumVerticalScrollStepPoints: CGFloat = 18 + private static let verticalScrollStepMultiplier: CGFloat = 1.15 + + private let terminalViewport = UIView() + private let inputField = TerminalInputField() + private let focusTapGesture = UITapGestureRecognizer() + private let scrollPanGesture = UIPanGestureRecognizer() + private var lastViewportSize: CGSize = .zero + private var lastContentScale: CGFloat = 0 + private var lastReportedGrid: (cols: Int, rows: Int)? + private var lastAppliedBuffer = "" + private var pendingVerticalScrollPoints: CGFloat = 0 + private var app: ghostty_app_t? + private var surface: ghostty_surface_t? + private var isCreatingSurface = false + private var surfaceCreationFailed = false + private var appearance = TerminalAppearanceScheme.dark + private var backgroundColorValue = UIColor(hexString: "#24292e") + + let onInput = EventDispatcher() + let onResize = EventDispatcher() + + var terminalKey: String = "" { + didSet { + accessibilityIdentifier = "t3-terminal-\(terminalKey)" + if oldValue != terminalKey { + resetSurface() + } + } + } + + var initialBuffer: String = "" { + didSet { + applyRemoteBuffer(initialBuffer) + } + } + + var fontSize: CGFloat = 12 { + didSet { + inputField.font = UIFont.monospacedSystemFont(ofSize: max(fontSize, 13), weight: .regular) + resetSurface() + } + } + + var appearanceScheme: String = TerminalAppearanceScheme.dark.rawValue { + didSet { + appearance = TerminalAppearanceScheme(value: appearanceScheme) + updateGhosttyTheme() + } + } + + var themeConfig: String = "" { + didSet { + updateGhosttyTheme() + } + } + + var backgroundColorHex: String = "#24292e" { + didSet { + backgroundColorValue = UIColor(hexString: backgroundColorHex) + applyTheme() + } + } + + var foregroundColorHex: String = "#d1d5da" + var mutedForegroundColorHex: String = "#959da5" + + public required init(appContext: AppContext? = nil) { + super.init(appContext: appContext) + + applyTheme() + clipsToBounds = true + contentScaleFactor = UIScreen.main.scale + + terminalViewport.clipsToBounds = true + terminalViewport.contentScaleFactor = contentScaleFactor + terminalViewport.translatesAutoresizingMaskIntoConstraints = false + terminalViewport.isUserInteractionEnabled = true + + inputField.delegate = self + inputField.backgroundColor = UIColor.clear + inputField.textColor = UIColor.clear + inputField.tintColor = UIColor.clear + inputField.font = UIFont.monospacedSystemFont(ofSize: max(fontSize, 13), weight: .regular) + inputField.placeholder = "" + inputField.autocorrectionType = .no + inputField.autocapitalizationType = .none + inputField.spellCheckingType = .no + inputField.smartDashesType = .no + inputField.smartQuotesType = .no + inputField.returnKeyType = .send + inputField.keyboardType = .asciiCapable + inputField.enablesReturnKeyAutomatically = false + inputField.translatesAutoresizingMaskIntoConstraints = false + inputField.alpha = 0.02 + inputField.isAccessibilityElement = false + inputField.accessibilityElementsHidden = true + inputField.addTarget(self, action: #selector(handleInputEditingDidBegin), for: .editingDidBegin) + inputField.onDeleteBackward = { [weak self] in + self?.emitInput("\u{7F}") + } + + focusTapGesture.addTarget(self, action: #selector(handleViewportTap)) + terminalViewport.addGestureRecognizer(focusTapGesture) + scrollPanGesture.addTarget(self, action: #selector(handleViewportPan(_:))) + scrollPanGesture.maximumNumberOfTouches = 1 + scrollPanGesture.cancelsTouchesInView = false + terminalViewport.addGestureRecognizer(scrollPanGesture) + + addSubview(terminalViewport) + addSubview(inputField) + + NSLayoutConstraint.activate([ + terminalViewport.leadingAnchor.constraint(equalTo: leadingAnchor), + terminalViewport.trailingAnchor.constraint(equalTo: trailingAnchor), + terminalViewport.topAnchor.constraint(equalTo: topAnchor), + terminalViewport.bottomAnchor.constraint(equalTo: bottomAnchor), + + inputField.trailingAnchor.constraint(equalTo: trailingAnchor), + inputField.topAnchor.constraint(equalTo: bottomAnchor, constant: 8), + inputField.widthAnchor.constraint(equalToConstant: 1), + inputField.heightAnchor.constraint(equalToConstant: 1), + ]) + } + + deinit { + destroySurface() + } + + public override func layoutSubviews() { + super.layoutSubviews() + updateContentScale() + + let viewportSize = terminalViewport.bounds.size + if surface == nil { + createSurfaceIfPossible() + } + + guard viewportSize != lastViewportSize || contentScaleFactor != lastContentScale else { + return + } + + lastViewportSize = viewportSize + lastContentScale = contentScaleFactor + resizeSurface() + } + + public override func didMoveToWindow() { + super.didMoveToWindow() + + guard window != nil else { return } + DispatchQueue.main.async { [weak self] in + self?.requestKeyboardFocus() + } + } + + public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { + if !string.isEmpty { + emitInput(string) + return false + } + + return false + } + + public func textFieldShouldReturn(_ textField: UITextField) -> Bool { + emitInput("\n") + textField.text = "" + return false + } + + @objc + private func handleViewportTap() { + requestKeyboardFocus() + } + + @objc + private func handleViewportPan(_ gesture: UIPanGestureRecognizer) { + guard let surface else { return } + + let location = gesture.location(in: terminalViewport) + ghostty_surface_mouse_pos( + surface, + Double(location.x * contentScaleFactor), + Double(location.y * contentScaleFactor), + GHOSTTY_MODS_NONE + ) + + switch gesture.state { + case .began: + pendingVerticalScrollPoints = 0 + gesture.setTranslation(.zero, in: terminalViewport) + case .changed: + let translation = gesture.translation(in: terminalViewport) + let stepSize = max( + fontSize * Self.verticalScrollStepMultiplier, + Self.minimumVerticalScrollStepPoints + ) + let totalVerticalPoints = pendingVerticalScrollPoints + translation.y + let verticalSteps = Int(totalVerticalPoints / stepSize) + pendingVerticalScrollPoints = totalVerticalPoints - (CGFloat(verticalSteps) * stepSize) + + guard verticalSteps != 0 else { + gesture.setTranslation(.zero, in: terminalViewport) + return + } + + ghostty_surface_mouse_scroll(surface, 0, Double(verticalSteps), 0) + redrawSurface() + gesture.setTranslation(.zero, in: terminalViewport) + default: + pendingVerticalScrollPoints = 0 + gesture.setTranslation(.zero, in: terminalViewport) + } + } + + @objc + private func handleInputEditingDidBegin() { + textInputModeDidChange() + } + + private func createSurfaceIfPossible() { + guard surface == nil, app == nil, !isCreatingSurface, !surfaceCreationFailed else { return } + guard terminalViewport.bounds.width > 0, terminalViewport.bounds.height > 0 else { return } + guard GhosttyRuntime.ensureInitialized() else { + surfaceCreationFailed = true + return + } + + isCreatingSurface = true + defer { isCreatingSurface = false } + + var runtimeConfig = ghostty_runtime_config_s( + userdata: Unmanaged.passUnretained(self).toOpaque(), + supports_selection_clipboard: false, + wakeup_cb: { _ in }, + action_cb: { _, _, _ in false }, + read_clipboard_cb: { _, _, _ in }, + confirm_read_clipboard_cb: { _, _, _, _ in }, + write_clipboard_cb: { _, _, _, _, _ in }, + close_surface_cb: { _, _ in } + ) + + guard let config = ghostty_config_new() else { + surfaceCreationFailed = true + return + } + loadThemeConfig(into: config) + ghostty_config_finalize(config) + defer { ghostty_config_free(config) } + + guard let createdApp = ghostty_app_new(&runtimeConfig, config) else { + surfaceCreationFailed = true + return + } + + var surfaceConfig = ghostty_surface_config_new() + surfaceConfig.platform_tag = GHOSTTY_PLATFORM_IOS + surfaceConfig.platform.ios.uiview = Unmanaged.passUnretained(terminalViewport).toOpaque() + surfaceConfig.userdata = Unmanaged.passUnretained(self).toOpaque() + surfaceConfig.scale_factor = Double(contentScaleFactor) + surfaceConfig.font_size = Float(fontSize) + surfaceConfig.context = GHOSTTY_SURFACE_CONTEXT_WINDOW + surfaceConfig.use_custom_io = true + + guard let createdSurface = ghostty_surface_new(createdApp, &surfaceConfig) else { + ghostty_app_free(createdApp) + surfaceCreationFailed = true + return + } + + app = createdApp + surface = createdSurface + ghostty_app_set_color_scheme(createdApp, appearance.ghosttyColorScheme) + ghostty_surface_set_color_scheme(createdSurface, appearance.ghosttyColorScheme) + setupWriteCallback() + resizeSurface() + feedBuffer(initialBuffer) + } + + private func resetSurface() { + destroySurface() + lastAppliedBuffer = "" + lastViewportSize = .zero + lastContentScale = 0 + lastReportedGrid = nil + surfaceCreationFailed = false + setNeedsLayout() + } + + private func destroySurface() { + if let surface { + ghostty_surface_set_write_callback(surface, nil, nil) + ghostty_surface_free(surface) + } + if let app { + ghostty_app_free(app) + } + surface = nil + app = nil + } + + private func applyRemoteBuffer(_ buffer: String) { + guard surface != nil else { + createSurfaceIfPossible() + return + } + + if buffer.hasPrefix(lastAppliedBuffer) { + let suffix = String(buffer.dropFirst(lastAppliedBuffer.count)) + feedData(Data(suffix.utf8)) + lastAppliedBuffer = buffer + return + } + + resetSurface() + createSurfaceIfPossible() + } + + private func feedBuffer(_ buffer: String) { + guard !buffer.isEmpty else { return } + feedData(Data(buffer.utf8)) + lastAppliedBuffer = buffer + } + + private func feedData(_ data: Data) { + guard let surface, !data.isEmpty else { return } + + data.withUnsafeBytes { buffer in + guard let pointer = buffer.baseAddress?.assumingMemoryBound(to: UInt8.self) else { + return + } + ghostty_surface_feed_data(surface, pointer, buffer.count) + } + + redrawSurface() + } + + private func setupWriteCallback() { + guard let surface else { return } + + let userdata = Unmanaged.passUnretained(self).toOpaque() + ghostty_surface_set_write_callback(surface, { userdata, data, len in + guard let userdata, let data, len > 0 else { return } + let view = Unmanaged.fromOpaque(userdata).takeUnretainedValue() + let bytes = Data(bytes: data, count: len) + guard let input = String(data: bytes, encoding: .utf8), !input.isEmpty else { return } + + DispatchQueue.main.async { + view.onInput(["data": input]) + } + }, userdata) + } + + private func resizeSurface() { + guard let surface else { + emitEstimatedResize() + return + } + + let scale = contentScaleFactor + let width = UInt32(max(floor(terminalViewport.bounds.width * scale), 1)) + let height = UInt32(max(floor(terminalViewport.bounds.height * scale), 1)) + + terminalViewport.contentScaleFactor = scale + ghostty_surface_set_content_scale(surface, Double(scale), Double(scale)) + ghostty_surface_set_size(surface, width, height) + ghostty_surface_set_occlusion(surface, window != nil) + configureIOSurfaceLayers() + redrawSurface() + emitGhosttyResize() + } + + private func redrawSurface() { + guard let surface else { return } + ghostty_surface_refresh(surface) + ghostty_surface_draw(surface) + markIOSurfaceLayersForDisplay() + emitGhosttyResize() + } + + private func emitGhosttyResize() { + guard let surface else { + emitEstimatedResize() + return + } + + let size = ghostty_surface_size(surface) + let cols = max(1, Int(size.columns)) + let rows = max(1, Int(size.rows)) + emitResize(cols: cols, rows: rows) + } + + private func emitEstimatedResize() { + guard bounds.width > 0, bounds.height > 0 else { return } + + let cellWidth = max(fontSize * 0.62, 1) + let cellHeight = max(fontSize * 1.35, 1) + let cols = max(20, min(400, Int(bounds.width / cellWidth))) + let terminalHeight = max(bounds.height, 0) + let rows = max(5, min(200, Int(terminalHeight / cellHeight))) + emitResize(cols: cols, rows: rows) + } + + private func emitResize(cols: Int, rows: Int) { + guard lastReportedGrid?.cols != cols || lastReportedGrid?.rows != rows else { + return + } + + lastReportedGrid = (cols, rows) + onResize([ + "cols": cols, + "rows": rows, + ]) + } + + private func updateContentScale() { + let scale = window?.screen.scale ?? UIScreen.main.scale + if contentScaleFactor != scale { + contentScaleFactor = scale + } + } + + private func requestKeyboardFocus() { + guard window != nil else { return } + inputField.becomeFirstResponder() + textInputModeDidChange() + } + + private func emitInput(_ data: String) { + guard !data.isEmpty else { return } + onInput(["data": data]) + } + + private func textInputModeDidChange() { + guard let app else { return } + ghostty_app_keyboard_changed(app) + } + + private func configureIOSurfaceLayers() { + let targetBounds = CGRect(origin: .zero, size: terminalViewport.bounds.size) + CATransaction.begin() + CATransaction.setDisableActions(true) + terminalViewport.layer.sublayers?.forEach { sublayer in + sublayer.frame = targetBounds + sublayer.contentsScale = contentScaleFactor + } + CATransaction.commit() + } + + private func markIOSurfaceLayersForDisplay() { + terminalViewport.layer.setNeedsDisplay() + terminalViewport.layer.sublayers?.forEach { layer in + layer.setNeedsDisplay() + } + } + + private func applyTheme() { + backgroundColor = backgroundColorValue + terminalViewport.backgroundColor = backgroundColorValue + } + + private func updateGhosttyTheme() { + guard let app, let surface else { return } + guard let config = ghostty_config_new() else { return } + loadThemeConfig(into: config) + ghostty_config_finalize(config) + ghostty_app_update_config(app, config) + ghostty_surface_update_config(surface, config) + ghostty_app_set_color_scheme(app, appearance.ghosttyColorScheme) + ghostty_surface_set_color_scheme(surface, appearance.ghosttyColorScheme) + ghostty_config_free(config) + redrawSurface() + } + + private func loadThemeConfig(into config: ghostty_config_t) { + guard let path = writeThemeConfigFile() else { return } + path.withCString { cString in + ghostty_config_load_file(config, cString) + } + } + + private func writeThemeConfigFile() -> String? { + guard !themeConfig.isEmpty else { return nil } + let configContents = themeConfig + let url = URL(fileURLWithPath: NSTemporaryDirectory()) + .appendingPathComponent("t3-terminal-theme-\(appearance.rawValue).ghostty") + + do { + if let existing = try? String(contentsOf: url, encoding: .utf8), existing == configContents { + return url.path + } + + try configContents.write(to: url, atomically: true, encoding: .utf8) + return url.path + } catch { + return nil + } + } +} diff --git a/apps/mobile/modules/t3-terminal/package.json b/apps/mobile/modules/t3-terminal/package.json new file mode 100644 index 0000000000..d658be1a21 --- /dev/null +++ b/apps/mobile/modules/t3-terminal/package.json @@ -0,0 +1,17 @@ +{ + "name": "@t3tools/mobile-terminal-native", + "version": "0.0.0", + "private": true, + "expo-module": { + "ios": { + "modules": [ + "T3TerminalModule" + ] + }, + "android": { + "modules": [ + "expo.modules.t3terminal.T3TerminalModule" + ] + } + } +} diff --git a/apps/mobile/package.json b/apps/mobile/package.json index 526fc62210..08329e1d41 100644 --- a/apps/mobile/package.json +++ b/apps/mobile/package.json @@ -30,6 +30,7 @@ "config:dev": "APP_VARIANT=development expo config", "config:preview": "APP_VARIANT=preview expo config", "config:prod": "APP_VARIANT=production expo config", + "test": "vitest run", "typecheck": "tsc --noEmit" }, "dependencies": { @@ -45,11 +46,13 @@ "@shikijs/themes": "3.23.0", "@t3tools/client-runtime": "workspace:*", "@t3tools/contracts": "workspace:*", + "@t3tools/mobile-terminal-native": "file:./modules/t3-terminal", "@t3tools/shared": "workspace:*", "clsx": "^2.1.1", "diff": "8.0.3", "effect": "catalog:", "expo": "~55.0.14", + "expo-build-properties": "~55.0.13", "expo-camera": "~55.0.15", "expo-clipboard": "~55.0.9", "expo-constants": "^55.0.9", @@ -60,6 +63,7 @@ "expo-haptics": "^55.0.9", "expo-image-picker": "~55.0.14", "expo-linking": "~55.0.12", + "expo-modules-core": "~55.0.22", "expo-paste-input": "^0.1.15", "expo-router": "~55.0.12", "expo-secure-store": "~55.0.9", diff --git a/apps/mobile/src/app/threads/[environmentId]/[threadId]/_layout.tsx b/apps/mobile/src/app/threads/[environmentId]/[threadId]/_layout.tsx index fc0b29c488..c741560e2f 100644 --- a/apps/mobile/src/app/threads/[environmentId]/[threadId]/_layout.tsx +++ b/apps/mobile/src/app/threads/[environmentId]/[threadId]/_layout.tsx @@ -65,6 +65,16 @@ export default function ThreadLayout() { sheetGrabberVisible: true, }} /> + ); } diff --git a/apps/mobile/src/app/threads/[environmentId]/[threadId]/terminal.tsx b/apps/mobile/src/app/threads/[environmentId]/[threadId]/terminal.tsx new file mode 100644 index 0000000000..a13b90216d --- /dev/null +++ b/apps/mobile/src/app/threads/[environmentId]/[threadId]/terminal.tsx @@ -0,0 +1,5 @@ +import { ThreadTerminalRouteScreen } from "../../../../features/threads/ThreadTerminalRouteScreen"; + +export default function ThreadTerminalRoute() { + return ; +} diff --git a/apps/mobile/src/features/threads/ThreadGitControls.tsx b/apps/mobile/src/features/threads/ThreadGitControls.tsx index 77262e8248..2361a06562 100644 --- a/apps/mobile/src/features/threads/ThreadGitControls.tsx +++ b/apps/mobile/src/features/threads/ThreadGitControls.tsx @@ -1,4 +1,4 @@ -import type { GitRunStackedActionResult, GitStatusResult } from "@t3tools/contracts"; +import type { GitRunStackedActionResult, GitStatusResult, ProjectScript } from "@t3tools/contracts"; import { type GitActionRequestInput, requiresDefaultBranchConfirmation, @@ -9,6 +9,14 @@ import Stack from "expo-router/stack"; import { useCallback, useMemo } from "react"; import { Alert, Linking } from "react-native"; import { buildThreadReviewRoutePath } from "../../lib/routes"; +import { + basename, + getTerminalLabel, + getTerminalStatusLabel, + projectScriptMenuIcon, + projectScriptMenuLabel, + type TerminalMenuSession, +} from "./terminalMenu"; function truncateMiddle(value: string, maxLength: number): string { if (value.length <= maxLength) { @@ -55,6 +63,12 @@ export function ThreadGitControls(props: { readonly currentBranch: string | null; readonly gitStatus: GitStatusResult | null; readonly gitOperationLabel: string | null; + readonly canOpenTerminal: boolean; + readonly projectScripts: ReadonlyArray; + readonly terminalSessions: ReadonlyArray; + readonly onOpenTerminal: (terminalId?: string | null) => void; + readonly onOpenNewTerminal: () => void; + readonly onRunProjectScript: (script: ProjectScript) => Promise; readonly onPull: () => Promise; readonly onRunAction: (input: GitActionRequestInput) => Promise; }) { @@ -167,6 +181,54 @@ export function ThreadGitControls(props: { return ( + + {props.projectScripts.length > 0 ? ( + + Project scripts + {props.projectScripts.map((script) => ( + void props.onRunProjectScript(script)} + subtitle={script.command} + > + {projectScriptMenuLabel(script)} + + ))} + + ) : ( + {}} + subtitle="This project has no saved scripts yet" + > + No project scripts + + )} + + Terminals + {props.terminalSessions.map((session) => ( + props.onOpenTerminal(session.terminalId)} + subtitle={[getTerminalStatusLabel({ status: session.status }), basename(session.cwd)] + .filter(Boolean) + .join(" · ")} + > + {getTerminalLabel(session.terminalId)} + + ))} + + Open new terminal + + + + buildTerminalMenuSessions({ + knownSessions: knownTerminalSessions, + workspaceRoot: selectedThreadProject?.workspaceRoot ?? null, + }), + [knownTerminalSessions, selectedThreadProject?.workspaceRoot], + ); + const selectedThreadDetailWorktreePath = selectedThreadDetail?.worktreePath ?? null; /* ─── Git action progress (for overlay banner) ──────────────────── */ const gitActionProgressTarget = useMemo( () => ({ environmentId: selectedThread?.environmentId ?? null, - cwd: selectedThread?.worktreePath ?? selectedThreadProject?.workspaceRoot ?? null, + cwd: selectedThreadCwd, }), - [ - selectedThread?.environmentId, - selectedThread?.worktreePath, - selectedThreadProject?.workspaceRoot, - ], + [selectedThread?.environmentId, selectedThreadCwd], ); const gitActionProgress = useGitActionProgress(gitActionProgressTarget); @@ -101,9 +122,9 @@ export function ThreadRouteScreen() { if (!selectedThread) return; await gitStatusManager.refresh({ environmentId: selectedThread.environmentId, - cwd: selectedThread.worktreePath ?? selectedThreadProject?.workspaceRoot ?? null, + cwd: selectedThreadCwd, }); - }, [selectedThread, selectedThreadProject?.workspaceRoot]); + }, [selectedThread, selectedThreadCwd]); /** Wraps thread refresh + git status refresh for pull-to-refresh */ const handleRefreshAll = useCallback(async () => { @@ -119,6 +140,83 @@ export function ThreadRouteScreen() { void router.push("/connections"); }, [router]); + const handleOpenTerminal = useCallback( + (nextTerminalId?: string | null) => { + if (!selectedThread || !selectedThreadProject?.workspaceRoot) { + return; + } + + void router.push(buildThreadTerminalRoutePath(selectedThread, nextTerminalId)); + }, + [router, selectedThread, selectedThreadProject?.workspaceRoot], + ); + + const handleOpenNewTerminal = useCallback(() => { + if (!selectedThread || !selectedThreadProject?.workspaceRoot) { + return; + } + + const nextId = nextTerminalId(terminalMenuSessions.map((session) => session.terminalId)); + void router.push(buildThreadTerminalRoutePath(selectedThread, nextId)); + }, [router, selectedThread, selectedThreadProject?.workspaceRoot, terminalMenuSessions]); + + const handleRunProjectScript = useCallback( + async (script: ProjectScript) => { + if (!selectedThread || !selectedThreadProject?.workspaceRoot) { + return; + } + + const client = getEnvironmentClient(selectedThread.environmentId); + if (!client) { + return; + } + + const targetTerminalId = resolveProjectScriptTerminalId({ + existingTerminalIds: terminalMenuSessions.map((session) => session.terminalId), + hasRunningTerminal: terminalMenuSessions.some( + (session) => session.status === "running" || session.status === "starting", + ), + }); + const preferredWorktreePath = resolvePreferredThreadWorktreePath({ + threadShellWorktreePath: selectedThread.worktreePath ?? null, + threadDetailWorktreePath: selectedThreadDetailWorktreePath, + }); + const cwd = projectScriptCwd({ + project: { cwd: selectedThreadProject.workspaceRoot }, + worktreePath: preferredWorktreePath, + }); + const env = projectScriptRuntimeEnv({ + project: { cwd: selectedThreadProject.workspaceRoot }, + worktreePath: preferredWorktreePath, + }); + const snapshot = await client.terminal.open({ + threadId: selectedThread.id, + terminalId: targetTerminalId, + cwd, + worktreePath: preferredWorktreePath, + env, + }); + + terminalSessionManager.syncSnapshot( + { environmentId: selectedThread.environmentId }, + snapshot, + ); + await client.terminal.write({ + threadId: selectedThread.id, + terminalId: targetTerminalId, + data: `${script.command}\r`, + }); + void router.push(buildThreadTerminalRoutePath(selectedThread, targetTerminalId)); + }, + [ + router, + selectedThread, + selectedThreadDetailWorktreePath, + selectedThreadProject, + terminalMenuSessions, + ], + ); + if (!environmentId || !threadId) { return ; } @@ -223,6 +321,12 @@ export function ThreadRouteScreen() { currentBranch={selectedThreadDetail.branch} gitStatus={gitStatus.data} gitOperationLabel={gitState.gitOperationLabel} + canOpenTerminal={Boolean(selectedThreadProject?.workspaceRoot)} + projectScripts={selectedThreadProject?.scripts ?? []} + terminalSessions={terminalMenuSessions} + onOpenTerminal={handleOpenTerminal} + onOpenNewTerminal={handleOpenNewTerminal} + onRunProjectScript={handleRunProjectScript} onPull={gitActions.onPullSelectedThreadBranch} onRunAction={gitActions.onRunSelectedThreadGitAction} /> diff --git a/apps/mobile/src/features/threads/ThreadTerminalPanel.tsx b/apps/mobile/src/features/threads/ThreadTerminalPanel.tsx new file mode 100644 index 0000000000..863ec93e6d --- /dev/null +++ b/apps/mobile/src/features/threads/ThreadTerminalPanel.tsx @@ -0,0 +1,170 @@ +import { DEFAULT_TERMINAL_ID } from "@t3tools/contracts"; +import { SymbolView } from "expo-symbols"; +import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react"; +import { Pressable, View } from "react-native"; + +import { AppText as Text } from "../../components/AppText"; +import { getEnvironmentClient } from "../../state/use-remote-environment-registry"; +import { useTerminalSession, useTerminalSessionTarget } from "../../state/use-terminal-session"; +import { TerminalSurface } from "../../native/terminal/NativeTerminalSurface"; +import { hasNativeTerminalSurface } from "../../native/terminal/nativeTerminalModule"; + +interface ThreadTerminalPanelProps { + readonly environmentId: string; + readonly threadId: string; + readonly cwd: string; + readonly worktreePath: string | null; + readonly visible: boolean; + readonly onClose: () => void; +} + +const DEFAULT_TERMINAL_COLS = 80; +const DEFAULT_TERMINAL_ROWS = 24; + +export const ThreadTerminalPanel = memo(function ThreadTerminalPanel( + props: ThreadTerminalPanelProps, +) { + const nativeTerminalAvailable = hasNativeTerminalSurface(); + const terminalId = DEFAULT_TERMINAL_ID; + const target = useTerminalSessionTarget({ + environmentId: props.environmentId, + threadId: props.threadId, + terminalId, + }); + const terminal = useTerminalSession(target); + const [lastGridSize, setLastGridSize] = useState({ + cols: DEFAULT_TERMINAL_COLS, + rows: DEFAULT_TERMINAL_ROWS, + }); + const hasOpenedRef = useRef(false); + + const terminalKey = useMemo( + () => `${props.environmentId}:${props.threadId}:${terminalId}`, + [props.environmentId, props.threadId, terminalId], + ); + const isRunning = terminal.status === "running" || terminal.status === "starting"; + + useEffect(() => { + hasOpenedRef.current = false; + }, [terminalKey]); + + const openTerminal = useCallback(async () => { + const client = getEnvironmentClient(props.environmentId); + if (!client) { + return; + } + + await client.terminal.open({ + threadId: props.threadId, + terminalId, + cwd: props.cwd, + worktreePath: props.worktreePath, + cols: lastGridSize.cols, + rows: lastGridSize.rows, + }); + }, [ + lastGridSize.cols, + lastGridSize.rows, + props.cwd, + props.environmentId, + props.threadId, + props.worktreePath, + terminalId, + ]); + + useEffect(() => { + if (!props.visible || hasOpenedRef.current || terminal.status !== "closed") { + return; + } + + hasOpenedRef.current = true; + void openTerminal().catch(() => { + hasOpenedRef.current = false; + }); + }, [openTerminal, props.visible, terminal.status]); + + const handleInput = useCallback( + (data: string) => { + const client = getEnvironmentClient(props.environmentId); + if (!client || !isRunning) { + return; + } + + void client.terminal.write({ + threadId: props.threadId, + terminalId, + data, + }); + }, + [isRunning, props.environmentId, props.threadId, terminalId], + ); + + const handleResize = useCallback( + (size: { readonly cols: number; readonly rows: number }) => { + if (size.cols === lastGridSize.cols && size.rows === lastGridSize.rows) { + return; + } + + setLastGridSize(size); + const client = getEnvironmentClient(props.environmentId); + if (!client || !isRunning) { + return; + } + + void client.terminal.resize({ + threadId: props.threadId, + terminalId, + cols: size.cols, + rows: size.rows, + }); + }, + [ + isRunning, + lastGridSize.cols, + lastGridSize.rows, + props.environmentId, + props.threadId, + terminalId, + ], + ); + + if (!props.visible) { + return null; + } + + return ( + + + + + Terminal + + + {nativeTerminalAvailable ? "Native Ghostty surface" : "Text fallback active"} + + + + {terminal.error ? ( + + {terminal.error} + + ) : null} + + + + + + + + ); +}); diff --git a/apps/mobile/src/features/threads/ThreadTerminalRouteScreen.test.ts b/apps/mobile/src/features/threads/ThreadTerminalRouteScreen.test.ts new file mode 100644 index 0000000000..5e20338892 --- /dev/null +++ b/apps/mobile/src/features/threads/ThreadTerminalRouteScreen.test.ts @@ -0,0 +1,66 @@ +import { describe, expect, it } from "vitest"; + +import { resolveTerminalRouteBootstrap } from "./terminalRouteBootstrap"; + +describe("resolveTerminalRouteBootstrap", () => { + it("redirects bare terminal routes to another already-running terminal for the thread", () => { + expect( + resolveTerminalRouteBootstrap({ + hasThread: true, + hasWorkspaceRoot: true, + hasOpened: false, + requestedTerminalId: null, + currentTerminalId: "default", + runningTerminalId: "term-2", + }), + ).toEqual({ + kind: "redirect", + terminalId: "term-2", + }); + }); + + it("hydrates the current running terminal instead of skipping open", () => { + expect( + resolveTerminalRouteBootstrap({ + hasThread: true, + hasWorkspaceRoot: true, + hasOpened: false, + requestedTerminalId: null, + currentTerminalId: "default", + runningTerminalId: "default", + }), + ).toEqual({ + kind: "open", + }); + }); + + it("opens explicit terminal routes once so they replay existing history", () => { + expect( + resolveTerminalRouteBootstrap({ + hasThread: true, + hasWorkspaceRoot: true, + hasOpened: false, + requestedTerminalId: "term-2", + currentTerminalId: "term-2", + runningTerminalId: "term-2", + }), + ).toEqual({ + kind: "open", + }); + }); + + it("stays idle after the route already bootstrapped once", () => { + expect( + resolveTerminalRouteBootstrap({ + hasThread: true, + hasWorkspaceRoot: true, + hasOpened: true, + requestedTerminalId: null, + currentTerminalId: "default", + runningTerminalId: "default", + }), + ).toEqual({ + kind: "idle", + }); + }); +}); diff --git a/apps/mobile/src/features/threads/ThreadTerminalRouteScreen.tsx b/apps/mobile/src/features/threads/ThreadTerminalRouteScreen.tsx new file mode 100644 index 0000000000..d438424e88 --- /dev/null +++ b/apps/mobile/src/features/threads/ThreadTerminalRouteScreen.tsx @@ -0,0 +1,734 @@ +import { DEFAULT_TERMINAL_ID } from "@t3tools/contracts"; +import { Stack, useLocalSearchParams, useRouter } from "expo-router"; +import { useCallback, useEffect, useMemo, useRef, useState } from "react"; +import { Pressable, ScrollView, Text as RNText, View } from "react-native"; +import { KeyboardStickyView } from "react-native-keyboard-controller"; +import Animated, { useAnimatedKeyboard, useAnimatedStyle } from "react-native-reanimated"; + +import { EmptyState } from "../../components/EmptyState"; +import { LoadingScreen } from "../../components/LoadingScreen"; +import { buildThreadTerminalRoutePath } from "../../lib/routes"; +import { + getEnvironmentClient, + useRemoteEnvironmentState, +} from "../../state/use-remote-environment-registry"; +import { + terminalSessionManager, + useKnownTerminalSessions, + useTerminalSession, + useTerminalSessionTarget, +} from "../../state/use-terminal-session"; +import { useThreadSelection } from "../../state/use-thread-selection"; +import { useSelectedThreadDetail } from "../../state/use-thread-detail"; +import { TerminalSurface } from "../../native/terminal/NativeTerminalSurface"; +import { loadPreferences, savePreferencesPatch } from "../../lib/storage"; +import { resolveTerminalRouteBootstrap } from "./terminalRouteBootstrap"; +import { resolveTerminalOpenLocation } from "./terminalLaunchContext"; +import { + basename, + buildTerminalMenuSessions, + getTerminalLabel, + getTerminalStatusLabel, + nextTerminalId, +} from "./terminalMenu"; +import { + DEFAULT_TERMINAL_FONT_SIZE, + MAX_TERMINAL_FONT_SIZE, + MIN_TERMINAL_FONT_SIZE, + TERMINAL_FONT_SIZE_STEP, + normalizeTerminalFontSize, +} from "./terminalPreferences"; + +const DEFAULT_TERMINAL_COLS = 80; +const DEFAULT_TERMINAL_ROWS = 24; +const TERMINAL_ACCESSORY_HEIGHT = 52; + +type PendingModifier = "ctrl" | "meta"; +type HostPlatform = "mac" | "linux" | "windows" | "unknown"; + +type TerminalToolbarAction = + | { readonly kind: "send"; readonly key: string; readonly label: string; readonly data: string } + | { + readonly kind: "modifier"; + readonly key: string; + readonly label: string; + readonly modifier: PendingModifier; + }; + +interface TerminalMenuSession { + readonly terminalId: string; + readonly cwd: string | null; + readonly status: "starting" | "running" | "exited" | "error" | "closed"; + readonly updatedAt: string | null; +} + +function getTerminalStatusTone(input: { + readonly status: TerminalMenuSession["status"]; + readonly hasRunningSubprocess?: boolean; +}): { + readonly tintColor: string; + readonly textColor: string; +} { + if (input.status === "running") { + if (input.hasRunningSubprocess) { + return { + tintColor: "#fbbf24", + textColor: "#a3a3a3", + }; + } + + return { + tintColor: "#34d399", + textColor: "#a3a3a3", + }; + } + + if (input.status === "starting") { + return { + tintColor: "#f59e0b", + textColor: "#a3a3a3", + }; + } + + if (input.status === "error") { + return { + tintColor: "#ef4444", + textColor: "#fca5a5", + }; + } + + return { + tintColor: "#ef4444", + textColor: "#a3a3a3", + }; +} + +function firstRouteParam(value: string | string[] | undefined): string | null { + if (Array.isArray(value)) { + return value[0] ?? null; + } + + return value ?? null; +} + +function inferHostPlatform(environmentLabel: string | null): HostPlatform { + const value = environmentLabel?.toLowerCase() ?? ""; + if ( + value.includes("mac") || + value.includes("macbook") || + value.includes("mac mini") || + value.includes("imac") || + value.includes("darwin") + ) { + return "mac"; + } + if (value.includes("windows") || value.includes("win")) { + return "windows"; + } + if (value.includes("linux") || value.includes("ubuntu") || value.includes("debian")) { + return "linux"; + } + + return "unknown"; +} + +function applyCtrlModifier(input: string): string { + const firstCharacter = input[0]; + if (!firstCharacter) { + return input; + } + + const lowerCharacter = firstCharacter.toLowerCase(); + if (lowerCharacter >= "a" && lowerCharacter <= "z") { + return String.fromCharCode(lowerCharacter.charCodeAt(0) - 96); + } + + if (firstCharacter === "@") return "\u0000"; + if (firstCharacter === "[") return "\u001b"; + if (firstCharacter === "\\") return "\u001c"; + if (firstCharacter === "]") return "\u001d"; + if (firstCharacter === "^") return "\u001e"; + if (firstCharacter === "_") return "\u001f"; + if (firstCharacter === "?") return "\u007f"; + + return input; +} + +export function ThreadTerminalRouteScreen() { + const router = useRouter(); + const keyboard = useAnimatedKeyboard(); + const { isLoadingSavedConnection } = useRemoteEnvironmentState(); + const params = useLocalSearchParams<{ + environmentId?: string | string[]; + threadId?: string | string[]; + terminalId?: string | string[]; + }>(); + const { selectedThread, selectedThreadProject, selectedEnvironmentConnection } = + useThreadSelection(); + const selectedThreadDetail = useSelectedThreadDetail(); + const requestedTerminalId = firstRouteParam(params.terminalId); + const knownSessions = useKnownTerminalSessions({ + environmentId: selectedThread?.environmentId ?? null, + threadId: selectedThread?.id ?? null, + }); + const [lastGridSize, setLastGridSize] = useState({ + cols: DEFAULT_TERMINAL_COLS, + rows: DEFAULT_TERMINAL_ROWS, + }); + const [pendingModifier, setPendingModifier] = useState(null); + const [fontSize, setFontSize] = useState(DEFAULT_TERMINAL_FONT_SIZE); + const hasOpenedRef = useRef(false); + const hasLoadedFontPreferenceRef = useRef(false); + + const terminalId = requestedTerminalId ?? DEFAULT_TERMINAL_ID; + const target = useTerminalSessionTarget({ + environmentId: selectedThread?.environmentId ?? null, + threadId: selectedThread?.id ?? null, + terminalId, + }); + const terminal = useTerminalSession(target); + const terminalKey = useMemo( + () => + selectedThread + ? `${selectedThread.environmentId}:${selectedThread.id}:${terminalId}` + : terminalId, + [selectedThread, terminalId], + ); + const isRunning = terminal.status === "running" || terminal.status === "starting"; + const cwd = terminal.snapshot?.cwd ?? selectedThreadProject?.workspaceRoot ?? null; + const hostPlatform = useMemo( + () => inferHostPlatform(selectedEnvironmentConnection?.environmentLabel ?? null), + [selectedEnvironmentConnection?.environmentLabel], + ); + const runningSession = useMemo( + () => + knownSessions.find( + (session) => session.state.status === "running" || session.state.status === "starting", + ) ?? null, + [knownSessions], + ); + const activeKnownSession = useMemo( + () => knownSessions.find((session) => session.target.terminalId === terminalId) ?? null, + [knownSessions, terminalId], + ); + const terminalStatusTone = useMemo( + () => + getTerminalStatusTone({ + status: terminal.status, + hasRunningSubprocess: terminal.hasRunningSubprocess, + }), + [terminal.hasRunningSubprocess, terminal.status], + ); + const headerTitle = useMemo(() => { + const topLineParts = [ + selectedEnvironmentConnection?.environmentLabel ?? null, + selectedThreadProject?.title ?? null, + ].filter((value): value is string => Boolean(value)); + + return { + topLine: topLineParts.join(" \u00b7 "), + bottomLine: cwd ?? selectedThreadProject?.workspaceRoot ?? "", + }; + }, [ + cwd, + selectedEnvironmentConnection?.environmentLabel, + selectedThreadProject?.title, + selectedThreadProject?.workspaceRoot, + ]); + const terminalToolbarActions = useMemo>(() => { + const modifierActions: ReadonlyArray = + hostPlatform === "mac" + ? [ + { kind: "modifier", key: "cmd", label: "cmd", modifier: "meta" }, + { kind: "modifier", key: "ctrl", label: "ctrl", modifier: "ctrl" }, + ] + : [ + { kind: "modifier", key: "ctrl", label: "ctrl", modifier: "ctrl" }, + { kind: "modifier", key: "alt", label: "alt", modifier: "meta" }, + ]; + + return [ + { kind: "send", key: "esc", label: "esc", data: "\u001b" }, + ...modifierActions, + { kind: "send", key: "tab", label: "tab", data: "\t" }, + { kind: "send", key: "up", label: "↑", data: "\u001b[A" }, + { kind: "send", key: "down", label: "↓", data: "\u001b[B" }, + { kind: "send", key: "left", label: "←", data: "\u001b[D" }, + { kind: "send", key: "right", label: "→", data: "\u001b[C" }, + { kind: "send", key: "tilde", label: "~", data: "~" }, + { kind: "send", key: "pipe", label: "|", data: "|" }, + { kind: "send", key: "slash", label: "/", data: "/" }, + { kind: "send", key: "dash", label: "-", data: "-" }, + ]; + }, [hostPlatform]); + const terminalBottomInset = TERMINAL_ACCESSORY_HEIGHT; + const terminalContainerAnimatedStyle = useAnimatedStyle(() => ({ + paddingBottom: + keyboard.height.value > 0 + ? keyboard.height.value + TERMINAL_ACCESSORY_HEIGHT + : terminalBottomInset, + })); + + const terminalMenuSessions = useMemo>( + () => + buildTerminalMenuSessions({ + knownSessions, + workspaceRoot: selectedThreadProject?.workspaceRoot ?? null, + currentSession: { + terminalId, + cwd: cwd ?? null, + status: terminal.status, + updatedAt: terminal.updatedAt, + }, + }), + [ + cwd, + knownSessions, + selectedThreadProject?.workspaceRoot, + terminal.status, + terminal.updatedAt, + terminalId, + ], + ); + + const openTerminal = useCallback(async () => { + if (!selectedThread || !selectedThreadProject?.workspaceRoot) { + return; + } + + const client = getEnvironmentClient(selectedThread.environmentId); + if (!client) { + return; + } + + const launchLocation = resolveTerminalOpenLocation({ + terminalSnapshot: terminal.snapshot, + activeSessionSnapshot: activeKnownSession?.state.snapshot ?? null, + workspaceRoot: selectedThreadProject.workspaceRoot, + threadShellWorktreePath: selectedThread.worktreePath ?? null, + threadDetailWorktreePath: selectedThreadDetail?.worktreePath ?? null, + }); + + const snapshot = await client.terminal.open({ + threadId: selectedThread.id, + terminalId, + cwd: launchLocation.cwd, + worktreePath: launchLocation.worktreePath, + cols: lastGridSize.cols, + rows: lastGridSize.rows, + }); + + terminalSessionManager.syncSnapshot({ environmentId: selectedThread.environmentId }, snapshot); + }, [ + lastGridSize.cols, + lastGridSize.rows, + activeKnownSession?.state.snapshot, + selectedThreadDetail?.worktreePath, + selectedThread, + selectedThreadProject?.workspaceRoot, + terminal.snapshot, + terminalId, + ]); + + useEffect(() => { + hasOpenedRef.current = false; + }, [terminalKey]); + + useEffect(() => { + let cancelled = false; + + void loadPreferences() + .then((preferences) => { + if (cancelled) { + return; + } + + setFontSize(normalizeTerminalFontSize(preferences.terminalFontSize)); + hasLoadedFontPreferenceRef.current = true; + }) + .catch(() => { + if (cancelled) { + return; + } + + hasLoadedFontPreferenceRef.current = true; + }); + + return () => { + cancelled = true; + }; + }, []); + + useEffect(() => { + if (!hasLoadedFontPreferenceRef.current) { + return; + } + + void savePreferencesPatch({ + terminalFontSize: normalizeTerminalFontSize(fontSize), + }); + }, [fontSize]); + + useEffect(() => { + const bootstrapAction = resolveTerminalRouteBootstrap({ + hasThread: selectedThread !== null, + hasWorkspaceRoot: Boolean(selectedThreadProject?.workspaceRoot), + hasOpened: hasOpenedRef.current, + requestedTerminalId, + currentTerminalId: terminalId, + runningTerminalId: runningSession?.target.terminalId ?? null, + }); + if (bootstrapAction.kind === "idle" || !selectedThread) { + return; + } + + if (bootstrapAction.kind === "redirect") { + router.replace(buildThreadTerminalRoutePath(selectedThread, bootstrapAction.terminalId)); + return; + } + + hasOpenedRef.current = true; + void openTerminal().catch(() => { + hasOpenedRef.current = false; + }); + }, [ + openTerminal, + requestedTerminalId, + router, + runningSession, + selectedThread, + selectedThreadProject?.workspaceRoot, + terminalId, + ]); + + useEffect(() => { + setPendingModifier(null); + }, [terminalId]); + + const writeInput = useCallback( + (data: string) => { + if (!selectedThread || !isRunning) { + return; + } + + const client = getEnvironmentClient(selectedThread.environmentId); + if (!client) { + return; + } + + void client.terminal.write({ + threadId: selectedThread.id, + terminalId, + data, + }); + }, + [isRunning, selectedThread, terminalId], + ); + + const handleInput = useCallback( + (data: string) => { + if (data.length === 0) { + return; + } + + if (pendingModifier === "ctrl") { + setPendingModifier(null); + writeInput(applyCtrlModifier(data)); + } else if (pendingModifier === "meta") { + setPendingModifier(null); + writeInput(`\u001b${data}`); + } else { + writeInput(data); + } + }, + [pendingModifier, writeInput], + ); + + const handleResize = useCallback( + (size: { readonly cols: number; readonly rows: number }) => { + if (size.cols === lastGridSize.cols && size.rows === lastGridSize.rows) { + return; + } + + setLastGridSize(size); + if (!selectedThread || !isRunning) { + return; + } + + const client = getEnvironmentClient(selectedThread.environmentId); + if (!client) { + return; + } + + void client.terminal.resize({ + threadId: selectedThread.id, + terminalId, + cols: size.cols, + rows: size.rows, + }); + }, + [isRunning, lastGridSize.cols, lastGridSize.rows, selectedThread, terminalId], + ); + + const handleSelectTerminal = useCallback( + (nextTerminalId: string) => { + if (!selectedThread || nextTerminalId === terminalId) { + return; + } + + router.replace(buildThreadTerminalRoutePath(selectedThread, nextTerminalId)); + }, + [router, selectedThread, terminalId], + ); + + const handleOpenNewTerminal = useCallback(() => { + if (!selectedThread) { + return; + } + + router.replace( + buildThreadTerminalRoutePath( + selectedThread, + nextTerminalId(terminalMenuSessions.map((session) => session.terminalId)), + ), + ); + }, [router, selectedThread, terminalMenuSessions]); + + const adjustFontSize = useCallback((delta: number) => { + setTimeout(() => { + setFontSize((current) => normalizeTerminalFontSize(current + delta)); + }, 0); + }, []); + + const handleDecreaseFontSize = useCallback(() => { + adjustFontSize(-TERMINAL_FONT_SIZE_STEP); + }, [adjustFontSize]); + + const handleIncreaseFontSize = useCallback(() => { + adjustFontSize(TERMINAL_FONT_SIZE_STEP); + }, [adjustFontSize]); + + const handleToolbarActionPress = useCallback( + (action: TerminalToolbarAction) => { + if (action.kind === "modifier") { + setPendingModifier((current) => (current === action.modifier ? null : action.modifier)); + return; + } + + setPendingModifier(null); + if (pendingModifier === "ctrl") { + writeInput(applyCtrlModifier(action.data)); + } else if (pendingModifier === "meta") { + writeInput(`\u001b${action.data}`); + } else { + writeInput(action.data); + } + }, + [pendingModifier, writeInput], + ); + + if (!selectedThread) { + if (isLoadingSavedConnection) { + return ; + } + + return ( + + + + ); + } + + if (!selectedThreadProject?.workspaceRoot) { + return ( + + + + ); + } + + return ( + <> + ( + + + {headerTitle.topLine} + + + {headerTitle.bottomLine} + + + ), + }} + /> + + + + + {getTerminalStatusLabel({ + status: terminal.status, + hasRunningSubprocess: terminal.hasRunningSubprocess, + })} + + + Text size + + {`A- ${Math.max(MIN_TERMINAL_FONT_SIZE, fontSize - TERMINAL_FONT_SIZE_STEP).toFixed(1)} pt`} + + = MAX_TERMINAL_FONT_SIZE} + discoverabilityLabel="Increase terminal text size" + onPress={handleIncreaseFontSize} + > + {`A+ ${Math.min(MAX_TERMINAL_FONT_SIZE, fontSize + TERMINAL_FONT_SIZE_STEP).toFixed(1)} pt`} + + + {terminalMenuSessions.map((session) => ( + handleSelectTerminal(session.terminalId)} + subtitle={[getTerminalStatusLabel({ status: session.status }), basename(session.cwd)] + .filter(Boolean) + .join(" · ")} + > + {getTerminalLabel(session.terminalId)} + + ))} + + Open new terminal + + + + + + + + + + + + + {terminalToolbarActions.map((action) => { + const active = action.kind === "modifier" && pendingModifier === action.modifier; + + return ( + handleToolbarActionPress(action)} + style={({ pressed }) => ({ + alignItems: "center", + backgroundColor: active + ? "rgba(74, 222, 128, 0.18)" + : pressed + ? "rgba(255,255,255,0.12)" + : "rgba(255,255,255,0.06)", + borderColor: active ? "rgba(74, 222, 128, 0.36)" : "rgba(255,255,255,0.08)", + borderRadius: 12, + borderWidth: 1, + justifyContent: "center", + minWidth: action.label.length > 1 ? 46 : 38, + paddingHorizontal: 11, + paddingVertical: 8, + })} + > + + {action.label} + + + ); + })} + + + + + + ); +} diff --git a/apps/mobile/src/features/threads/git/GitBranchesSheet.tsx b/apps/mobile/src/features/threads/git/GitBranchesSheet.tsx index 020e34c36c..41bd5d79e0 100644 --- a/apps/mobile/src/features/threads/git/GitBranchesSheet.tsx +++ b/apps/mobile/src/features/threads/git/GitBranchesSheet.tsx @@ -10,12 +10,14 @@ import { useGitStatus } from "../../../state/use-git-status"; import { useThreadSelection } from "../../../state/use-thread-selection"; import { useSelectedThreadGitActions } from "../use-selected-thread-git-actions"; import { useSelectedThreadGitState } from "../use-selected-thread-git-state"; +import { useSelectedThreadWorktree } from "../use-selected-thread-worktree"; import { SheetActionButton } from "./gitSheetComponents"; export function GitBranchesSheet() { const router = useRouter(); const insets = useSafeAreaInsets(); - const { selectedThread, selectedThreadProject } = useThreadSelection(); + const { selectedThread } = useThreadSelection(); + const { selectedThreadCwd, selectedThreadWorktreePath } = useSelectedThreadWorktree(); const gitState = useSelectedThreadGitState(); const gitActions = useSelectedThreadGitActions(); @@ -27,11 +29,11 @@ export function GitBranchesSheet() { const gitStatus = useGitStatus({ environmentId: selectedThread?.environmentId ?? "", - cwd: selectedThread?.worktreePath ?? selectedThreadProject?.workspaceRoot ?? null, + cwd: selectedThreadCwd, }); const currentBranchLabel = gitStatus.data?.branch ?? selectedThread?.branch ?? "Detached HEAD"; - const currentWorktreePath = selectedThread?.worktreePath ?? null; + const currentWorktreePath = selectedThreadWorktreePath; const availableBranches = gitState.selectedThreadBranches; const branchesLoading = gitState.selectedThreadBranchesLoading; const busy = gitState.gitOperationLabel !== null; diff --git a/apps/mobile/src/features/threads/git/GitCommitSheet.tsx b/apps/mobile/src/features/threads/git/GitCommitSheet.tsx index fc9195b5af..fab0f73429 100644 --- a/apps/mobile/src/features/threads/git/GitCommitSheet.tsx +++ b/apps/mobile/src/features/threads/git/GitCommitSheet.tsx @@ -9,13 +9,15 @@ import { useGitStatus } from "../../../state/use-git-status"; import { useThreadSelection } from "../../../state/use-thread-selection"; import { useSelectedThreadGitActions } from "../use-selected-thread-git-actions"; import { useSelectedThreadGitState } from "../use-selected-thread-git-state"; +import { useSelectedThreadWorktree } from "../use-selected-thread-worktree"; import { SheetActionButton } from "./gitSheetComponents"; export function GitCommitSheet() { const router = useRouter(); const insets = useSafeAreaInsets(); const isDarkMode = useColorScheme() === "dark"; - const { selectedThread, selectedThreadProject } = useThreadSelection(); + const { selectedThread } = useThreadSelection(); + const { selectedThreadCwd } = useSelectedThreadWorktree(); const gitState = useSelectedThreadGitState(); const gitActions = useSelectedThreadGitActions(); @@ -27,7 +29,7 @@ export function GitCommitSheet() { const gitStatus = useGitStatus({ environmentId: selectedThread?.environmentId ?? "", - cwd: selectedThread?.worktreePath ?? selectedThreadProject?.workspaceRoot ?? null, + cwd: selectedThreadCwd, }); const busy = gitState.gitOperationLabel !== null; diff --git a/apps/mobile/src/features/threads/git/GitOverviewSheet.tsx b/apps/mobile/src/features/threads/git/GitOverviewSheet.tsx index 765d603a4d..d8d9808602 100644 --- a/apps/mobile/src/features/threads/git/GitOverviewSheet.tsx +++ b/apps/mobile/src/features/threads/git/GitOverviewSheet.tsx @@ -17,6 +17,7 @@ import { useGitStatus } from "../../../state/use-git-status"; import { useThreadSelection } from "../../../state/use-thread-selection"; import { useSelectedThreadGitActions } from "../use-selected-thread-git-actions"; import { useSelectedThreadGitState } from "../use-selected-thread-git-state"; +import { useSelectedThreadWorktree } from "../use-selected-thread-worktree"; import { MetaCard, SheetListRow, menuItemIconName, statusSummary } from "./gitSheetComponents"; export function GitOverviewSheet() { @@ -26,7 +27,8 @@ export function GitOverviewSheet() { environmentId: string; threadId: string; }>(); - const { selectedThread, selectedThreadProject } = useThreadSelection(); + const { selectedThread } = useThreadSelection(); + const { selectedThreadCwd, selectedThreadWorktreePath } = useSelectedThreadWorktree(); const gitState = useSelectedThreadGitState(); const gitActions = useSelectedThreadGitActions(); @@ -35,11 +37,11 @@ export function GitOverviewSheet() { const gitStatus = useGitStatus({ environmentId: selectedThread?.environmentId ?? "", - cwd: selectedThread?.worktreePath ?? selectedThreadProject?.workspaceRoot ?? null, + cwd: selectedThreadCwd, }); const currentBranchLabel = gitStatus.data?.branch ?? selectedThread?.branch ?? "Detached HEAD"; - const currentWorktreePath = selectedThread?.worktreePath ?? null; + const currentWorktreePath = selectedThreadWorktreePath; const gitOperationLabel = gitState.gitOperationLabel; const busy = gitOperationLabel !== null; const isRepo = gitStatus.data?.isRepo ?? true; diff --git a/apps/mobile/src/features/threads/review/ReviewSheet.tsx b/apps/mobile/src/features/threads/review/ReviewSheet.tsx index 858b0832b9..193fe156bd 100644 --- a/apps/mobile/src/features/threads/review/ReviewSheet.tsx +++ b/apps/mobile/src/features/threads/review/ReviewSheet.tsx @@ -23,8 +23,8 @@ import { cn } from "../../../lib/cn"; import { useThemeColor } from "../../../lib/useThemeColor"; import { getEnvironmentClient } from "../../../state/use-remote-environment-registry"; import { useSelectedThreadDetail } from "../../../state/use-thread-detail"; -import { useThreadSelection } from "../../../state/use-thread-selection"; import { useThreadDraftForThread } from "../use-thread-composer-state"; +import { useSelectedThreadWorktree } from "../use-selected-thread-worktree"; import { getCachedReviewParsedDiff, setReviewGitSections, @@ -445,7 +445,6 @@ export function ReviewSheet() { }>(); const { draftMessage } = useThreadDraftForThread({ environmentId, threadId }); const reviewCache = useReviewCacheForThread({ environmentId, threadId }); - const { selectedThreadProject } = useThreadSelection(); const selectedThread = useSelectedThreadDetail(); const [loadingTurnIds, setLoadingTurnIds] = useState>({}); const [loadingGitDiffs, setLoadingGitDiffs] = useState(false); @@ -464,8 +463,9 @@ export function ReviewSheet() { const highlightQueueActiveRef = useRef(false); const highlightableFilesByIdRef = useRef>(new Map()); const selectedThemeRef = useRef(selectedTheme); + const { selectedThreadCwd } = useSelectedThreadWorktree(); - const cwd = selectedThread?.worktreePath ?? selectedThreadProject?.workspaceRoot ?? null; + const cwd = selectedThreadCwd; const readyCheckpoints = useMemo( () => getReadyReviewCheckpoints(selectedThread?.checkpoints ?? []), [selectedThread?.checkpoints], diff --git a/apps/mobile/src/features/threads/terminalLaunchContext.test.ts b/apps/mobile/src/features/threads/terminalLaunchContext.test.ts new file mode 100644 index 0000000000..acf2c42bec --- /dev/null +++ b/apps/mobile/src/features/threads/terminalLaunchContext.test.ts @@ -0,0 +1,61 @@ +import { describe, expect, it } from "vitest"; + +import { + resolvePreferredThreadWorktreePath, + resolveTerminalOpenLocation, +} from "./terminalLaunchContext"; + +describe("resolvePreferredThreadWorktreePath", () => { + it("prefers thread detail worktree paths over thread shell paths", () => { + expect( + resolvePreferredThreadWorktreePath({ + threadShellWorktreePath: "/repo/root", + threadDetailWorktreePath: "/repo/worktrees/feature", + }), + ).toBe("/repo/worktrees/feature"); + }); + + it("falls back to the thread shell worktree path when detail is unavailable", () => { + expect( + resolvePreferredThreadWorktreePath({ + threadShellWorktreePath: "/repo/worktrees/feature", + threadDetailWorktreePath: null, + }), + ).toBe("/repo/worktrees/feature"); + }); +}); + +describe("resolveTerminalOpenLocation", () => { + it("uses the thread detail worktree path before the workspace root for a fresh mobile open", () => { + expect( + resolveTerminalOpenLocation({ + terminalSnapshot: null, + activeSessionSnapshot: null, + workspaceRoot: "/repo/root", + threadShellWorktreePath: null, + threadDetailWorktreePath: "/repo/worktrees/feature", + }), + ).toEqual({ + cwd: "/repo/worktrees/feature", + worktreePath: "/repo/worktrees/feature", + }); + }); + + it("preserves the running terminal snapshot cwd when attaching to an existing session", () => { + expect( + resolveTerminalOpenLocation({ + terminalSnapshot: null, + activeSessionSnapshot: { + cwd: "/repo/worktrees/feature", + worktreePath: "/repo/worktrees/feature", + }, + workspaceRoot: "/repo/root", + threadShellWorktreePath: null, + threadDetailWorktreePath: "/repo/worktrees/other", + }), + ).toEqual({ + cwd: "/repo/worktrees/feature", + worktreePath: "/repo/worktrees/feature", + }); + }); +}); diff --git a/apps/mobile/src/features/threads/terminalLaunchContext.ts b/apps/mobile/src/features/threads/terminalLaunchContext.ts new file mode 100644 index 0000000000..4b9fbf57dd --- /dev/null +++ b/apps/mobile/src/features/threads/terminalLaunchContext.ts @@ -0,0 +1,39 @@ +interface TerminalSnapshotLike { + readonly cwd: string; + readonly worktreePath: string | null; +} + +export function resolvePreferredThreadWorktreePath(input: { + readonly threadShellWorktreePath: string | null; + readonly threadDetailWorktreePath: string | null; +}): string | null { + return input.threadDetailWorktreePath ?? input.threadShellWorktreePath ?? null; +} + +export function resolveTerminalOpenLocation(input: { + readonly terminalSnapshot: TerminalSnapshotLike | null; + readonly activeSessionSnapshot: TerminalSnapshotLike | null; + readonly workspaceRoot: string; + readonly threadShellWorktreePath: string | null; + readonly threadDetailWorktreePath: string | null; +}): { + readonly cwd: string; + readonly worktreePath: string | null; +} { + const preferredThreadWorktreePath = resolvePreferredThreadWorktreePath({ + threadShellWorktreePath: input.threadShellWorktreePath, + threadDetailWorktreePath: input.threadDetailWorktreePath, + }); + + return { + cwd: + input.terminalSnapshot?.cwd ?? + input.activeSessionSnapshot?.cwd ?? + preferredThreadWorktreePath ?? + input.workspaceRoot, + worktreePath: + input.terminalSnapshot?.worktreePath ?? + input.activeSessionSnapshot?.worktreePath ?? + preferredThreadWorktreePath, + }; +} diff --git a/apps/mobile/src/features/threads/terminalMenu.test.ts b/apps/mobile/src/features/threads/terminalMenu.test.ts new file mode 100644 index 0000000000..deabf6d8a7 --- /dev/null +++ b/apps/mobile/src/features/threads/terminalMenu.test.ts @@ -0,0 +1,128 @@ +import { describe, expect, it } from "vitest"; + +import type { KnownTerminalSession } from "@t3tools/client-runtime"; +import { DEFAULT_TERMINAL_ID } from "@t3tools/contracts"; + +import { buildTerminalMenuSessions, resolveProjectScriptTerminalId } from "./terminalMenu"; + +function makeKnownSession(input: { + readonly terminalId: string; + readonly status: KnownTerminalSession["state"]["status"]; + readonly cwd?: string | null; + readonly updatedAt?: string | null; +}): KnownTerminalSession { + return { + target: { + environmentId: "env-1", + threadId: "thread-1", + terminalId: input.terminalId, + }, + state: { + snapshot: input.cwd + ? { + threadId: "thread-1", + terminalId: input.terminalId, + cwd: input.cwd, + worktreePath: input.cwd, + status: input.status === "closed" ? "error" : input.status, + pid: input.status === "running" ? 123 : null, + history: "", + exitCode: null, + exitSignal: null, + updatedAt: input.updatedAt ?? "2026-04-15T20:00:00.000Z", + } + : null, + buffer: "", + status: input.status, + error: null, + hasRunningSubprocess: false, + updatedAt: input.updatedAt ?? "2026-04-15T20:00:00.000Z", + version: 1, + }, + }; +} + +describe("buildTerminalMenuSessions", () => { + it("keeps the default shell and only includes running sessions by default", () => { + expect( + buildTerminalMenuSessions({ + knownSessions: [ + makeKnownSession({ + terminalId: "term-3", + status: "running", + cwd: "/workspace/feature", + updatedAt: "2026-04-15T20:05:00.000Z", + }), + makeKnownSession({ + terminalId: "term-2", + status: "exited", + cwd: "/workspace/exited", + updatedAt: "2026-04-15T20:06:00.000Z", + }), + ], + workspaceRoot: "/workspace/root", + }), + ).toEqual([ + { + terminalId: DEFAULT_TERMINAL_ID, + cwd: "/workspace/root", + status: "closed", + updatedAt: null, + }, + { + terminalId: "term-3", + cwd: "/workspace/feature", + status: "running", + updatedAt: "2026-04-15T20:05:00.000Z", + }, + ]); + }); + + it("keeps the current terminal visible even if it is no longer running", () => { + expect( + buildTerminalMenuSessions({ + knownSessions: [], + workspaceRoot: "/workspace/root", + currentSession: { + terminalId: "term-4", + cwd: "/workspace/exited", + status: "exited", + updatedAt: "2026-04-15T20:07:00.000Z", + }, + }), + ).toEqual([ + { + terminalId: DEFAULT_TERMINAL_ID, + cwd: "/workspace/root", + status: "closed", + updatedAt: null, + }, + { + terminalId: "term-4", + cwd: "/workspace/exited", + status: "exited", + updatedAt: "2026-04-15T20:07:00.000Z", + }, + ]); + }); +}); + +describe("resolveProjectScriptTerminalId", () => { + it("reuses the default shell when no terminal is running", () => { + expect( + resolveProjectScriptTerminalId({ + existingTerminalIds: [DEFAULT_TERMINAL_ID], + hasRunningTerminal: false, + }), + ).toBe(DEFAULT_TERMINAL_ID); + }); + + it("opens a new terminal when a shell is already running", () => { + expect( + resolveProjectScriptTerminalId({ + existingTerminalIds: [DEFAULT_TERMINAL_ID, "term-2", "term-4"], + hasRunningTerminal: true, + }), + ).toBe("term-3"); + }); +}); diff --git a/apps/mobile/src/features/threads/terminalMenu.ts b/apps/mobile/src/features/threads/terminalMenu.ts new file mode 100644 index 0000000000..085dd4808e --- /dev/null +++ b/apps/mobile/src/features/threads/terminalMenu.ts @@ -0,0 +1,139 @@ +import type { KnownTerminalSession } from "@t3tools/client-runtime"; +import { DEFAULT_TERMINAL_ID, type ProjectScript } from "@t3tools/contracts"; + +export interface TerminalMenuSession { + readonly terminalId: string; + readonly cwd: string | null; + readonly status: "starting" | "running" | "exited" | "error" | "closed"; + readonly updatedAt: string | null; +} + +export function basename(input: string | null): string | null { + if (!input) { + return null; + } + + const normalized = input.replace(/\/+$/, ""); + if (normalized.length === 0) { + return "/"; + } + + const segments = normalized.split("/"); + return segments[segments.length - 1] ?? normalized; +} + +export function getTerminalLabel(terminalId: string): string { + if (terminalId === DEFAULT_TERMINAL_ID) { + return "Main shell"; + } + + const numericSuffix = /^term(?:inal)?-(\d+)$/i.exec(terminalId)?.[1]; + if (numericSuffix) { + return `Terminal ${numericSuffix}`; + } + + return terminalId; +} + +export function getTerminalStatusLabel(input: { + readonly status: TerminalMenuSession["status"]; + readonly hasRunningSubprocess?: boolean; +}): string { + if (input.status === "running") { + return input.hasRunningSubprocess ? "Task running" : "Ready"; + } + if (input.status === "starting") { + return "Starting"; + } + if (input.status === "exited") { + return "Exited"; + } + if (input.status === "error") { + return "Error"; + } + + return "Not started"; +} + +export function nextTerminalId(existingTerminalIds: ReadonlyArray): string { + const usedIds = new Set(existingTerminalIds); + let nextIndex = 2; + while (usedIds.has(`term-${nextIndex}`)) { + nextIndex += 1; + } + + return `term-${nextIndex}`; +} + +export function buildTerminalMenuSessions(input: { + readonly knownSessions: ReadonlyArray; + readonly workspaceRoot: string | null; + readonly currentSession?: TerminalMenuSession | null; +}): ReadonlyArray { + const sessionsById = new Map(); + + sessionsById.set(DEFAULT_TERMINAL_ID, { + terminalId: DEFAULT_TERMINAL_ID, + cwd: input.workspaceRoot, + status: "closed", + updatedAt: null, + }); + + for (const session of input.knownSessions) { + if ( + session.state.status !== "running" && + session.state.status !== "starting" && + session.target.terminalId !== input.currentSession?.terminalId + ) { + continue; + } + + sessionsById.set(session.target.terminalId, { + terminalId: session.target.terminalId, + cwd: session.state.snapshot?.cwd ?? input.workspaceRoot, + status: session.state.status, + updatedAt: session.state.updatedAt, + }); + } + + if (input.currentSession && !sessionsById.has(input.currentSession.terminalId)) { + sessionsById.set(input.currentSession.terminalId, input.currentSession); + } + + return Array.from(sessionsById.values()).sort((left, right) => { + if (left.terminalId === DEFAULT_TERMINAL_ID) return -1; + if (right.terminalId === DEFAULT_TERMINAL_ID) return 1; + + const leftUpdatedAt = left.updatedAt ? Date.parse(left.updatedAt) : 0; + const rightUpdatedAt = right.updatedAt ? Date.parse(right.updatedAt) : 0; + if (leftUpdatedAt !== rightUpdatedAt) { + return rightUpdatedAt - leftUpdatedAt; + } + + return left.terminalId.localeCompare(right.terminalId); + }); +} + +export function resolveProjectScriptTerminalId(input: { + readonly existingTerminalIds: ReadonlyArray; + readonly hasRunningTerminal: boolean; +}): string { + if (!input.hasRunningTerminal) { + return DEFAULT_TERMINAL_ID; + } + + return nextTerminalId(input.existingTerminalIds); +} + +export function projectScriptMenuLabel(script: ProjectScript): string { + return script.runOnWorktreeCreate ? `${script.name} (setup)` : script.name; +} + +export function projectScriptMenuIcon(icon: ProjectScript["icon"]) { + if (icon === "test") return "flask"; + if (icon === "lint") return "checklist"; + if (icon === "configure") return "wrench.and.screwdriver"; + if (icon === "build") return "hammer"; + if (icon === "debug") return "ladybug"; + return "play"; +} diff --git a/apps/mobile/src/features/threads/terminalPreferences.test.ts b/apps/mobile/src/features/threads/terminalPreferences.test.ts new file mode 100644 index 0000000000..06bfdfbf3c --- /dev/null +++ b/apps/mobile/src/features/threads/terminalPreferences.test.ts @@ -0,0 +1,28 @@ +import { describe, expect, it } from "vitest"; + +import { + DEFAULT_TERMINAL_FONT_SIZE, + MAX_TERMINAL_FONT_SIZE, + MIN_TERMINAL_FONT_SIZE, + normalizeTerminalFontSize, +} from "./terminalPreferences"; + +describe("normalizeTerminalFontSize", () => { + it("returns the default size for missing or invalid values", () => { + expect(normalizeTerminalFontSize(undefined)).toBe(DEFAULT_TERMINAL_FONT_SIZE); + expect(normalizeTerminalFontSize(null)).toBe(DEFAULT_TERMINAL_FONT_SIZE); + expect(normalizeTerminalFontSize(Number.NaN)).toBe(DEFAULT_TERMINAL_FONT_SIZE); + }); + + it("clamps below the minimum", () => { + expect(normalizeTerminalFontSize(MIN_TERMINAL_FONT_SIZE - 4)).toBe(MIN_TERMINAL_FONT_SIZE); + }); + + it("clamps above the maximum", () => { + expect(normalizeTerminalFontSize(MAX_TERMINAL_FONT_SIZE + 4)).toBe(MAX_TERMINAL_FONT_SIZE); + }); + + it("preserves in-range values", () => { + expect(normalizeTerminalFontSize(9.5)).toBe(9.5); + }); +}); diff --git a/apps/mobile/src/features/threads/terminalPreferences.ts b/apps/mobile/src/features/threads/terminalPreferences.ts new file mode 100644 index 0000000000..095876fa2a --- /dev/null +++ b/apps/mobile/src/features/threads/terminalPreferences.ts @@ -0,0 +1,12 @@ +export const DEFAULT_TERMINAL_FONT_SIZE = 10; +export const TERMINAL_FONT_SIZE_STEP = 0.5; +export const MIN_TERMINAL_FONT_SIZE = 6; +export const MAX_TERMINAL_FONT_SIZE = 14; + +export function normalizeTerminalFontSize(value: number | null | undefined): number { + if (typeof value !== "number" || !Number.isFinite(value)) { + return DEFAULT_TERMINAL_FONT_SIZE; + } + + return Math.min(MAX_TERMINAL_FONT_SIZE, Math.max(MIN_TERMINAL_FONT_SIZE, value)); +} diff --git a/apps/mobile/src/features/threads/terminalRouteBootstrap.ts b/apps/mobile/src/features/threads/terminalRouteBootstrap.ts new file mode 100644 index 0000000000..458201f09a --- /dev/null +++ b/apps/mobile/src/features/threads/terminalRouteBootstrap.ts @@ -0,0 +1,25 @@ +export function resolveTerminalRouteBootstrap(input: { + readonly hasThread: boolean; + readonly hasWorkspaceRoot: boolean; + readonly hasOpened: boolean; + readonly requestedTerminalId: string | null; + readonly currentTerminalId: string; + readonly runningTerminalId: string | null; +}): + | { readonly kind: "idle" } + | { readonly kind: "redirect"; readonly terminalId: string } + | { readonly kind: "open" } { + if (!input.hasThread || !input.hasWorkspaceRoot || input.hasOpened) { + return { kind: "idle" }; + } + + if ( + input.requestedTerminalId === null && + input.runningTerminalId !== null && + input.runningTerminalId !== input.currentTerminalId + ) { + return { kind: "redirect", terminalId: input.runningTerminalId }; + } + + return { kind: "open" }; +} diff --git a/apps/mobile/src/features/threads/use-selected-thread-git-actions.ts b/apps/mobile/src/features/threads/use-selected-thread-git-actions.ts index 283c530554..e713a7d070 100644 --- a/apps/mobile/src/features/threads/use-selected-thread-git-actions.ts +++ b/apps/mobile/src/features/threads/use-selected-thread-git-actions.ts @@ -25,9 +25,11 @@ import { gitActionManager, showGitActionResult } from "../../state/use-git-actio import { gitBranchManager } from "../../state/use-git-branches"; import { gitStatusManager } from "../../state/use-git-status"; import { useThreadSelection } from "../../state/use-thread-selection"; +import { useSelectedThreadWorktree } from "./use-selected-thread-worktree"; export function useSelectedThreadGitActions() { const { selectedThread, selectedThreadProject } = useThreadSelection(); + const { selectedThreadCwd, selectedThreadWorktreePath } = useSelectedThreadWorktree(); const selectedThreadGitRootCwd = selectedThreadProject?.workspaceRoot ?? null; @@ -61,8 +63,7 @@ export function useSelectedThreadGitActions() { return null; } - const cwd = - options?.cwd ?? selectedThread.worktreePath ?? selectedThreadProject.workspaceRoot; + const cwd = options?.cwd ?? selectedThreadCwd; if (!cwd) { return null; } @@ -86,7 +87,7 @@ export function useSelectedThreadGitActions() { return null; } }, - [selectedThread, selectedThreadProject], + [selectedThread, selectedThreadCwd, selectedThreadProject], ); useEffect(() => { @@ -109,7 +110,7 @@ export function useSelectedThreadGitActions() { return null; } - const cwd = selectedThread.worktreePath ?? selectedThreadProject.workspaceRoot; + const cwd = selectedThreadCwd; if (!cwd) { return null; } @@ -128,7 +129,7 @@ export function useSelectedThreadGitActions() { return null; } }, - [selectedThread, selectedThreadProject], + [selectedThread, selectedThreadCwd, selectedThreadProject], ); const refreshSelectedThreadBranches = useCallback(async (): Promise> => { @@ -204,12 +205,12 @@ export function useSelectedThreadGitActions() { cwd, nextThreadState: { branch: result?.branch ?? thread.branch, - worktreePath: thread.worktreePath, + worktreePath: selectedThreadWorktreePath, }, }); }); }, - [runSelectedThreadGitMutation, syncSelectedThreadBranchState], + [runSelectedThreadGitMutation, selectedThreadWorktreePath, syncSelectedThreadBranchState], ); const onCreateSelectedThreadBranch = useCallback( @@ -227,12 +228,12 @@ export function useSelectedThreadGitActions() { cwd, nextThreadState: { branch: result?.branch ?? thread.branch, - worktreePath: thread.worktreePath, + worktreePath: selectedThreadWorktreePath, }, }); }); }, - [runSelectedThreadGitMutation, syncSelectedThreadBranchState], + [runSelectedThreadGitMutation, selectedThreadWorktreePath, syncSelectedThreadBranchState], ); const onCreateSelectedThreadWorktree = useCallback( @@ -316,7 +317,7 @@ export function useSelectedThreadGitActions() { cwd, nextThreadState: { branch: result.branch.name, - worktreePath: thread.worktreePath, + worktreePath: selectedThreadWorktreePath, }, }); return result; @@ -326,7 +327,12 @@ export function useSelectedThreadGitActions() { return result; }); }, - [refreshSelectedThreadGitStatus, runSelectedThreadGitMutation, syncSelectedThreadBranchState], + [ + refreshSelectedThreadGitStatus, + runSelectedThreadGitMutation, + selectedThreadWorktreePath, + syncSelectedThreadBranchState, + ], ); return { diff --git a/apps/mobile/src/features/threads/use-selected-thread-git-state.ts b/apps/mobile/src/features/threads/use-selected-thread-git-state.ts index efcc6e2556..1ba53130cc 100644 --- a/apps/mobile/src/features/threads/use-selected-thread-git-state.ts +++ b/apps/mobile/src/features/threads/use-selected-thread-git-state.ts @@ -5,20 +5,18 @@ import { dedupeRemoteBranchesWithLocalMatches } from "@t3tools/shared/git"; import { useGitActionState } from "../../state/use-git-action-state"; import { useGitBranches } from "../../state/use-git-branches"; import { useThreadSelection } from "../../state/use-thread-selection"; +import { useSelectedThreadWorktree } from "./use-selected-thread-worktree"; export function useSelectedThreadGitState() { const { selectedThread, selectedThreadProject } = useThreadSelection(); + const { selectedThreadCwd } = useSelectedThreadWorktree(); const selectedThreadGitTarget = useMemo( () => ({ environmentId: selectedThread?.environmentId ?? null, - cwd: selectedThread?.worktreePath ?? selectedThreadProject?.workspaceRoot ?? null, + cwd: selectedThreadCwd, }), - [ - selectedThread?.environmentId, - selectedThread?.worktreePath, - selectedThreadProject?.workspaceRoot, - ], + [selectedThread?.environmentId, selectedThreadCwd], ); const gitActionState = useGitActionState(selectedThreadGitTarget); diff --git a/apps/mobile/src/features/threads/use-selected-thread-worktree.ts b/apps/mobile/src/features/threads/use-selected-thread-worktree.ts new file mode 100644 index 0000000000..7c0064996b --- /dev/null +++ b/apps/mobile/src/features/threads/use-selected-thread-worktree.ts @@ -0,0 +1,24 @@ +import { useMemo } from "react"; + +import { useSelectedThreadDetail } from "../../state/use-thread-detail"; +import { useThreadSelection } from "../../state/use-thread-selection"; +import { resolvePreferredThreadWorktreePath } from "./terminalLaunchContext"; + +export function useSelectedThreadWorktree() { + const { selectedThread, selectedThreadProject } = useThreadSelection(); + const selectedThreadDetail = useSelectedThreadDetail(); + + const selectedThreadWorktreePath = useMemo( + () => + resolvePreferredThreadWorktreePath({ + threadShellWorktreePath: selectedThread?.worktreePath ?? null, + threadDetailWorktreePath: selectedThreadDetail?.worktreePath ?? null, + }), + [selectedThread?.worktreePath, selectedThreadDetail?.worktreePath], + ); + + return { + selectedThreadWorktreePath, + selectedThreadCwd: selectedThreadWorktreePath ?? selectedThreadProject?.workspaceRoot ?? null, + }; +} diff --git a/apps/mobile/src/lib/routes.ts b/apps/mobile/src/lib/routes.ts index b70ab7638e..6fbbe49c86 100644 --- a/apps/mobile/src/lib/routes.ts +++ b/apps/mobile/src/lib/routes.ts @@ -29,6 +29,18 @@ export function buildThreadReviewRoutePath( return `${buildThreadRoutePath(input)}/review`; } +export function buildThreadTerminalRoutePath( + input: ThreadRouteInput | PlainThreadRouteInput, + terminalId?: string | null, +): string { + const basePath = `${buildThreadRoutePath(input)}/terminal`; + if (!terminalId) { + return basePath; + } + + return `${basePath}?terminalId=${encodeURIComponent(terminalId)}`; +} + export function dismissRoute(router: Router) { if (router.canGoBack()) { router.back(); diff --git a/apps/mobile/src/lib/storage.ts b/apps/mobile/src/lib/storage.ts index e40fdc3179..fe2c88e27a 100644 --- a/apps/mobile/src/lib/storage.ts +++ b/apps/mobile/src/lib/storage.ts @@ -5,6 +5,11 @@ import * as SecureStore from "expo-secure-store"; import type { SavedRemoteConnection } from "./connection"; const CONNECTIONS_KEY = "t3code.connections"; +const PREFERENCES_KEY = "t3code.preferences"; + +export interface MobilePreferences { + readonly terminalFontSize?: number; +} async function readStorageItem(key: string): Promise { return await SecureStore.getItemAsync(key); @@ -14,23 +19,31 @@ async function writeStorageItem(key: string, value: string): Promise { await SecureStore.setItemAsync(key, value); } -export async function loadSavedConnections(): Promise> { - const raw = (await readStorageItem(CONNECTIONS_KEY)) ?? ""; +async function readJsonStorageItem(key: string): Promise { + const raw = (await readStorageItem(key)) ?? ""; if (!raw.trim()) { - return []; + return null; } try { - const parsed = JSON.parse(raw) as { - readonly connections?: ReadonlyArray; - }; - return pipe( - parsed.connections ?? [], - Arr.filter((c) => !!c.environmentId && !!c.bearerToken?.trim()), - ); + return JSON.parse(raw) as T; } catch { + return null; + } +} + +export async function loadSavedConnections(): Promise> { + const parsed = await readJsonStorageItem<{ + readonly connections?: ReadonlyArray; + }>(CONNECTIONS_KEY); + if (!parsed) { return []; } + + return pipe( + parsed.connections ?? [], + Arr.filter((c) => !!c.environmentId && !!c.bearerToken?.trim()), + ); } export async function saveConnection(connection: SavedRemoteConnection): Promise { @@ -53,3 +66,28 @@ export async function clearSavedConnection(environmentId: string): Promise ); await writeStorageItem(CONNECTIONS_KEY, JSON.stringify({ connections: next })); } + +export async function loadPreferences(): Promise { + const parsed = await readJsonStorageItem(PREFERENCES_KEY); + if (!parsed || typeof parsed !== "object") { + return {}; + } + + if (typeof parsed.terminalFontSize === "number") { + return { terminalFontSize: parsed.terminalFontSize }; + } + + return {}; +} + +export async function savePreferencesPatch( + patch: Partial, +): Promise { + const current = await loadPreferences(); + const next: MobilePreferences = { + ...current, + ...patch, + }; + await writeStorageItem(PREFERENCES_KEY, JSON.stringify(next)); + return next; +} diff --git a/apps/mobile/src/native/terminal/NativeTerminalSurface.tsx b/apps/mobile/src/native/terminal/NativeTerminalSurface.tsx new file mode 100644 index 0000000000..bd123e3aae --- /dev/null +++ b/apps/mobile/src/native/terminal/NativeTerminalSurface.tsx @@ -0,0 +1,206 @@ +import { memo, useCallback } from "react"; +import { + Pressable, + ScrollView, + TextInput, + View, + type LayoutChangeEvent, + type NativeSyntheticEvent, + type ViewProps, + useColorScheme, +} from "react-native"; + +import { AppText as Text } from "../../components/AppText"; +import { resolveNativeTerminalSurfaceView } from "./nativeTerminalModule"; +import { + buildGhosttyThemeConfig, + getGitHubTerminalTheme, + type TerminalTheme, +} from "./terminalTheme"; + +interface TerminalInputEvent { + readonly data: string; +} + +interface TerminalResizeEvent { + readonly cols: number; + readonly rows: number; +} + +interface TerminalSurfaceProps extends ViewProps { + readonly terminalKey: string; + readonly buffer: string; + readonly fontSize?: number; + readonly isRunning: boolean; + readonly theme?: TerminalTheme; + readonly onInput: (data: string) => void; + readonly onResize: (size: { readonly cols: number; readonly rows: number }) => void; +} + +function estimateGridSize(input: { + readonly width: number; + readonly height: number; + readonly fontSize: number; +}): { readonly cols: number; readonly rows: number } { + const cellWidth = input.fontSize * 0.62; + const cellHeight = input.fontSize * 1.35; + return { + cols: Math.max(20, Math.min(400, Math.floor(input.width / cellWidth))), + rows: Math.max(5, Math.min(200, Math.floor(input.height / cellHeight))), + }; +} + +const FallbackTerminalSurface = memo(function FallbackTerminalSurface(props: TerminalSurfaceProps) { + const fontSize = props.fontSize ?? 12; + const appearanceScheme = useColorScheme() === "light" ? "light" : "dark"; + const theme = props.theme ?? getGitHubTerminalTheme(appearanceScheme); + const statusLabel = props.isRunning + ? "Native terminal unavailable. Using text fallback." + : "Open terminal to start a shell."; + + const handleLayout = (event: LayoutChangeEvent) => { + const { width, height } = event.nativeEvent.layout; + props.onResize(estimateGridSize({ width, height, fontSize })); + }; + + return ( + + + + {statusLabel} + + + + {props.buffer || "$ "} + + + + + { + const text = event.nativeEvent.text; + if (text.length > 0) { + props.onInput(`${text}\n`); + } + }} + /> + ({ + opacity: !props.isRunning ? 0.35 : pressed ? 0.65 : 1, + paddingHorizontal: 10, + paddingVertical: 6, + borderRadius: 8, + backgroundColor: theme.border, + })} + onPress={() => props.onInput("\u0003")} + > + + Ctrl-C + + + + + ); +}); + +export const TerminalSurface = memo(function TerminalSurface(props: TerminalSurfaceProps) { + const fontSize = props.fontSize ?? 12; + const appearanceScheme = useColorScheme() === "light" ? "light" : "dark"; + const theme = props.theme ?? getGitHubTerminalTheme(appearanceScheme); + const { onInput, onResize } = props; + const NativeTerminalSurfaceView = resolveNativeTerminalSurfaceView(); + const handleNativeInput = useCallback( + (event: NativeSyntheticEvent) => { + onInput(event.nativeEvent.data); + }, + [onInput], + ); + const handleNativeResize = useCallback( + (event: NativeSyntheticEvent) => { + onResize({ + cols: event.nativeEvent.cols, + rows: event.nativeEvent.rows, + }); + }, + [onResize], + ); + + if (NativeTerminalSurfaceView) { + return ( + + ); + } + + return ; +}); diff --git a/apps/mobile/src/native/terminal/nativeTerminalModule.test.ts b/apps/mobile/src/native/terminal/nativeTerminalModule.test.ts new file mode 100644 index 0000000000..db750f3984 --- /dev/null +++ b/apps/mobile/src/native/terminal/nativeTerminalModule.test.ts @@ -0,0 +1,52 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +const expoModulesCoreMocks = vi.hoisted(() => ({ + requireNativeViewManager: vi.fn(), +})); +const nativeView = () => null; +const originalExpo = globalThis.expo; + +function setExpoViewConfigAvailable() { + globalThis.expo = { + getViewConfig: vi.fn().mockReturnValue({ validAttributes: {}, directEventTypes: {} }), + } as unknown as typeof globalThis.expo; +} + +vi.mock("expo-modules-core", () => ({ + requireNativeViewManager: expoModulesCoreMocks.requireNativeViewManager, +})); + +describe("resolveNativeTerminalSurfaceView", () => { + beforeEach(() => { + vi.clearAllMocks(); + vi.resetModules(); + globalThis.expo = undefined as unknown as typeof globalThis.expo; + }); + + afterEach(() => { + globalThis.expo = originalExpo; + }); + + it("returns null when the native terminal view config is unavailable", async () => { + const { resolveNativeTerminalSurfaceView } = await import("./nativeTerminalModule"); + expect(resolveNativeTerminalSurfaceView()).toBeNull(); + expect(expoModulesCoreMocks.requireNativeViewManager).not.toHaveBeenCalled(); + }); + + it("returns the native terminal view when the view config is installed", async () => { + setExpoViewConfigAvailable(); + expoModulesCoreMocks.requireNativeViewManager.mockReturnValue(nativeView); + const { resolveNativeTerminalSurfaceView } = await import("./nativeTerminalModule"); + expect(resolveNativeTerminalSurfaceView()).toBe(nativeView); + expect(expoModulesCoreMocks.requireNativeViewManager).toHaveBeenCalledWith("T3TerminalSurface"); + }); + + it("returns null when the view manager cannot be required", async () => { + setExpoViewConfigAvailable(); + expoModulesCoreMocks.requireNativeViewManager.mockImplementation(() => { + throw new Error("boom"); + }); + const { resolveNativeTerminalSurfaceView } = await import("./nativeTerminalModule"); + expect(resolveNativeTerminalSurfaceView()).toBeNull(); + }); +}); diff --git a/apps/mobile/src/native/terminal/nativeTerminalModule.ts b/apps/mobile/src/native/terminal/nativeTerminalModule.ts new file mode 100644 index 0000000000..85705c790d --- /dev/null +++ b/apps/mobile/src/native/terminal/nativeTerminalModule.ts @@ -0,0 +1,65 @@ +import type { ComponentType } from "react"; +import type { NativeSyntheticEvent, ViewProps } from "react-native"; +import { requireNativeViewManager } from "expo-modules-core"; + +const NATIVE_TERMINAL_MODULE_NAME = "T3TerminalSurface"; + +interface ExpoGlobalWithViewConfig { + readonly expo?: { + getViewConfig?: (moduleName: string, viewName?: string) => unknown; + }; +} + +interface TerminalInputEvent { + readonly data: string; +} + +interface TerminalResizeEvent { + readonly cols: number; + readonly rows: number; +} + +export interface NativeTerminalSurfaceProps extends ViewProps { + readonly appearanceScheme?: "light" | "dark"; + readonly themeConfig?: string; + readonly backgroundColor?: string; + readonly foregroundColor?: string; + readonly mutedForegroundColor?: string; + readonly terminalKey: string; + readonly initialBuffer: string; + readonly fontSize: number; + readonly onInput?: (event: NativeSyntheticEvent) => void; + readonly onResize?: (event: NativeSyntheticEvent) => void; +} + +let cachedNativeTerminalSurfaceView: ComponentType | undefined; + +function getExpoViewConfig(moduleName: string) { + return (globalThis as typeof globalThis & ExpoGlobalWithViewConfig).expo?.getViewConfig?.( + moduleName, + ); +} + +export function resolveNativeTerminalSurfaceView(): ComponentType | null { + if (cachedNativeTerminalSurfaceView) { + return cachedNativeTerminalSurfaceView; + } + + if (getExpoViewConfig(NATIVE_TERMINAL_MODULE_NAME) == null) { + return null; + } + + try { + cachedNativeTerminalSurfaceView = requireNativeViewManager( + NATIVE_TERMINAL_MODULE_NAME, + ); + } catch { + return null; + } + + return cachedNativeTerminalSurfaceView ?? null; +} + +export function hasNativeTerminalSurface() { + return resolveNativeTerminalSurfaceView() !== null; +} diff --git a/apps/mobile/src/native/terminal/terminalTheme.test.ts b/apps/mobile/src/native/terminal/terminalTheme.test.ts new file mode 100644 index 0000000000..40bcb87170 --- /dev/null +++ b/apps/mobile/src/native/terminal/terminalTheme.test.ts @@ -0,0 +1,36 @@ +import { describe, expect, it } from "vitest"; + +import { buildGhosttyThemeConfig, getGitHubTerminalTheme } from "./terminalTheme"; + +describe("getGitHubTerminalTheme", () => { + it("returns the GitHub light terminal palette", () => { + expect(getGitHubTerminalTheme("light")).toMatchObject({ + background: "#ffffff", + foreground: "#586069", + cursorForeground: "#005cc5", + cursorBackground: "#d1d5da", + }); + }); + + it("returns the GitHub dark terminal palette", () => { + expect(getGitHubTerminalTheme("dark")).toMatchObject({ + background: "#24292e", + foreground: "#d1d5da", + cursorForeground: "#79b8ff", + cursorBackground: "#586069", + }); + }); +}); + +describe("buildGhosttyThemeConfig", () => { + it("serializes theme colors into a ghostty config file", () => { + const config = buildGhosttyThemeConfig(getGitHubTerminalTheme("dark")); + + expect(config).toContain("background = #24292e"); + expect(config).toContain("foreground = #d1d5da"); + expect(config).toContain("cursor-color = #79b8ff"); + expect(config).toContain("palette = 0=#586069"); + expect(config).toContain("palette = 15=#fafbfc"); + expect(config.endsWith("\n")).toBe(true); + }); +}); diff --git a/apps/mobile/src/native/terminal/terminalTheme.ts b/apps/mobile/src/native/terminal/terminalTheme.ts new file mode 100644 index 0000000000..3cdae022d3 --- /dev/null +++ b/apps/mobile/src/native/terminal/terminalTheme.ts @@ -0,0 +1,85 @@ +export type TerminalAppearanceScheme = "light" | "dark"; + +export interface TerminalTheme { + readonly background: string; + readonly foreground: string; + readonly mutedForeground: string; + readonly border: string; + readonly cursorForeground: string; + readonly cursorBackground: string; + readonly palette: readonly string[]; +} + +const GITHUB_LIGHT_THEME: TerminalTheme = { + // Sourced from GitHub's official VS Code theme terminal palette. + background: "#ffffff", + foreground: "#586069", + mutedForeground: "#6a737d", + border: "rgba(27,31,35,0.12)", + cursorForeground: "#005cc5", + cursorBackground: "#d1d5da", + palette: [ + "#24292e", + "#d73a49", + "#28a745", + "#dbab09", + "#0366d6", + "#5a32a3", + "#1b7c83", + "#6a737d", + "#959da5", + "#cb2431", + "#22863a", + "#b08800", + "#005cc5", + "#5a32a3", + "#3192aa", + "#d1d5da", + ], +}; + +const GITHUB_DARK_THEME: TerminalTheme = { + background: "#24292e", + foreground: "#d1d5da", + mutedForeground: "#959da5", + border: "rgba(240,246,252,0.12)", + cursorForeground: "#79b8ff", + cursorBackground: "#586069", + palette: [ + "#586069", + "#ea4a5a", + "#34d058", + "#ffea7f", + "#2188ff", + "#b392f0", + "#39c5cf", + "#d1d5da", + "#959da5", + "#f97583", + "#85e89d", + "#ffea7f", + "#79b8ff", + "#b392f0", + "#56d4dd", + "#fafbfc", + ], +}; + +export function getGitHubTerminalTheme(scheme: TerminalAppearanceScheme): TerminalTheme { + return scheme === "light" ? GITHUB_LIGHT_THEME : GITHUB_DARK_THEME; +} + +export function buildGhosttyThemeConfig(theme: TerminalTheme): string { + const lines = [ + `background = ${theme.background}`, + `foreground = ${theme.foreground}`, + `cursor-color = ${theme.cursorForeground}`, + `cursor-text = ${theme.cursorBackground}`, + ]; + + for (const [index, color] of theme.palette.entries()) { + lines.push(`palette = ${index}=${color}`); + } + + return `${lines.join("\n")}\n`; +} diff --git a/apps/mobile/src/state/use-remote-environment-registry.ts b/apps/mobile/src/state/use-remote-environment-registry.ts index 5f697259ef..8cdfcb22f4 100644 --- a/apps/mobile/src/state/use-remote-environment-registry.ts +++ b/apps/mobile/src/state/use-remote-environment-registry.ts @@ -23,6 +23,7 @@ import { appAtomRegistry } from "./atom-registry"; import { type ConnectedEnvironmentSummary, type EnvironmentSession } from "./remote-runtime-types"; import { environmentRuntimeManager, useEnvironmentRuntimeStates } from "./use-environment-runtime"; import { shellSnapshotManager } from "./use-shell-snapshot"; +import { terminalSessionManager } from "./use-terminal-session"; const environmentSessions = new Map(); const environmentConnectionListeners = new Set<() => void>(); @@ -154,6 +155,7 @@ export async function disconnectEnvironment( notifyEnvironmentConnectionListeners(); await session?.connection.dispose(); shellSnapshotManager.invalidate({ environmentId }); + terminalSessionManager.invalidateEnvironment(environmentId); environmentRuntimeManager.invalidate({ environmentId }); if (options?.removeSaved) { @@ -244,7 +246,9 @@ export async function connectSavedEnvironment( onShellResubscribe: (environmentId) => { shellSnapshotManager.markPending({ environmentId }); }, - applyTerminalEvent: () => undefined, + applyTerminalEvent: (event, environmentId) => { + terminalSessionManager.applyEvent({ environmentId }, event); + }, onConfigSnapshot: (serverConfig) => { environmentRuntimeManager.patch({ environmentId: connection.environmentId }, (runtime) => ({ ...runtime, @@ -333,6 +337,7 @@ export function useRemoteEnvironmentBootstrap() { environmentSessions.clear(); environmentRuntimeManager.invalidate(); shellSnapshotManager.invalidate(); + terminalSessionManager.invalidate(); notifyEnvironmentConnectionListeners(); }; }, []); diff --git a/apps/mobile/src/state/use-terminal-session.ts b/apps/mobile/src/state/use-terminal-session.ts new file mode 100644 index 0000000000..41c595eb24 --- /dev/null +++ b/apps/mobile/src/state/use-terminal-session.ts @@ -0,0 +1,63 @@ +import { useAtomValue } from "@effect/atom-react"; +import { + createTerminalSessionManager, + EMPTY_TERMINAL_SESSION_ATOM, + EMPTY_TERMINAL_SESSION_STATE, + getTerminalSessionTargetKey, + knownTerminalSessionsAtom, + terminalSessionStateAtom, + type TerminalSessionState, +} from "@t3tools/client-runtime"; +import { useMemo } from "react"; + +import { appAtomRegistry } from "./atom-registry"; + +export const terminalSessionManager = createTerminalSessionManager({ + getRegistry: () => appAtomRegistry, +}); + +export function useTerminalSession(input: { + readonly environmentId: string | null; + readonly threadId: string | null; + readonly terminalId: string | null; +}): TerminalSessionState { + const targetKey = getTerminalSessionTargetKey(input); + const state = useAtomValue( + targetKey !== null ? terminalSessionStateAtom(targetKey) : EMPTY_TERMINAL_SESSION_ATOM, + ); + return targetKey === null ? EMPTY_TERMINAL_SESSION_STATE : state; +} + +export function useTerminalSessionTarget(input: { + readonly environmentId: string | null; + readonly threadId: string | null; + readonly terminalId: string | null; +}) { + return useMemo( + () => ({ + environmentId: input.environmentId, + threadId: input.threadId, + terminalId: input.terminalId, + }), + [input.environmentId, input.threadId, input.terminalId], + ); +} + +export function useKnownTerminalSessions(input: { + readonly environmentId: string | null; + readonly threadId: string | null; +}) { + const knownSessionsIndex = useAtomValue(knownTerminalSessionsAtom); + + return useMemo(() => { + if (input.environmentId === null || input.threadId === null) { + return []; + } + + void knownSessionsIndex; + return terminalSessionManager.listSessions({ + environmentId: input.environmentId, + threadId: input.threadId, + }); + }, [input.environmentId, input.threadId, knownSessionsIndex]); +} diff --git a/apps/server/src/terminal/Layers/Manager.test.ts b/apps/server/src/terminal/Layers/Manager.test.ts index 9d41c3de20..baaad033fd 100644 --- a/apps/server/src/terminal/Layers/Manager.test.ts +++ b/apps/server/src/terminal/Layers/Manager.test.ts @@ -440,6 +440,32 @@ it.layer(NodeServices.layer, { excludeTestServices: true })("TerminalManager", ( }), ); + it.effect("restarts a running session when open is called with a different cwd", () => + Effect.gen(function* () { + const { manager, ptyAdapter, logsDir, baseDir } = yield* createManager(); + const originalCwd = path.join(baseDir, "original"); + const differentCwd = path.join(baseDir, "different"); + yield* makeDirectory(originalCwd); + yield* makeDirectory(differentCwd); + + yield* manager.open(openInput({ cwd: originalCwd })); + const firstProcess = ptyAdapter.processes[0]; + expect(firstProcess).toBeDefined(); + if (!firstProcess) return; + + firstProcess.emitData("before reopen\n"); + yield* waitFor(pathExists(historyLogPath(logsDir))); + + const reopened = yield* manager.open(openInput({ cwd: differentCwd })); + + expect(ptyAdapter.spawnInputs).toHaveLength(2); + assert.equal(firstProcess.killed, true); + assert.equal(reopened.cwd, differentCwd); + assert.equal(reopened.history, ""); + yield* waitFor(Effect.map(readFileString(historyLogPath(logsDir)), (text) => text === "")); + }), + ); + it.effect("propagates explicit worktree metadata through snapshots and lifecycle events", () => Effect.gen(function* () { const { manager, getEvents, baseDir } = yield* createManager(); @@ -778,6 +804,21 @@ it.layer(NodeServices.layer, { excludeTestServices: true })("TerminalManager", ( }).pipe(Effect.provide(TestClock.layer())), ); + it.effect("publishes closed events when terminals are explicitly closed", () => + Effect.gen(function* () { + const { manager, getEvents } = yield* createManager(); + yield* manager.open(openInput({ terminalId: "default" })); + yield* manager.open(openInput({ terminalId: "sidecar" })); + + yield* manager.close({ threadId: "thread-1" }); + + const closedEvents = (yield* getEvents).filter( + (event): event is Extract => event.type === "closed", + ); + expect(closedEvents.map((event) => event.terminalId).sort()).toEqual(["default", "sidecar"]); + }), + ); + it.effect("evicts oldest inactive terminal sessions when retention limit is exceeded", () => Effect.gen(function* () { const { manager, ptyAdapter, logsDir, getEvents } = yield* createManager(5, { diff --git a/apps/server/src/terminal/Layers/Manager.ts b/apps/server/src/terminal/Layers/Manager.ts index 5e14db8e5c..cda9f711de 100644 --- a/apps/server/src/terminal/Layers/Manager.ts +++ b/apps/server/src/terminal/Layers/Manager.ts @@ -1484,15 +1484,24 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith yield* flushPersist(threadId, terminalId); - yield* modifyManagerState((state) => { + const removed = yield* modifyManagerState((state) => { if (!state.sessions.has(key)) { - return [undefined, state] as const; + return [false, state] as const; } const sessions = new Map(state.sessions); sessions.delete(key); - return [undefined, { ...state, sessions }] as const; + return [true, { ...state, sessions }] as const; }); + if (removed) { + yield* publishEvent({ + type: "closed", + threadId, + terminalId, + createdAt: new Date().toISOString(), + }); + } + if (deleteHistoryOnClose) { yield* deleteHistory(threadId, terminalId); } @@ -1683,11 +1692,19 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith const targetCols = input.cols ?? liveSession.cols; const targetRows = input.rows ?? liveSession.rows; const runtimeEnvChanged = !Equal.equals(currentRuntimeEnv, nextRuntimeEnv); + const nextWorktreePath = + input.worktreePath !== undefined + ? (input.worktreePath ?? null) + : liveSession.worktreePath; + const launchContextChanged = + liveSession.cwd !== input.cwd || + runtimeEnvChanged || + liveSession.worktreePath !== nextWorktreePath; - if (liveSession.cwd !== input.cwd || runtimeEnvChanged) { + if (launchContextChanged) { yield* stopProcess(liveSession); liveSession.cwd = input.cwd; - liveSession.worktreePath = input.worktreePath ?? null; + liveSession.worktreePath = nextWorktreePath; liveSession.runtimeEnv = nextRuntimeEnv; liveSession.history = ""; liveSession.pendingHistoryControlSequence = ""; @@ -1701,7 +1718,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith ); } else if (liveSession.status === "exited" || liveSession.status === "error") { liveSession.runtimeEnv = nextRuntimeEnv; - liveSession.worktreePath = input.worktreePath ?? null; + liveSession.worktreePath = nextWorktreePath; liveSession.history = ""; liveSession.pendingHistoryControlSequence = ""; liveSession.pendingProcessEvents = []; diff --git a/apps/web/src/components/ThreadTerminalDrawer.tsx b/apps/web/src/components/ThreadTerminalDrawer.tsx index 6c71e5eb33..0c6e36248a 100644 --- a/apps/web/src/components/ThreadTerminalDrawer.tsx +++ b/apps/web/src/components/ThreadTerminalDrawer.tsx @@ -602,16 +602,21 @@ export function TerminalViewport({ return; } - const details = [ - typeof event.exitCode === "number" ? `code ${event.exitCode}` : null, - typeof event.exitSignal === "number" ? `signal ${event.exitSignal}` : null, - ] - .filter((value): value is string => value !== null) - .join(", "); - writeSystemMessage( - activeTerminal, - details.length > 0 ? `Process exited (${details})` : "Process exited", - ); + if (event.type === "closed") { + writeSystemMessage(activeTerminal, "Terminal closed"); + } else { + const details = [ + typeof event.exitCode === "number" ? `code ${event.exitCode}` : null, + typeof event.exitSignal === "number" ? `signal ${event.exitSignal}` : null, + ] + .filter((value): value is string => value !== null) + .join(", "); + writeSystemMessage( + activeTerminal, + details.length > 0 ? `Process exited (${details})` : "Process exited", + ); + } + if (hasHandledExitRef.current) { return; } diff --git a/apps/web/src/terminalActivity.ts b/apps/web/src/terminalActivity.ts index 24f4984ff5..55881e9056 100644 --- a/apps/web/src/terminalActivity.ts +++ b/apps/web/src/terminalActivity.ts @@ -7,6 +7,7 @@ export function terminalRunningSubprocessFromEvent(event: TerminalEvent): boolea case "started": case "restarted": case "exited": + case "closed": return false; default: return null; diff --git a/apps/web/src/terminalStateStore.test.ts b/apps/web/src/terminalStateStore.test.ts index eceb621ac7..bd9e5eaf31 100644 --- a/apps/web/src/terminalStateStore.test.ts +++ b/apps/web/src/terminalStateStore.test.ts @@ -34,6 +34,8 @@ function makeTerminalEvent( return { ...base, type, ...overrides } as TerminalEvent; case "exited": return { ...base, type, exitCode: 0, exitSignal: null, ...overrides } as TerminalEvent; + case "closed": + return { ...base, type, ...overrides } as TerminalEvent; case "started": case "restarted": return { diff --git a/bun.lock b/bun.lock index 2726f88873..1f01a8a61f 100644 --- a/bun.lock +++ b/bun.lock @@ -57,11 +57,13 @@ "@shikijs/themes": "3.23.0", "@t3tools/client-runtime": "workspace:*", "@t3tools/contracts": "workspace:*", + "@t3tools/mobile-terminal-native": "file:./modules/t3-terminal", "@t3tools/shared": "workspace:*", "clsx": "^2.1.1", "diff": "8.0.3", "effect": "catalog:", "expo": "~55.0.14", + "expo-build-properties": "~55.0.13", "expo-camera": "~55.0.15", "expo-clipboard": "~55.0.9", "expo-constants": "^55.0.9", @@ -72,6 +74,7 @@ "expo-haptics": "^55.0.9", "expo-image-picker": "~55.0.14", "expo-linking": "~55.0.12", + "expo-modules-core": "~55.0.22", "expo-paste-input": "^0.1.15", "expo-router": "~55.0.12", "expo-secure-store": "~55.0.9", @@ -1662,6 +1665,8 @@ "expo-asset": ["expo-asset@55.0.15", "", { "dependencies": { "@expo/image-utils": "^0.8.13", "expo-constants": "~55.0.14" }, "peerDependencies": { "expo": "*", "react": "*", "react-native": "*" } }, "sha512-d3FIpHJ6ZngYXxRItYWBGT5H8Wkk7/l4fMe8Mmd2xDyKrO0/CM7c8r/J5M71D+BJr5P3My8wertGYZXHSiZYxQ=="], + "expo-build-properties": ["expo-build-properties@55.0.13", "", { "dependencies": { "@expo/schema-utils": "^55.0.3", "resolve-from": "^5.0.0", "semver": "^7.6.0" }, "peerDependencies": { "expo": "*" } }, "sha512-UYZhUKyh7YQhbJdkBvo68WUQ7fOtZeSV7F8kfYkjEiN/ADRHG0WfEIiddvGfi9cH/5iwpptv/+Lu5cx6uvfegA=="], + "expo-camera": ["expo-camera@55.0.15", "", { "dependencies": { "barcode-detector": "^3.0.0" }, "peerDependencies": { "expo": "*", "react": "*", "react-native": "*", "react-native-web": "*" }, "optionalPeers": ["react-native-web"] }, "sha512-WRVsZf+2p7EsxudwyiUMYijJS8M98t/BVP6yG7N+08JSUotkGjmZcemom1gM36uy27P8QsSVP0hD+FravmQiBA=="], "expo-clipboard": ["expo-clipboard@55.0.13", "", { "peerDependencies": { "expo": "*", "react": "*", "react-native": "*" } }, "sha512-PrOmmuVsGW4bAkNQmGKtxMXj3invsfN+jfIKmQxHwE/dn7ODqwFWviUTa+PMUjP3XZmYCDLyu/i0GLeu7HF9Ew=="], @@ -3032,6 +3037,8 @@ "@shikijs/primitive/@shikijs/types": ["@shikijs/types@4.0.2", "", { "dependencies": { "@shikijs/vscode-textmate": "^10.0.2", "@types/hast": "^3.0.4" } }, "sha512-qzbeRooUTPnLE+sHD/Z8DStmaDgnbbc/pMrU203950aRqjX/6AFHeDYT+j00y2lPdz0ywJKx7o/7qnqTivtlXg=="], + "@t3tools/mobile/@t3tools/mobile-terminal-native": ["@t3tools/mobile-terminal-native@file:apps/mobile/modules/t3-terminal", {}], + "@tailwindcss/node/tailwindcss": ["tailwindcss@4.2.1", "", {}, "sha512-/tBrSQ36vCleJkAOsy9kbNTgaxvGbyOamC30PRePTQe/o1MFwEKHQk4Cn7BNGaPtjp+PuUrByJehM1hgxfq4sw=="], "@tailwindcss/oxide-wasm32-wasi/@emnapi/core": ["@emnapi/core@1.9.2", "", { "dependencies": { "@emnapi/wasi-threads": "1.2.1", "tslib": "^2.4.0" }, "bundled": true }, "sha512-UC+ZhH3XtczQYfOlu3lNEkdW/p4dsJ1r/bP7H8+rhao3TTTMO1ATq/4DdIi23XuGoFY+Cz0JmCbdVl0hz9jZcA=="], diff --git a/packages/client-runtime/src/index.ts b/packages/client-runtime/src/index.ts index e7db41bbcd..76bb3a80f2 100644 --- a/packages/client-runtime/src/index.ts +++ b/packages/client-runtime/src/index.ts @@ -11,6 +11,7 @@ export * from "./gitActions.ts"; export * from "./gitActionState.ts"; export * from "./gitBranchState.ts"; export * from "./gitStatusState.ts"; +export * from "./terminalSessionState.ts"; export * from "./transportError.ts"; export * from "./wsRpcProtocol.ts"; export * from "./wsTransport.ts"; diff --git a/packages/client-runtime/src/terminalSessionState.test.ts b/packages/client-runtime/src/terminalSessionState.test.ts new file mode 100644 index 0000000000..79d7c3157a --- /dev/null +++ b/packages/client-runtime/src/terminalSessionState.test.ts @@ -0,0 +1,276 @@ +import { AtomRegistry } from "effect/unstable/reactivity"; +import { afterEach, describe, expect, it } from "vitest"; + +import type { TerminalSessionSnapshot } from "@t3tools/contracts"; + +import { createTerminalSessionManager } from "./terminalSessionState"; + +let atomRegistry = AtomRegistry.make(); + +function resetAtomRegistry() { + atomRegistry.dispose(); + atomRegistry = AtomRegistry.make(); +} + +const TARGET = { + environmentId: "env-local", + threadId: "thread-1", + terminalId: "default", +} as const; + +const BASE_SNAPSHOT: TerminalSessionSnapshot = { + threadId: TARGET.threadId, + terminalId: TARGET.terminalId, + cwd: "/repo", + worktreePath: null, + status: "running", + pid: 123, + history: "hello", + exitCode: null, + exitSignal: null, + updatedAt: "2026-04-01T00:00:00.000Z", +}; + +describe("createTerminalSessionManager", () => { + afterEach(() => { + resetAtomRegistry(); + }); + + it("hydrates from started snapshots and appends output events", () => { + const manager = createTerminalSessionManager({ + getRegistry: () => atomRegistry, + }); + + manager.applyEvent(TARGET, { + type: "started", + threadId: TARGET.threadId, + terminalId: TARGET.terminalId, + createdAt: BASE_SNAPSHOT.updatedAt, + snapshot: BASE_SNAPSHOT, + }); + manager.applyEvent(TARGET, { + type: "output", + threadId: TARGET.threadId, + terminalId: TARGET.terminalId, + createdAt: "2026-04-01T00:00:01.000Z", + data: " world", + }); + + expect(manager.getSnapshot(TARGET)).toMatchObject({ + snapshot: BASE_SNAPSHOT, + buffer: "hello world", + status: "running", + error: null, + updatedAt: "2026-04-01T00:00:01.000Z", + }); + }); + + it("caps retained output", () => { + const manager = createTerminalSessionManager({ + getRegistry: () => atomRegistry, + maxBufferBytes: 5, + }); + + manager.applyEvent(TARGET, { + type: "output", + threadId: TARGET.threadId, + terminalId: TARGET.terminalId, + createdAt: "2026-04-01T00:00:01.000Z", + data: "abcdef", + }); + + expect(manager.getSnapshot(TARGET).buffer).toBe("bcdef"); + }); + + it("caps retained output by utf-8 byte length", () => { + const manager = createTerminalSessionManager({ + getRegistry: () => atomRegistry, + maxBufferBytes: 4, + }); + + manager.applyEvent(TARGET, { + type: "output", + threadId: TARGET.threadId, + terminalId: TARGET.terminalId, + createdAt: "2026-04-01T00:00:01.000Z", + data: "🙂🙂", + }); + + expect(manager.getSnapshot(TARGET).buffer).toBe("🙂"); + }); + + it("invalidates one environment without clearing others", () => { + const manager = createTerminalSessionManager({ + getRegistry: () => atomRegistry, + }); + const otherTarget = { + environmentId: "env-remote", + threadId: "thread-1", + terminalId: "default", + } as const; + + for (const target of [TARGET, otherTarget]) { + manager.applyEvent(target, { + type: "output", + threadId: target.threadId, + terminalId: target.terminalId, + createdAt: "2026-04-01T00:00:01.000Z", + data: target.environmentId, + }); + } + + manager.invalidateEnvironment(TARGET.environmentId); + + expect(manager.getSnapshot(TARGET).buffer).toBe(""); + expect(manager.getSnapshot(otherTarget).buffer).toBe("env-remote"); + }); + + it("lists known sessions for a thread ordered by recency", () => { + const manager = createTerminalSessionManager({ + getRegistry: () => atomRegistry, + }); + + manager.applyEvent(TARGET, { + type: "started", + threadId: TARGET.threadId, + terminalId: TARGET.terminalId, + createdAt: "2026-04-01T00:00:00.000Z", + snapshot: BASE_SNAPSHOT, + }); + manager.applyEvent( + { + environmentId: TARGET.environmentId, + }, + { + type: "started", + threadId: TARGET.threadId, + terminalId: "term-2", + createdAt: "2026-04-01T00:00:02.000Z", + snapshot: { + ...BASE_SNAPSHOT, + terminalId: "term-2", + updatedAt: "2026-04-01T00:00:02.000Z", + }, + }, + ); + + expect( + manager + .listSessions({ + environmentId: TARGET.environmentId, + threadId: TARGET.threadId, + }) + .map((session) => session.target.terminalId), + ).toEqual(["term-2", "default"]); + }); + + it("drops known sessions when an environment is invalidated", () => { + const manager = createTerminalSessionManager({ + getRegistry: () => atomRegistry, + }); + + manager.applyEvent(TARGET, { + type: "output", + threadId: TARGET.threadId, + terminalId: TARGET.terminalId, + createdAt: "2026-04-01T00:00:01.000Z", + data: "hello", + }); + + manager.invalidateEnvironment(TARGET.environmentId); + + expect( + manager.listSessions({ + environmentId: TARGET.environmentId, + threadId: TARGET.threadId, + }), + ).toEqual([]); + }); + + it("removes closed sessions from the known-session index while keeping local closed state", () => { + const manager = createTerminalSessionManager({ + getRegistry: () => atomRegistry, + }); + + manager.applyEvent(TARGET, { + type: "started", + threadId: TARGET.threadId, + terminalId: TARGET.terminalId, + createdAt: BASE_SNAPSHOT.updatedAt, + snapshot: BASE_SNAPSHOT, + }); + + manager.applyEvent(TARGET, { + type: "closed", + threadId: TARGET.threadId, + terminalId: TARGET.terminalId, + createdAt: "2026-04-01T00:00:04.000Z", + }); + + expect( + manager.listSessions({ + environmentId: TARGET.environmentId, + threadId: TARGET.threadId, + }), + ).toEqual([]); + expect(manager.getSnapshot(TARGET)).toMatchObject({ + buffer: "hello", + status: "closed", + snapshot: null, + updatedAt: "2026-04-01T00:00:04.000Z", + }); + }); + + it("clears locally retained closed state on reset", () => { + const manager = createTerminalSessionManager({ + getRegistry: () => atomRegistry, + }); + + manager.applyEvent(TARGET, { + type: "started", + threadId: TARGET.threadId, + terminalId: TARGET.terminalId, + createdAt: BASE_SNAPSHOT.updatedAt, + snapshot: BASE_SNAPSHOT, + }); + manager.applyEvent(TARGET, { + type: "closed", + threadId: TARGET.threadId, + terminalId: TARGET.terminalId, + createdAt: "2026-04-01T00:00:04.000Z", + }); + + manager.reset(); + + expect(manager.getSnapshot(TARGET)).toEqual({ + snapshot: null, + buffer: "", + status: "closed", + error: null, + hasRunningSubprocess: false, + updatedAt: null, + version: 0, + }); + }); + + it("syncs snapshots returned from open calls immediately", () => { + const manager = createTerminalSessionManager({ + getRegistry: () => atomRegistry, + }); + + manager.syncSnapshot( + { environmentId: TARGET.environmentId }, + { + ...BASE_SNAPSHOT, + history: "prompt$ ", + updatedAt: "2026-04-01T00:00:03.000Z", + }, + ); + + expect(manager.getSnapshot(TARGET)).toMatchObject({ + buffer: "prompt$ ", + status: "running", + updatedAt: "2026-04-01T00:00:03.000Z", + }); + }); +}); diff --git a/packages/client-runtime/src/terminalSessionState.ts b/packages/client-runtime/src/terminalSessionState.ts new file mode 100644 index 0000000000..d246e4fbdc --- /dev/null +++ b/packages/client-runtime/src/terminalSessionState.ts @@ -0,0 +1,404 @@ +import type { TerminalEvent, TerminalSessionSnapshot } from "@t3tools/contracts"; +import { Atom, type AtomRegistry } from "effect/unstable/reactivity"; + +export interface TerminalSessionState { + readonly snapshot: TerminalSessionSnapshot | null; + readonly buffer: string; + readonly status: TerminalSessionSnapshot["status"] | "closed"; + readonly error: string | null; + readonly hasRunningSubprocess: boolean; + readonly updatedAt: string | null; + readonly version: number; +} + +export interface TerminalSessionTarget { + readonly environmentId: string | null; + readonly threadId: string | null; + readonly terminalId: string | null; +} + +export interface KnownTerminalSessionTarget { + readonly environmentId: string; + readonly threadId: string; + readonly terminalId: string; +} + +export interface KnownTerminalSession { + readonly target: KnownTerminalSessionTarget; + readonly state: TerminalSessionState; +} + +export interface TerminalSessionManagerConfig { + readonly getRegistry: () => AtomRegistry.AtomRegistry; + readonly maxBufferBytes?: number; +} + +export const EMPTY_TERMINAL_SESSION_STATE = Object.freeze({ + snapshot: null, + buffer: "", + status: "closed", + error: null, + hasRunningSubprocess: false, + updatedAt: null, + version: 0, +}); + +const DEFAULT_MAX_BUFFER_BYTES = 512 * 1024; +const knownTerminalSessionKeys = new Set(); +const textEncoder = new TextEncoder(); +const textDecoder = new TextDecoder(); + +export const terminalSessionStateAtom = Atom.family((key: string) => { + knownTerminalSessionKeys.add(key); + return Atom.make(EMPTY_TERMINAL_SESSION_STATE).pipe( + Atom.keepAlive, + Atom.withLabel(`terminal-session:${key}`), + ); +}); + +export const EMPTY_TERMINAL_SESSION_ATOM = Atom.make(EMPTY_TERMINAL_SESSION_STATE).pipe( + Atom.keepAlive, + Atom.withLabel("terminal-session:null"), +); + +export const knownTerminalSessionsAtom = Atom.make>( + {}, +).pipe(Atom.keepAlive, Atom.withLabel("terminal-session:index")); + +export function getTerminalSessionTargetKey(target: TerminalSessionTarget): string | null { + if (target.environmentId === null || target.threadId === null || target.terminalId === null) { + return null; + } + + return `${target.environmentId}:${target.threadId}:${target.terminalId}`; +} + +function toKnownTarget(target: TerminalSessionTarget): KnownTerminalSessionTarget | null { + const targetKey = getTerminalSessionTargetKey(target); + if (targetKey === null) { + return null; + } + + const environmentId = target.environmentId; + const threadId = target.threadId; + const terminalId = target.terminalId; + if (environmentId === null || threadId === null || terminalId === null) { + return null; + } + + return { + environmentId, + threadId, + terminalId, + }; +} + +function trimBufferToBytes(buffer: string, maxBufferBytes: number): string { + if (maxBufferBytes <= 0) { + return ""; + } + + const encoded = textEncoder.encode(buffer); + if (encoded.byteLength <= maxBufferBytes) { + return buffer; + } + + let start = encoded.byteLength - maxBufferBytes; + while (start < encoded.length) { + const byte = encoded[start]; + if (byte === undefined || (byte & 0b1100_0000) !== 0b1000_0000) { + break; + } + start += 1; + } + + return textDecoder.decode(encoded.subarray(start)); +} + +function stateFromSnapshot( + snapshot: TerminalSessionSnapshot, + maxBufferBytes: number, +): TerminalSessionState { + return { + snapshot, + buffer: trimBufferToBytes(snapshot.history, maxBufferBytes), + status: snapshot.status, + error: null, + hasRunningSubprocess: false, + updatedAt: snapshot.updatedAt, + version: 1, + }; +} + +export function createTerminalSessionManager(config: TerminalSessionManagerConfig) { + const maxBufferBytes = config.maxBufferBytes ?? DEFAULT_MAX_BUFFER_BYTES; + const closedSessionStates = new Map(); + + function clearKnownSessionAtomState(targetKey: string): void { + knownTerminalSessionKeys.delete(targetKey); + config.getRegistry().set(terminalSessionStateAtom(targetKey), EMPTY_TERMINAL_SESSION_STATE); + } + + function rememberTarget(target: TerminalSessionTarget): string | null { + const targetKey = getTerminalSessionTargetKey(target); + const knownTarget = toKnownTarget(target); + if (targetKey === null || knownTarget === null) { + return null; + } + + closedSessionStates.delete(targetKey); + + const current = config.getRegistry().get(knownTerminalSessionsAtom); + const existing = current[targetKey]; + if ( + existing?.environmentId === knownTarget.environmentId && + existing.threadId === knownTarget.threadId && + existing.terminalId === knownTarget.terminalId + ) { + return targetKey; + } + + config.getRegistry().set(knownTerminalSessionsAtom, { + ...current, + [targetKey]: knownTarget, + }); + return targetKey; + } + + function removeTargets( + match: (target: KnownTerminalSessionTarget) => boolean, + ): ReadonlyArray { + const current = config.getRegistry().get(knownTerminalSessionsAtom); + const removedKeys: string[] = []; + const next = Object.fromEntries( + Object.entries(current).filter(([key, target]) => { + const shouldRemove = match(target); + if (shouldRemove) { + removedKeys.push(key); + } + return !shouldRemove; + }), + ) as Record; + if (Object.keys(next).length === Object.keys(current).length) { + return removedKeys; + } + + config.getRegistry().set(knownTerminalSessionsAtom, next); + return removedKeys; + } + + function getSnapshot(target: TerminalSessionTarget): TerminalSessionState { + const targetKey = getTerminalSessionTargetKey(target); + if (targetKey === null) { + return EMPTY_TERMINAL_SESSION_STATE; + } + + const closedState = closedSessionStates.get(targetKey); + if (closedState) { + return closedState; + } + + const rememberedTargetKey = rememberTarget(target); + if (rememberedTargetKey === null) { + return EMPTY_TERMINAL_SESSION_STATE; + } + + return config.getRegistry().get(terminalSessionStateAtom(rememberedTargetKey)); + } + + function setState(targetKey: string, nextState: TerminalSessionState): void { + config.getRegistry().set(terminalSessionStateAtom(targetKey), nextState); + } + + function syncSnapshot( + target: Pick, + snapshot: TerminalSessionSnapshot, + ): void { + const targetKey = rememberTarget({ + environmentId: target.environmentId, + threadId: snapshot.threadId, + terminalId: snapshot.terminalId, + }); + if (targetKey === null) { + return; + } + + setState(targetKey, stateFromSnapshot(snapshot, maxBufferBytes)); + } + + function applyEvent( + target: Pick, + event: TerminalEvent, + ): void { + const targetKey = rememberTarget({ + environmentId: target.environmentId, + threadId: event.threadId, + terminalId: event.terminalId, + }); + if (targetKey === null) { + return; + } + + const current = config.getRegistry().get(terminalSessionStateAtom(targetKey)); + switch (event.type) { + case "started": + case "restarted": + setState(targetKey, stateFromSnapshot(event.snapshot, maxBufferBytes)); + return; + case "output": + setState(targetKey, { + ...current, + buffer: trimBufferToBytes(`${current.buffer}${event.data}`, maxBufferBytes), + status: current.status === "closed" ? "running" : current.status, + error: null, + updatedAt: event.createdAt, + version: current.version + 1, + }); + return; + case "cleared": + setState(targetKey, { + ...current, + buffer: "", + error: null, + updatedAt: event.createdAt, + version: current.version + 1, + }); + return; + case "exited": + setState(targetKey, { + ...current, + snapshot: current.snapshot + ? { + ...current.snapshot, + status: "exited", + exitCode: event.exitCode, + exitSignal: event.exitSignal, + updatedAt: event.createdAt, + } + : null, + status: "exited", + hasRunningSubprocess: false, + updatedAt: event.createdAt, + version: current.version + 1, + }); + return; + case "closed": + closedSessionStates.set(targetKey, { + ...current, + snapshot: null, + status: "closed", + error: null, + hasRunningSubprocess: false, + updatedAt: event.createdAt, + version: current.version + 1, + }); + clearKnownSessionAtomState(targetKey); + removeTargets( + (knownTarget) => + knownTarget.environmentId === target.environmentId && + knownTarget.threadId === event.threadId && + knownTarget.terminalId === event.terminalId, + ); + return; + case "error": + setState(targetKey, { + ...current, + status: "error", + error: event.message, + hasRunningSubprocess: false, + updatedAt: event.createdAt, + version: current.version + 1, + }); + return; + case "activity": + setState(targetKey, { + ...current, + hasRunningSubprocess: event.hasRunningSubprocess, + updatedAt: event.createdAt, + version: current.version + 1, + }); + return; + } + } + + function invalidate(target?: TerminalSessionTarget): void { + if (target) { + const targetKey = getTerminalSessionTargetKey(target); + if (targetKey !== null) { + closedSessionStates.delete(targetKey); + setState(targetKey, EMPTY_TERMINAL_SESSION_STATE); + } + return; + } + + for (const key of knownTerminalSessionKeys) { + setState(key, EMPTY_TERMINAL_SESSION_STATE); + } + closedSessionStates.clear(); + knownTerminalSessionKeys.clear(); + config.getRegistry().set(knownTerminalSessionsAtom, {}); + } + + function invalidateEnvironment(environmentId: string): void { + const prefix = `${environmentId}:`; + for (const key of knownTerminalSessionKeys) { + if (key.startsWith(prefix)) { + setState(key, EMPTY_TERMINAL_SESSION_STATE); + } + } + for (const key of closedSessionStates.keys()) { + if (key.startsWith(prefix)) { + closedSessionStates.delete(key); + } + } + for (const key of removeTargets((target) => target.environmentId === environmentId)) { + closedSessionStates.delete(key); + clearKnownSessionAtomState(key); + } + } + + function reset(): void { + invalidate(); + } + + function listSessions( + filter?: Partial, + ): ReadonlyArray { + const knownTargets = Object.values(config.getRegistry().get(knownTerminalSessionsAtom)); + return knownTargets + .filter((target) => { + if (filter?.environmentId && target.environmentId !== filter.environmentId) { + return false; + } + if (filter?.threadId && target.threadId !== filter.threadId) { + return false; + } + if (filter?.terminalId && target.terminalId !== filter.terminalId) { + return false; + } + return true; + }) + .map((target) => ({ + target, + state: getSnapshot(target), + })) + .sort((left, right) => { + const leftUpdatedAt = left.state.updatedAt ? Date.parse(left.state.updatedAt) : 0; + const rightUpdatedAt = right.state.updatedAt ? Date.parse(right.state.updatedAt) : 0; + if (leftUpdatedAt !== rightUpdatedAt) { + return rightUpdatedAt - leftUpdatedAt; + } + return left.target.terminalId.localeCompare(right.target.terminalId); + }); + } + + return { + applyEvent, + getSnapshot, + invalidate, + invalidateEnvironment, + listSessions, + syncSnapshot, + reset, + }; +} diff --git a/packages/contracts/src/terminal.test.ts b/packages/contracts/src/terminal.test.ts index 3feae67492..95403f14c1 100644 --- a/packages/contracts/src/terminal.test.ts +++ b/packages/contracts/src/terminal.test.ts @@ -197,6 +197,17 @@ describe("TerminalEvent", () => { ).toBe(true); }); + it("accepts closed events", () => { + expect( + decodes(TerminalEvent, { + type: "closed", + threadId: "thread-1", + terminalId: DEFAULT_TERMINAL_ID, + createdAt: new Date().toISOString(), + }), + ).toBe(true); + }); + it("accepts activity events", () => { expect( decodes(TerminalEvent, { diff --git a/packages/contracts/src/terminal.ts b/packages/contracts/src/terminal.ts index 21bd74a099..72d63ff1aa 100644 --- a/packages/contracts/src/terminal.ts +++ b/packages/contracts/src/terminal.ts @@ -119,6 +119,11 @@ const TerminalExitedEvent = Schema.Struct({ exitSignal: Schema.NullOr(Schema.Int), }); +const TerminalClosedEvent = Schema.Struct({ + ...TerminalEventBaseSchema.fields, + type: Schema.Literal("closed"), +}); + const TerminalErrorEvent = Schema.Struct({ ...TerminalEventBaseSchema.fields, type: Schema.Literal("error"), @@ -146,6 +151,7 @@ export const TerminalEvent = Schema.Union([ TerminalStartedEvent, TerminalOutputEvent, TerminalExitedEvent, + TerminalClosedEvent, TerminalErrorEvent, TerminalClearedEvent, TerminalRestartedEvent,