feat(mobile): Add terminal powered by libghostty (#2056)
Co-authored-by: Julius Marminge <[email protected]>
This commit is contained in:
1 parent
d686613e34
commit
da6ea88331
84 files changed
+10510
-66
No files matched your search
@@ -114,6 +114,14 @@ const config: ExpoConfig = {
|
||||
},
|
||||
},
|
||||
],
|
||||
[
|
||||
"expo-build-properties",
|
||||
{
|
||||
ios: {
|
||||
deploymentTarget: "16.1",
|
||||
},
|
||||
},
|
||||
],
|
||||
"expo-secure-store",
|
||||
"expo-router",
|
||||
"./plugins/withAndroidCleartextTraffic.cjs",
|
||||
|
||||
@@ -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`.
|
||||
@@ -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' => '[email protected]' }
|
||||
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
|
||||
@@ -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`.
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>AvailableLibraries</key>
|
||||
<array>
|
||||
<dict>
|
||||
<key>BinaryPath</key>
|
||||
<string>libghostty-fat.a</string>
|
||||
<key>HeadersPath</key>
|
||||
<string>Headers</string>
|
||||
<key>LibraryIdentifier</key>
|
||||
<string>ios-arm64</string>
|
||||
<key>LibraryPath</key>
|
||||
<string>libghostty-fat.a</string>
|
||||
<key>SupportedArchitectures</key>
|
||||
<array>
|
||||
<string>arm64</string>
|
||||
</array>
|
||||
<key>SupportedPlatform</key>
|
||||
<string>ios</string>
|
||||
</dict>
|
||||
<dict>
|
||||
<key>BinaryPath</key>
|
||||
<string>libghostty-fat.a</string>
|
||||
<key>HeadersPath</key>
|
||||
<string>Headers</string>
|
||||
<key>LibraryIdentifier</key>
|
||||
<string>ios-arm64-simulator</string>
|
||||
<key>LibraryPath</key>
|
||||
<string>libghostty-fat.a</string>
|
||||
<key>SupportedArchitectures</key>
|
||||
<array>
|
||||
<string>arm64</string>
|
||||
</array>
|
||||
<key>SupportedPlatform</key>
|
||||
<string>ios</string>
|
||||
<key>SupportedPlatformVariant</key>
|
||||
<string>simulator</string>
|
||||
</dict>
|
||||
</array>
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>XFWK</string>
|
||||
<key>XCFrameworkFormatVersion</key>
|
||||
<string>1.0</string>
|
||||
</dict>
|
||||
</plist>
|
||||
+1187
File diff suppressed because it is too large.
Load diff
+87
@@ -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 <ghostty/vt/result.h>
|
||||
#include <ghostty/vt/allocator.h>
|
||||
#include <ghostty/vt/osc.h>
|
||||
#include <ghostty/vt/sgr.h>
|
||||
#include <ghostty/vt/key.h>
|
||||
#include <ghostty/vt/paste.h>
|
||||
#include <ghostty/vt/wasm.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* GHOSTTY_VT_H */
|
||||
+196
@@ -0,0 +1,196 @@
|
||||
/**
|
||||
* @file allocator.h
|
||||
*
|
||||
* Memory management interface for libghostty-vt.
|
||||
*/
|
||||
|
||||
#ifndef GHOSTTY_VT_ALLOCATOR_H
|
||||
#define GHOSTTY_VT_ALLOCATOR_H
|
||||
|
||||
#include <stdbool.h>
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
/** @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 */
|
||||
+96
@@ -0,0 +1,96 @@
|
||||
/**
|
||||
* @file color.h
|
||||
*
|
||||
* Color types and utilities.
|
||||
*/
|
||||
|
||||
#ifndef GHOSTTY_VT_COLOR_H
|
||||
#define GHOSTTY_VT_COLOR_H
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
#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 */
|
||||
+80
@@ -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 <assert.h>
|
||||
* #include <stdio.h>
|
||||
* #include <ghostty/vt.h>
|
||||
*
|
||||
* 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 <ghostty/vt/key/event.h>
|
||||
#include <ghostty/vt/key/encoder.h>
|
||||
|
||||
/** @} */
|
||||
|
||||
#endif /* GHOSTTY_VT_KEY_H */
|
||||
+221
@@ -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 <stddef.h>
|
||||
#include <stdint.h>
|
||||
#include <ghostty/vt/result.h>
|
||||
#include <ghostty/vt/allocator.h>
|
||||
#include <ghostty/vt/key/event.h>
|
||||
|
||||
/**
|
||||
* 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 */
|
||||
+474
@@ -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 <stdbool.h>
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
#include <ghostty/vt/result.h>
|
||||
#include <ghostty/vt/allocator.h>
|
||||
|
||||
/**
|
||||
* 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 */
|
||||
+233
@@ -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 <stdbool.h>
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
#include <ghostty/vt/result.h>
|
||||
#include <ghostty/vt/allocator.h>
|
||||
|
||||
/**
|
||||
* 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 */
|
||||
+75
@@ -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 <stdio.h>
|
||||
* #include <string.h>
|
||||
* #include <ghostty/vt.h>
|
||||
*
|
||||
* 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 <stdbool.h>
|
||||
#include <stddef.h>
|
||||
|
||||
#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 */
|
||||
+22
@@ -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 */
|
||||
+394
@@ -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 <assert.h>
|
||||
* #include <stdio.h>
|
||||
* #include <ghostty/vt.h>
|
||||
*
|
||||
* 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 <ghostty/vt/allocator.h>
|
||||
#include <ghostty/vt/color.h>
|
||||
#include <ghostty/vt/result.h>
|
||||
#include <stdbool.h>
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
#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 */
|
||||
+159
@@ -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 <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
/** @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 */
|
||||
+7
@@ -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 *
|
||||
}
|
||||
BIN
Binary file not shown.
apps/mobile/modules/t3-terminal/Vendor/libghostty/GhosttyKit.xcframework/ios-arm64/Headers/ghostty.h
Vendored
+1187
File diff suppressed because it is too large.
Load diff
+87
@@ -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 <ghostty/vt/result.h>
|
||||
#include <ghostty/vt/allocator.h>
|
||||
#include <ghostty/vt/osc.h>
|
||||
#include <ghostty/vt/sgr.h>
|
||||
#include <ghostty/vt/key.h>
|
||||
#include <ghostty/vt/paste.h>
|
||||
#include <ghostty/vt/wasm.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* GHOSTTY_VT_H */
|
||||
+196
@@ -0,0 +1,196 @@
|
||||
/**
|
||||
* @file allocator.h
|
||||
*
|
||||
* Memory management interface for libghostty-vt.
|
||||
*/
|
||||
|
||||
#ifndef GHOSTTY_VT_ALLOCATOR_H
|
||||
#define GHOSTTY_VT_ALLOCATOR_H
|
||||
|
||||
#include <stdbool.h>
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
/** @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 */
|
||||
+96
@@ -0,0 +1,96 @@
|
||||
/**
|
||||
* @file color.h
|
||||
*
|
||||
* Color types and utilities.
|
||||
*/
|
||||
|
||||
#ifndef GHOSTTY_VT_COLOR_H
|
||||
#define GHOSTTY_VT_COLOR_H
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
#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 */
|
||||
+80
@@ -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 <assert.h>
|
||||
* #include <stdio.h>
|
||||
* #include <ghostty/vt.h>
|
||||
*
|
||||
* 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 <ghostty/vt/key/event.h>
|
||||
#include <ghostty/vt/key/encoder.h>
|
||||
|
||||
/** @} */
|
||||
|
||||
#endif /* GHOSTTY_VT_KEY_H */
|
||||
+221
@@ -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 <stddef.h>
|
||||
#include <stdint.h>
|
||||
#include <ghostty/vt/result.h>
|
||||
#include <ghostty/vt/allocator.h>
|
||||
#include <ghostty/vt/key/event.h>
|
||||
|
||||
/**
|
||||
* 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 */
|
||||
+474
@@ -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 <stdbool.h>
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
#include <ghostty/vt/result.h>
|
||||
#include <ghostty/vt/allocator.h>
|
||||
|
||||
/**
|
||||
* 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 */
|
||||
+233
@@ -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 <stdbool.h>
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
#include <ghostty/vt/result.h>
|
||||
#include <ghostty/vt/allocator.h>
|
||||
|
||||
/**
|
||||
* 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 */
|
||||
+75
@@ -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 <stdio.h>
|
||||
* #include <string.h>
|
||||
* #include <ghostty/vt.h>
|
||||
*
|
||||
* 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 <stdbool.h>
|
||||
#include <stddef.h>
|
||||
|
||||
#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 */
|
||||
+22
@@ -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 */
|
||||
+394
@@ -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 <assert.h>
|
||||
* #include <stdio.h>
|
||||
* #include <ghostty/vt.h>
|
||||
*
|
||||
* 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 <ghostty/vt/allocator.h>
|
||||
#include <ghostty/vt/color.h>
|
||||
#include <ghostty/vt/result.h>
|
||||
#include <stdbool.h>
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
#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 */
|
||||
+159
@@ -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 <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
/** @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 */
|
||||
+7
@@ -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 *
|
||||
}
|
||||
Vendored
BIN
Binary file not shown.
@@ -0,0 +1 @@
|
||||
268a0a9d761fb19673f05d28042488e2002300f2
|
||||
@@ -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')
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android" />
|
||||
+46
@@ -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")
|
||||
}
|
||||
}
|
||||
}
|
||||
+210
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"platforms": ["apple", "android"],
|
||||
"apple": {
|
||||
"modules": ["T3TerminalModule"],
|
||||
"podspecPath": "T3TerminalNative.podspec"
|
||||
},
|
||||
"android": {
|
||||
"modules": ["expo.modules.t3terminal.T3TerminalModule"]
|
||||
}
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<T3TerminalView>.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
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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",
|
||||
|
||||
@@ -65,6 +65,16 @@ export default function ThreadLayout() {
|
||||
sheetGrabberVisible: true,
|
||||
}}
|
||||
/>
|
||||
<Stack.Screen
|
||||
name="terminal"
|
||||
options={{
|
||||
animation: "slide_from_right",
|
||||
contentStyle: { backgroundColor: "#050505" },
|
||||
headerBackButtonDisplayMode: "minimal",
|
||||
headerShown: true,
|
||||
headerShadowVisible: false,
|
||||
}}
|
||||
/>
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
import { ThreadTerminalRouteScreen } from "../../../../features/threads/ThreadTerminalRouteScreen";
|
||||
|
||||
export default function ThreadTerminalRoute() {
|
||||
return <ThreadTerminalRouteScreen />;
|
||||
}
|
||||
@@ -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<ProjectScript>;
|
||||
readonly terminalSessions: ReadonlyArray<TerminalMenuSession>;
|
||||
readonly onOpenTerminal: (terminalId?: string | null) => void;
|
||||
readonly onOpenNewTerminal: () => void;
|
||||
readonly onRunProjectScript: (script: ProjectScript) => Promise<void>;
|
||||
readonly onPull: () => Promise<void>;
|
||||
readonly onRunAction: (input: GitActionRequestInput) => Promise<GitRunStackedActionResult | null>;
|
||||
}) {
|
||||
@@ -167,6 +181,54 @@ export function ThreadGitControls(props: {
|
||||
|
||||
return (
|
||||
<Stack.Toolbar placement="right">
|
||||
<Stack.Toolbar.Menu icon="terminal" disabled={!props.canOpenTerminal} separateBackground>
|
||||
{props.projectScripts.length > 0 ? (
|
||||
<Stack.Toolbar.Menu icon="play" inline title="Project scripts">
|
||||
<Stack.Toolbar.Label>Project scripts</Stack.Toolbar.Label>
|
||||
{props.projectScripts.map((script) => (
|
||||
<Stack.Toolbar.MenuAction
|
||||
key={script.id}
|
||||
icon={projectScriptMenuIcon(script.icon)}
|
||||
onPress={() => void props.onRunProjectScript(script)}
|
||||
subtitle={script.command}
|
||||
>
|
||||
<Stack.Toolbar.Label>{projectScriptMenuLabel(script)}</Stack.Toolbar.Label>
|
||||
</Stack.Toolbar.MenuAction>
|
||||
))}
|
||||
</Stack.Toolbar.Menu>
|
||||
) : (
|
||||
<Stack.Toolbar.MenuAction
|
||||
icon="play"
|
||||
disabled
|
||||
onPress={() => {}}
|
||||
subtitle="This project has no saved scripts yet"
|
||||
>
|
||||
<Stack.Toolbar.Label>No project scripts</Stack.Toolbar.Label>
|
||||
</Stack.Toolbar.MenuAction>
|
||||
)}
|
||||
<Stack.Toolbar.Menu icon="terminal" inline title="Terminals">
|
||||
<Stack.Toolbar.Label>Terminals</Stack.Toolbar.Label>
|
||||
{props.terminalSessions.map((session) => (
|
||||
<Stack.Toolbar.MenuAction
|
||||
key={session.terminalId}
|
||||
icon="terminal"
|
||||
onPress={() => props.onOpenTerminal(session.terminalId)}
|
||||
subtitle={[getTerminalStatusLabel({ status: session.status }), basename(session.cwd)]
|
||||
.filter(Boolean)
|
||||
.join(" · ")}
|
||||
>
|
||||
<Stack.Toolbar.Label>{getTerminalLabel(session.terminalId)}</Stack.Toolbar.Label>
|
||||
</Stack.Toolbar.MenuAction>
|
||||
))}
|
||||
<Stack.Toolbar.MenuAction
|
||||
icon="plus"
|
||||
onPress={props.onOpenNewTerminal}
|
||||
subtitle="Start another shell for this thread"
|
||||
>
|
||||
<Stack.Toolbar.Label>Open new terminal</Stack.Toolbar.Label>
|
||||
</Stack.Toolbar.MenuAction>
|
||||
</Stack.Toolbar.Menu>
|
||||
</Stack.Toolbar.Menu>
|
||||
<Stack.Toolbar.Menu icon="point.topleft.down.curvedto.point.bottomright.up">
|
||||
<Stack.Toolbar.MenuAction
|
||||
icon="point.topleft.down.curvedto.point.bottomright.up"
|
||||
|
||||
@@ -3,6 +3,8 @@ import { useCallback, useMemo, useState } from "react";
|
||||
import * as Arr from "effect/Array";
|
||||
import * as Option from "effect/Option";
|
||||
import { pipe } from "effect/Function";
|
||||
import type { ProjectScript } from "@t3tools/contracts";
|
||||
import { projectScriptCwd, projectScriptRuntimeEnv } from "@t3tools/shared/projectScripts";
|
||||
import { Pressable, ScrollView, Text as RNText, View, useColorScheme } from "react-native";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import { useGitStatus, gitStatusManager } from "../../state/use-git-status";
|
||||
@@ -10,24 +12,33 @@ import { dismissGitActionResult, useGitActionProgress } from "../../state/use-gi
|
||||
|
||||
import { EmptyState } from "../../components/EmptyState";
|
||||
import { LoadingScreen } from "../../components/LoadingScreen";
|
||||
import { buildThreadRoutePath } from "../../lib/routes";
|
||||
import { buildThreadRoutePath, buildThreadTerminalRoutePath } from "../../lib/routes";
|
||||
import { scopedThreadKey } from "../../lib/scopedEntities";
|
||||
import { connectionTone } from "../connection/connectionTone";
|
||||
|
||||
import { useRemoteCatalog } from "../../state/use-remote-catalog";
|
||||
import {
|
||||
getEnvironmentClient,
|
||||
useRemoteConnectionStatus,
|
||||
useRemoteEnvironmentState,
|
||||
} from "../../state/use-remote-environment-registry";
|
||||
import { terminalSessionManager, useKnownTerminalSessions } from "../../state/use-terminal-session";
|
||||
import { useSelectedThreadDetail } from "../../state/use-thread-detail";
|
||||
import { useThreadSelection } from "../../state/use-thread-selection";
|
||||
import { GitActionProgressOverlay } from "./GitActionProgressOverlay";
|
||||
import {
|
||||
buildTerminalMenuSessions,
|
||||
nextTerminalId,
|
||||
resolveProjectScriptTerminalId,
|
||||
} from "./terminalMenu";
|
||||
import { resolvePreferredThreadWorktreePath } from "./terminalLaunchContext";
|
||||
import { ThreadDetailScreen } from "./ThreadDetailScreen";
|
||||
import { ThreadGitControls } from "./ThreadGitControls";
|
||||
import { ThreadNavigationDrawer } from "./ThreadNavigationDrawer";
|
||||
import { useSelectedThreadCommands } from "./use-selected-thread-commands";
|
||||
import { useSelectedThreadGitActions } from "./use-selected-thread-git-actions";
|
||||
import { useSelectedThreadGitState } from "./use-selected-thread-git-state";
|
||||
import { useSelectedThreadWorktree } from "./use-selected-thread-worktree";
|
||||
import { useThreadComposerState } from "./use-thread-composer-state";
|
||||
|
||||
function firstRouteParam(value: string | string[] | undefined): string | null {
|
||||
@@ -47,6 +58,7 @@ export function ThreadRouteScreen() {
|
||||
const { selectedThread, selectedThreadProject, selectedEnvironmentConnection } =
|
||||
useThreadSelection();
|
||||
const selectedThreadDetail = useSelectedThreadDetail();
|
||||
const { selectedThreadCwd } = useSelectedThreadWorktree();
|
||||
const composer = useThreadComposerState();
|
||||
const gitState = useSelectedThreadGitState();
|
||||
const gitActions = useSelectedThreadGitActions();
|
||||
@@ -80,20 +92,29 @@ export function ThreadRouteScreen() {
|
||||
/* ─── Git status for native header trigger ───────────────────────── */
|
||||
const gitStatus = useGitStatus({
|
||||
environmentId: selectedThread?.environmentId ?? "",
|
||||
cwd: selectedThread?.worktreePath ?? selectedThreadProject?.workspaceRoot ?? null,
|
||||
cwd: selectedThreadCwd,
|
||||
});
|
||||
const knownTerminalSessions = useKnownTerminalSessions({
|
||||
environmentId: selectedThread?.environmentId ?? null,
|
||||
threadId: selectedThread?.id ?? null,
|
||||
});
|
||||
const terminalMenuSessions = useMemo(
|
||||
() =>
|
||||
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 <LoadingScreen message="Opening thread…" />;
|
||||
}
|
||||
@@ -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}
|
||||
/>
|
||||
|
||||
@@ -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 (
|
||||
<View className="absolute inset-x-3 bottom-28 top-28 overflow-hidden rounded-[8px] border border-white/10 bg-neutral-950 shadow-2xl">
|
||||
<View className="flex-row items-center justify-between border-b border-white/10 px-3 py-2">
|
||||
<View className="min-w-0 flex-1">
|
||||
<Text className="font-t3-bold text-[13px] text-neutral-100" numberOfLines={1}>
|
||||
Terminal
|
||||
</Text>
|
||||
<Text className="text-[11px] text-neutral-500" numberOfLines={1}>
|
||||
{nativeTerminalAvailable ? "Native Ghostty surface" : "Text fallback active"}
|
||||
</Text>
|
||||
</View>
|
||||
<View className="flex-row items-center gap-2">
|
||||
{terminal.error ? (
|
||||
<Text className="max-w-44 text-right text-[11px] text-red-300" numberOfLines={1}>
|
||||
{terminal.error}
|
||||
</Text>
|
||||
) : null}
|
||||
<Pressable
|
||||
className="h-8 w-8 items-center justify-center rounded-[8px] bg-white/10"
|
||||
onPress={props.onClose}
|
||||
>
|
||||
<SymbolView name="xmark" size={13} tintColor="#e5e5e5" type="monochrome" />
|
||||
</Pressable>
|
||||
</View>
|
||||
</View>
|
||||
<TerminalSurface
|
||||
terminalKey={terminalKey}
|
||||
buffer={terminal.buffer}
|
||||
isRunning={isRunning}
|
||||
onInput={handleInput}
|
||||
onResize={handleResize}
|
||||
style={{ flex: 1 }}
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
});
|
||||
@@ -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",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -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<PendingModifier | null>(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<ReadonlyArray<TerminalToolbarAction>>(() => {
|
||||
const modifierActions: ReadonlyArray<TerminalToolbarAction> =
|
||||
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<ReadonlyArray<TerminalMenuSession>>(
|
||||
() =>
|
||||
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 <LoadingScreen message="Opening terminal…" />;
|
||||
}
|
||||
|
||||
return (
|
||||
<View className="flex-1 bg-screen">
|
||||
<EmptyState
|
||||
title="Thread unavailable"
|
||||
detail="This terminal route needs an active thread and workspace."
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
if (!selectedThreadProject?.workspaceRoot) {
|
||||
return (
|
||||
<View className="flex-1 bg-screen">
|
||||
<EmptyState
|
||||
title="Terminal unavailable"
|
||||
detail="This thread does not have a workspace root yet, so there is nowhere to open a shell."
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Stack.Screen
|
||||
options={{
|
||||
headerShown: true,
|
||||
headerBackButtonDisplayMode: "minimal",
|
||||
headerBackTitle: "",
|
||||
headerShadowVisible: false,
|
||||
headerStyle: { backgroundColor: "#0a0a0a" },
|
||||
headerTintColor: "#f5f5f5",
|
||||
headerTitleAlign: "center",
|
||||
title: "",
|
||||
headerTitle: () => (
|
||||
<View
|
||||
style={{
|
||||
alignItems: "center",
|
||||
gap: 1,
|
||||
maxWidth: 240,
|
||||
}}
|
||||
>
|
||||
<RNText
|
||||
numberOfLines={1}
|
||||
style={{
|
||||
color: "#f5f5f5",
|
||||
fontFamily: "DMSans_700Bold",
|
||||
fontSize: 13,
|
||||
lineHeight: 16,
|
||||
}}
|
||||
>
|
||||
{headerTitle.topLine}
|
||||
</RNText>
|
||||
<RNText
|
||||
ellipsizeMode="middle"
|
||||
numberOfLines={1}
|
||||
style={{
|
||||
color: "#8f8f94",
|
||||
fontFamily: "Menlo",
|
||||
fontSize: 11,
|
||||
lineHeight: 14,
|
||||
}}
|
||||
>
|
||||
{headerTitle.bottomLine}
|
||||
</RNText>
|
||||
</View>
|
||||
),
|
||||
}}
|
||||
/>
|
||||
|
||||
<Stack.Toolbar placement="right">
|
||||
<Stack.Toolbar.Menu
|
||||
icon="circle.fill"
|
||||
style={{
|
||||
color: terminalStatusTone.textColor,
|
||||
fontFamily: "DMSans_700Bold",
|
||||
fontSize: 12,
|
||||
fontWeight: "700",
|
||||
}}
|
||||
tintColor={terminalStatusTone.tintColor}
|
||||
title="Terminal options"
|
||||
>
|
||||
<Stack.Toolbar.Label>
|
||||
{getTerminalStatusLabel({
|
||||
status: terminal.status,
|
||||
hasRunningSubprocess: terminal.hasRunningSubprocess,
|
||||
})}
|
||||
</Stack.Toolbar.Label>
|
||||
<Stack.Toolbar.Menu icon="textformat.size" inline title="Text size">
|
||||
<Stack.Toolbar.Label>Text size</Stack.Toolbar.Label>
|
||||
<Stack.Toolbar.MenuAction
|
||||
disabled={fontSize <= MIN_TERMINAL_FONT_SIZE}
|
||||
discoverabilityLabel="Decrease terminal text size"
|
||||
onPress={handleDecreaseFontSize}
|
||||
>
|
||||
<Stack.Toolbar.Label>{`A- ${Math.max(MIN_TERMINAL_FONT_SIZE, fontSize - TERMINAL_FONT_SIZE_STEP).toFixed(1)} pt`}</Stack.Toolbar.Label>
|
||||
</Stack.Toolbar.MenuAction>
|
||||
<Stack.Toolbar.MenuAction
|
||||
disabled={fontSize >= MAX_TERMINAL_FONT_SIZE}
|
||||
discoverabilityLabel="Increase terminal text size"
|
||||
onPress={handleIncreaseFontSize}
|
||||
>
|
||||
<Stack.Toolbar.Label>{`A+ ${Math.min(MAX_TERMINAL_FONT_SIZE, fontSize + TERMINAL_FONT_SIZE_STEP).toFixed(1)} pt`}</Stack.Toolbar.Label>
|
||||
</Stack.Toolbar.MenuAction>
|
||||
</Stack.Toolbar.Menu>
|
||||
{terminalMenuSessions.map((session) => (
|
||||
<Stack.Toolbar.MenuAction
|
||||
key={session.terminalId}
|
||||
icon={session.terminalId === terminalId ? "checkmark" : "terminal"}
|
||||
onPress={() => handleSelectTerminal(session.terminalId)}
|
||||
subtitle={[getTerminalStatusLabel({ status: session.status }), basename(session.cwd)]
|
||||
.filter(Boolean)
|
||||
.join(" · ")}
|
||||
>
|
||||
<Stack.Toolbar.Label>{getTerminalLabel(session.terminalId)}</Stack.Toolbar.Label>
|
||||
</Stack.Toolbar.MenuAction>
|
||||
))}
|
||||
<Stack.Toolbar.MenuAction
|
||||
icon="plus"
|
||||
onPress={handleOpenNewTerminal}
|
||||
subtitle={`Start another shell in ${basename(selectedThreadProject.workspaceRoot) ?? "this workspace"}`}
|
||||
>
|
||||
<Stack.Toolbar.Label>Open new terminal</Stack.Toolbar.Label>
|
||||
</Stack.Toolbar.MenuAction>
|
||||
</Stack.Toolbar.Menu>
|
||||
</Stack.Toolbar>
|
||||
|
||||
<View style={{ flex: 1, backgroundColor: "#050505" }}>
|
||||
<Animated.View style={[{ flex: 1 }, terminalContainerAnimatedStyle]}>
|
||||
<TerminalSurface
|
||||
buffer={terminal.buffer}
|
||||
fontSize={fontSize}
|
||||
isRunning={isRunning}
|
||||
onInput={handleInput}
|
||||
onResize={handleResize}
|
||||
style={{ flex: 1 }}
|
||||
terminalKey={terminalKey}
|
||||
/>
|
||||
</Animated.View>
|
||||
|
||||
<KeyboardStickyView style={{ position: "absolute", bottom: 0, left: 0, right: 0 }}>
|
||||
<View
|
||||
style={{
|
||||
backgroundColor: "#0a0a0a",
|
||||
borderTopColor: "rgba(255,255,255,0.08)",
|
||||
borderTopWidth: 1,
|
||||
minHeight: TERMINAL_ACCESSORY_HEIGHT,
|
||||
paddingBottom: 4,
|
||||
paddingHorizontal: 8,
|
||||
paddingTop: 4,
|
||||
}}
|
||||
>
|
||||
<ScrollView
|
||||
horizontal
|
||||
contentContainerStyle={{ alignItems: "center", gap: 6, paddingRight: 2 }}
|
||||
showsHorizontalScrollIndicator={false}
|
||||
>
|
||||
{terminalToolbarActions.map((action) => {
|
||||
const active = action.kind === "modifier" && pendingModifier === action.modifier;
|
||||
|
||||
return (
|
||||
<Pressable
|
||||
key={action.key}
|
||||
onPress={() => 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,
|
||||
})}
|
||||
>
|
||||
<RNText
|
||||
style={{
|
||||
color: active ? "#bbf7d0" : "#f5f5f5",
|
||||
fontFamily: "DMSans_700Bold",
|
||||
fontSize: 12,
|
||||
fontWeight: "700",
|
||||
textTransform: action.kind === "modifier" ? "uppercase" : "none",
|
||||
}}
|
||||
>
|
||||
{action.label}
|
||||
</RNText>
|
||||
</Pressable>
|
||||
);
|
||||
})}
|
||||
</ScrollView>
|
||||
</View>
|
||||
</KeyboardStickyView>
|
||||
</View>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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<Record<string, boolean>>({});
|
||||
const [loadingGitDiffs, setLoadingGitDiffs] = useState(false);
|
||||
@@ -464,8 +463,9 @@ export function ReviewSheet() {
|
||||
const highlightQueueActiveRef = useRef(false);
|
||||
const highlightableFilesByIdRef = useRef<ReadonlyMap<string, ReviewRenderableFile>>(new Map());
|
||||
const selectedThemeRef = useRef<ReviewDiffTheme>(selectedTheme);
|
||||
const { selectedThreadCwd } = useSelectedThreadWorktree();
|
||||
|
||||
const cwd = selectedThread?.worktreePath ?? selectedThreadProject?.workspaceRoot ?? null;
|
||||
const cwd = selectedThreadCwd;
|
||||
const readyCheckpoints = useMemo(
|
||||
() => getReadyReviewCheckpoints(selectedThread?.checkpoints ?? []),
|
||||
[selectedThread?.checkpoints],
|
||||
|
||||
@@ -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",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -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,
|
||||
};
|
||||
}
|
||||
@@ -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");
|
||||
});
|
||||
});
|
||||
@@ -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>): 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<KnownTerminalSession>;
|
||||
readonly workspaceRoot: string | null;
|
||||
readonly currentSession?: TerminalMenuSession | null;
|
||||
}): ReadonlyArray<TerminalMenuSession> {
|
||||
const sessionsById = new Map<string, TerminalMenuSession>();
|
||||
|
||||
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<string>;
|
||||
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";
|
||||
}
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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));
|
||||
}
|
||||
@@ -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" };
|
||||
}
|
||||
@@ -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<ReadonlyArray<GitBranch>> => {
|
||||
@@ -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 {
|
||||
|
||||
@@ -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);
|
||||
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
}
|
||||
@@ -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();
|
||||
|
||||
@@ -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<string | null> {
|
||||
return await SecureStore.getItemAsync(key);
|
||||
@@ -14,23 +19,31 @@ async function writeStorageItem(key: string, value: string): Promise<void> {
|
||||
await SecureStore.setItemAsync(key, value);
|
||||
}
|
||||
|
||||
export async function loadSavedConnections(): Promise<ReadonlyArray<SavedRemoteConnection>> {
|
||||
const raw = (await readStorageItem(CONNECTIONS_KEY)) ?? "";
|
||||
async function readJsonStorageItem<T>(key: string): Promise<T | null> {
|
||||
const raw = (await readStorageItem(key)) ?? "";
|
||||
if (!raw.trim()) {
|
||||
return [];
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const parsed = JSON.parse(raw) as {
|
||||
readonly connections?: ReadonlyArray<SavedRemoteConnection>;
|
||||
};
|
||||
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<ReadonlyArray<SavedRemoteConnection>> {
|
||||
const parsed = await readJsonStorageItem<{
|
||||
readonly connections?: ReadonlyArray<SavedRemoteConnection>;
|
||||
}>(CONNECTIONS_KEY);
|
||||
if (!parsed) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return pipe(
|
||||
parsed.connections ?? [],
|
||||
Arr.filter((c) => !!c.environmentId && !!c.bearerToken?.trim()),
|
||||
);
|
||||
}
|
||||
|
||||
export async function saveConnection(connection: SavedRemoteConnection): Promise<void> {
|
||||
@@ -53,3 +66,28 @@ export async function clearSavedConnection(environmentId: string): Promise<void>
|
||||
);
|
||||
await writeStorageItem(CONNECTIONS_KEY, JSON.stringify({ connections: next }));
|
||||
}
|
||||
|
||||
export async function loadPreferences(): Promise<MobilePreferences> {
|
||||
const parsed = await readJsonStorageItem<MobilePreferences>(PREFERENCES_KEY);
|
||||
if (!parsed || typeof parsed !== "object") {
|
||||
return {};
|
||||
}
|
||||
|
||||
if (typeof parsed.terminalFontSize === "number") {
|
||||
return { terminalFontSize: parsed.terminalFontSize };
|
||||
}
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
export async function savePreferencesPatch(
|
||||
patch: Partial<MobilePreferences>,
|
||||
): Promise<MobilePreferences> {
|
||||
const current = await loadPreferences();
|
||||
const next: MobilePreferences = {
|
||||
...current,
|
||||
...patch,
|
||||
};
|
||||
await writeStorageItem(PREFERENCES_KEY, JSON.stringify(next));
|
||||
return next;
|
||||
}
|
||||
@@ -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 (
|
||||
<View
|
||||
style={[
|
||||
{
|
||||
flex: 1,
|
||||
backgroundColor: theme.background,
|
||||
borderRadius: 8,
|
||||
overflow: "hidden",
|
||||
},
|
||||
props.style,
|
||||
]}
|
||||
onLayout={handleLayout}
|
||||
>
|
||||
<View style={{ flex: 1, paddingHorizontal: 10, paddingVertical: 8 }}>
|
||||
<Text
|
||||
style={{
|
||||
color: theme.mutedForeground,
|
||||
fontSize: 11,
|
||||
paddingBottom: 8,
|
||||
}}
|
||||
>
|
||||
{statusLabel}
|
||||
</Text>
|
||||
<ScrollView
|
||||
style={{ flex: 1 }}
|
||||
contentContainerStyle={{ paddingBottom: 12 }}
|
||||
showsVerticalScrollIndicator={false}
|
||||
>
|
||||
<Text
|
||||
selectable
|
||||
style={{
|
||||
color: theme.foreground,
|
||||
fontFamily: "Menlo",
|
||||
fontSize,
|
||||
lineHeight: Math.round(fontSize * 1.35),
|
||||
}}
|
||||
>
|
||||
{props.buffer || "$ "}
|
||||
</Text>
|
||||
</ScrollView>
|
||||
</View>
|
||||
<View
|
||||
style={{
|
||||
borderTopWidth: 1,
|
||||
borderTopColor: theme.border,
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: 8,
|
||||
padding: 8,
|
||||
}}
|
||||
>
|
||||
<TextInput
|
||||
autoCapitalize="none"
|
||||
autoCorrect={false}
|
||||
blurOnSubmit={false}
|
||||
editable={props.isRunning}
|
||||
placeholder="type and press return"
|
||||
placeholderTextColor={theme.mutedForeground}
|
||||
returnKeyType="send"
|
||||
style={{
|
||||
color: theme.foreground,
|
||||
flex: 1,
|
||||
fontFamily: "Menlo",
|
||||
fontSize: 13,
|
||||
padding: 0,
|
||||
}}
|
||||
onSubmitEditing={(event) => {
|
||||
const text = event.nativeEvent.text;
|
||||
if (text.length > 0) {
|
||||
props.onInput(`${text}\n`);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<Pressable
|
||||
disabled={!props.isRunning}
|
||||
style={({ pressed }) => ({
|
||||
opacity: !props.isRunning ? 0.35 : pressed ? 0.65 : 1,
|
||||
paddingHorizontal: 10,
|
||||
paddingVertical: 6,
|
||||
borderRadius: 8,
|
||||
backgroundColor: theme.border,
|
||||
})}
|
||||
onPress={() => props.onInput("\u0003")}
|
||||
>
|
||||
<Text
|
||||
style={{
|
||||
color: theme.foreground,
|
||||
fontFamily: "DMSans_700Bold",
|
||||
fontSize: 11,
|
||||
}}
|
||||
>
|
||||
Ctrl-C
|
||||
</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
});
|
||||
|
||||
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<TerminalInputEvent>) => {
|
||||
onInput(event.nativeEvent.data);
|
||||
},
|
||||
[onInput],
|
||||
);
|
||||
const handleNativeResize = useCallback(
|
||||
(event: NativeSyntheticEvent<TerminalResizeEvent>) => {
|
||||
onResize({
|
||||
cols: event.nativeEvent.cols,
|
||||
rows: event.nativeEvent.rows,
|
||||
});
|
||||
},
|
||||
[onResize],
|
||||
);
|
||||
|
||||
if (NativeTerminalSurfaceView) {
|
||||
return (
|
||||
<NativeTerminalSurfaceView
|
||||
{...props}
|
||||
appearanceScheme={appearanceScheme}
|
||||
backgroundColor={theme.background}
|
||||
foregroundColor={theme.foreground}
|
||||
mutedForegroundColor={theme.mutedForeground}
|
||||
terminalKey={props.terminalKey}
|
||||
initialBuffer={props.buffer}
|
||||
fontSize={fontSize}
|
||||
themeConfig={buildGhosttyThemeConfig(theme)}
|
||||
onInput={handleNativeInput}
|
||||
onResize={handleNativeResize}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return <FallbackTerminalSurface {...props} fontSize={fontSize} theme={theme} />;
|
||||
});
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
@@ -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<TerminalInputEvent>) => void;
|
||||
readonly onResize?: (event: NativeSyntheticEvent<TerminalResizeEvent>) => void;
|
||||
}
|
||||
|
||||
let cachedNativeTerminalSurfaceView: ComponentType<NativeTerminalSurfaceProps> | undefined;
|
||||
|
||||
function getExpoViewConfig(moduleName: string) {
|
||||
return (globalThis as typeof globalThis & ExpoGlobalWithViewConfig).expo?.getViewConfig?.(
|
||||
moduleName,
|
||||
);
|
||||
}
|
||||
|
||||
export function resolveNativeTerminalSurfaceView(): ComponentType<NativeTerminalSurfaceProps> | null {
|
||||
if (cachedNativeTerminalSurfaceView) {
|
||||
return cachedNativeTerminalSurfaceView;
|
||||
}
|
||||
|
||||
if (getExpoViewConfig(NATIVE_TERMINAL_MODULE_NAME) == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
cachedNativeTerminalSurfaceView = requireNativeViewManager<NativeTerminalSurfaceProps>(
|
||||
NATIVE_TERMINAL_MODULE_NAME,
|
||||
);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
|
||||
return cachedNativeTerminalSurfaceView ?? null;
|
||||
}
|
||||
|
||||
export function hasNativeTerminalSurface() {
|
||||
return resolveNativeTerminalSurfaceView() !== null;
|
||||
}
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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`;
|
||||
}
|
||||
@@ -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<string, EnvironmentSession>();
|
||||
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();
|
||||
};
|
||||
}, []);
|
||||
|
||||
@@ -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]);
|
||||
}
|
||||
@@ -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<TerminalEvent, { type: "closed" }> => 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, {
|
||||
|
||||
@@ -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 = [];
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ export function terminalRunningSubprocessFromEvent(event: TerminalEvent): boolea
|
||||
case "started":
|
||||
case "restarted":
|
||||
case "exited":
|
||||
case "closed":
|
||||
return false;
|
||||
default:
|
||||
return null;
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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": ["[email protected]", "", { "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": ["[email protected]", "", { "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": ["[email protected]", "", { "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": ["[email protected]", "", { "peerDependencies": { "expo": "*", "react": "*", "react-native": "*" } }, "sha512-PrOmmuVsGW4bAkNQmGKtxMXj3invsfN+jfIKmQxHwE/dn7ODqwFWviUTa+PMUjP3XZmYCDLyu/i0GLeu7HF9Ew=="],
|
||||
@@ -3032,6 +3037,8 @@
|
||||
|
||||
"@shikijs/primitive/@shikijs/types": ["@shikijs/[email protected]", "", { "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": ["[email protected]", "", {}, "sha512-/tBrSQ36vCleJkAOsy9kbNTgaxvGbyOamC30PRePTQe/o1MFwEKHQk4Cn7BNGaPtjp+PuUrByJehM1hgxfq4sw=="],
|
||||
|
||||
"@tailwindcss/oxide-wasm32-wasi/@emnapi/core": ["@emnapi/[email protected]", "", { "dependencies": { "@emnapi/wasi-threads": "1.2.1", "tslib": "^2.4.0" }, "bundled": true }, "sha512-UC+ZhH3XtczQYfOlu3lNEkdW/p4dsJ1r/bP7H8+rhao3TTTMO1ATq/4DdIi23XuGoFY+Cz0JmCbdVl0hz9jZcA=="],
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -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",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -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<TerminalSessionState>({
|
||||
snapshot: null,
|
||||
buffer: "",
|
||||
status: "closed",
|
||||
error: null,
|
||||
hasRunningSubprocess: false,
|
||||
updatedAt: null,
|
||||
version: 0,
|
||||
});
|
||||
|
||||
const DEFAULT_MAX_BUFFER_BYTES = 512 * 1024;
|
||||
const knownTerminalSessionKeys = new Set<string>();
|
||||
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<Record<string, KnownTerminalSessionTarget>>(
|
||||
{},
|
||||
).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<string, TerminalSessionState>();
|
||||
|
||||
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<string> {
|
||||
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<string, KnownTerminalSessionTarget>;
|
||||
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<TerminalSessionTarget, "environmentId">,
|
||||
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<TerminalSessionTarget, "environmentId">,
|
||||
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<KnownTerminalSessionTarget>,
|
||||
): ReadonlyArray<KnownTerminalSession> {
|
||||
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,
|
||||
};
|
||||
}
|
||||
@@ -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, {
|
||||
|
||||
@@ -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,
|
||||
|
||||
Reference in new issue
Block a user