Compare commits

...
Author SHA1 Message Date
Cursor Agent 7c3f9b483b fix: use measured text width instead of grapheme count for diff content width and word-diff highlight positioning
Replace String.count (grapheme clusters) with NSString.size(withAttributes:)
for computing content widths in rebuildRowLayout and positioning word-diff
highlight ranges in drawWordDiffRanges. This ensures correct horizontal
scroll limits and highlight alignment for lines containing tabs, CJK
characters, or emoji.
2026-05-12 20:54:40 +00:00
Julius Marminge c3943721ab Normalize branch and model selection handling
- Deduplicate terminal IDs and favorite model slugs with trim-aware iteration
- Use effect-based filtering for local branch and built-in model lists
- Switch stable array handling to non-mutating `toSorted`
2026-05-12 22:42:15 +02:00
Julius Marmingeandcodex c0807d4928 Merge origin/main into mobile remote connect
Co-authored-by: codex <[email protected]>
2026-05-12 22:19:17 +02:00
Julius Marminge 168ec8a818 Harden remote connect and subscription handling
- Scope cleartext mobile config to development
- Fix stale loads, ordering, and terminal reuse
- Clean up terminal metadata subscriptions on failure
2026-05-08 22:54:50 -07:00
Julius Marmingeandcodex 547c0e5809 Fix browser VCS status test mocks
Co-authored-by: codex <[email protected]>
2026-05-08 20:55:01 -07:00
Julius Marmingeandcodex 2cffe6742e Merge main into mobile remote connect
Co-authored-by: codex <[email protected]>
2026-05-08 20:44:55 -07:00
Julius Marminge 4ec9647ce7 Rename git state to VCS and add diff preview caching
- Replace git-scoped client/runtime state with VCS-scoped APIs
- Add checkpoint diff preview state and reuse cached diffs
- Update mobile and web review flows to use the new shared state
2026-05-08 20:41:39 -07:00
Julius Marminge 01596f53ad Refactor client runtime state refresh handling
- Move archived threads state into shared client-runtime
- Add stale-aware refresh/invalidation for path search, discovery, and VCS refs
- Wire provider invalidations through the web runtime
2026-05-08 19:38:12 -07:00
Julius Marminge 9ef8d75c54 Replace git react-query layer with vcsRefManager and source control acti
- Migrate branch selector and git actions to useVcsRefs and new source control action hooks
- Remove gitReactQuery and projectReactQuery modules in favor of sourceControlActions and vcsRefState
- Add staleTimeMs to mobile vcs ref manager configuration
2026-05-08 19:16:22 -07:00
Julius Marminge c0a2f00f50 Rename branch state to VCS refs
- Switch mobile and client-runtime state to the generic VcsRef API
- Preserve background refreshes with client change handling and errors
2026-05-08 18:23:58 -07:00
Julius Marminge 54964f57ae Handle truncated git review diff previews safely
- Drop unterminated paths from truncated NUL-separated git stdout
- Preserve truncation state when building untracked review diffs
2026-05-08 18:14:25 -07:00
Julius Marminge 665c0c6685 Refactor mobile remote search and review state
- Move composer path search and source-control discovery into shared managed state
- Persist review async/loading state in atoms and add coverage
- Update mobile/web composers and review highlighter initialization
2026-05-08 18:08:41 -07:00
Julius Marmingeandcodex 89fbeb22c2 Merge origin/main into mobile remote connect
Co-authored-by: codex <[email protected]>
2026-05-08 16:53:18 -07:00
Julius Marmingeandcodex fd93d7f0d9 Fix mobile native static check typecheck
Co-authored-by: codex <[email protected]>
2026-05-08 13:22:16 -07:00
Julius Marmingeandcodex 7bea6820e3 Merge latest origin/main into t3code/mobile-remote-connect
Co-authored-by: codex <[email protected]>
2026-05-08 13:13:25 -07:00
Julius Marmingeandcodex 040c80626c Merge latest origin/main into t3code/mobile-remote-connect
Co-authored-by: codex <[email protected]>
2026-05-08 13:13:16 -07:00
Julius Marmingeandcodex 7791f47ac0 Merge latest origin/main into t3code/mobile-remote-connect
Co-authored-by: codex <[email protected]>
2026-05-07 21:52:48 -07:00
Julius Marmingeandcodex b357476e71 Merge origin/main into t3code/mobile-remote-connect
Co-authored-by: codex <[email protected]>
2026-05-07 21:48:25 -07:00
Julius Marminge 87f74346b2 Refactor review sheet into focused native review hooks
- Split file visibility, diff data, and comment selection logic out of `ReviewSheet`
- Add tests for review file visibility and native diff bridge behavior
- Wire review selection and mobile remote connect state through shared hooks
2026-05-07 00:11:43 -07:00
Julius Marminge 4b6bae59ba Restrict review diff preview to workspace roots
- Reject diff preview requests outside the configured workspace
- Add tests covering allowed and denied cwd paths
2026-05-06 23:46:07 -07:00
Yash Singh f29a9ff8f1 use custom react-native-nitro-markdown 2026-05-06 22:33:42 -05:00
Julius Marmingeandcodex ef1ed88c18 Merge origin/main into t3code/mobile-remote-connect
Co-authored-by: codex <[email protected]>
2026-05-06 16:20:05 -07:00
Julius Marminge d2c7dbfc4d rm 2026-05-04 23:50:06 -07:00
Julius Marminge f73b8bc122 Switch review preview timestamps to DateTimeUtc
- Emit Effect DateTime values from review and git diff previews
- Tighten the contract to require UTC datetime output
2026-05-04 23:46:44 -07:00
Julius Marminge 92368028f6 Add remote review diff plumbing
- Move review diff parsing and highlighting into shared mobile diff modules
- Add review service and wire server, web, and mobile around remote review selection
2026-05-04 23:35:32 -07:00
Julius Marmingeandcodex 0c1ccdadf1 Merge origin/main into mobile remote connect
Co-authored-by: codex <[email protected]>
2026-05-04 22:46:27 -07:00
Julius Marminge 7d20cb9e79 Add inline review comment selection to mobile diffs
- render comment rows and line selection state in the native diff view
- wire long-press/tap gestures to start and complete review comments
- tighten shared diff utilities and add coverage
2026-05-04 19:29:02 -07:00
Julius Marmingeandcodex 5225844b96 Fix saved environment runtime test mocks
Co-authored-by: codex <[email protected]>
2026-05-04 15:16:36 -07:00
Julius Marmingeandcodex f239d3a93d Merge origin/main into mobile remote connect
Co-authored-by: codex <[email protected]>
2026-05-04 14:22:18 -07:00
Yash SinghandJulius Marminge 057d3f24d8 feat: ios16 support (#2469)
Co-authored-by: Julius Marminge <[email protected]>
2026-05-03 21:32:30 -07:00
Julius Marmingeandcodex 93ec45eb3c Fix terminal attach session launch context
Co-authored-by: codex <[email protected]>
2026-05-03 20:56:44 -07:00
Julius Marmingeandcodex b4615a847a Use branded ids in mobile runtime flows
Co-authored-by: codex <[email protected]>
2026-05-03 20:29:53 -07:00
Julius Marmingeandcodex 96897ab346 Add mobile source control discovery runtime state
- Share source control discovery state across mobile environment lifecycles
- Resolve discovery clients through centralized mobile environment sessions
- Ignore stale in-flight discovery refreshes after invalidation or reset
- Mark pending web shell/thread-detail runtime migration points

Co-authored-by: codex <[email protected]>
2026-05-03 20:15:10 -07:00
Julius Marmingeandcodex 3aaa338f3b Merge origin/main into mobile remote connect
Co-authored-by: codex <[email protected]>
2026-05-03 18:53:16 -07:00
Julius Marmingeandcodex 0385713da4 Merge origin/main into mobile remote connect
Co-authored-by: codex <[email protected]>
2026-05-02 20:47:06 -07:00
Julius Marminge 9b9fe0d64b Add native mobile review diff rendering and static checks
- Add iOS review diff module, parser, and highlighter support
- Wire mobile native lint tooling into CI and local docs
- Include fixtures and tests for the new diff pipeline
2026-04-30 22:29:07 -07:00
Julius Marminge 95038c1add Add mobile review profiling and syntax highlight debug tools
- Add a debug diff scratch route with fixture-driven highlighting
- Wrap review screen in a shared highlighter provider
- Document profiling steps and add a Hermes profiling script
2026-04-28 20:31:08 -07:00
Julius Marminge 664768bff5 Merge origin/main into t3code/mobile-remote-connect
Co-authored-by: codex <[email protected]>

# Conflicts:
#	apps/web/src/components/ChatView.tsx
#	apps/web/src/composer-logic.ts
#	apps/web/src/environments/runtime/service.test.ts
#	apps/web/src/environments/runtime/service.ts
#	apps/web/src/rpc/wsTransport.test.ts
#	apps/web/src/rpc/wsTransport.ts
#	packages/client-runtime/src/wsRpcProtocol.ts
2026-04-27 13:21:38 -07:00
Julius Marminge 4e38d93a8f terminals 2026-04-27 12:39:22 -07:00
Julius Marminge cace5784c3 Ignore fast mode updates for Opencode models
- Skip remote fast-mode selection changes when the current provider is `opencode`
- Keep existing model selection state unchanged for unsupported providers
2026-04-17 19:53:17 -07:00
Julius Marminge 1985d2c2ef Extract WebSocket RPC client into shared runtime package
- Move ws RPC client and transport primitives into `@t3tools/client-runtime`
- Update web settings and environment code to use shared runtime types
- Keep reconnect and transport tests aligned with the new package boundary
2026-04-17 19:48:34 -07:00
Julius Marminge 3fe96f17b4 Refactor remote terminal session state handling
- Tighten environment/thread ID typing across mobile and shared state
- Track terminal metadata and subprocess status when attaching sessions
- Update launch and status flows for remote terminals
2026-04-17 19:48:34 -07:00
Julius Marminge dc994a1fe4 move some stuff around 2026-04-17 19:48:20 -07:00
Julius Marmingeandcodex 932ec190ed Fix post-rebase mobile typecheck issues
Co-authored-by: codex <[email protected]>
2026-04-17 19:48:20 -07:00
Julius Marminge 034a8bcab3 Stage remote terminal launches and replay hydrated buffers
- Carry pending launch context into terminal open
- Delay buffer replay until surface hydration is stable
- Co-authored-by: codex <[email protected]>
2026-04-17 19:48:19 -07:00
Julius Marminge 97263c5db4 Set mobile config scheme per app variant
- Use variant-specific Expo schemes for development, preview, and production
- Preserve the production `t3code` scheme while fixing remote-connect routing
2026-04-17 19:48:19 -07:00
Julius MarmingeandJulius Marminge da6ea88331 feat(mobile): Add terminal powered by libghostty (#2056)
Co-authored-by: Julius Marminge <[email protected]>
2026-04-17 19:48:19 -07:00
Julius Marminge d686613e34 Improve mobile review diff rendering
- Switch review screen to a virtualized list layout
- Queue diff highlighting and default to the JS engine
- Add word-diff helpers and tests
2026-04-17 19:48:19 -07:00
Julius Marminge 12fc9b7a12 shiki loading changes 2026-04-17 19:48:19 -07:00
Julius Marminge a22cb0548f get native highlighter setup properly 2026-04-17 19:48:18 -07:00
Julius Marmingeandcodex 9bebd283a5 Enhance mobile review comments with diff previews
- Add syntax-highlighted diff rendering and cached review state
- Support pasted/attached images in review comments
- Improve mobile review sheet handling for large or partial diffs

Co-authored-by: codex <[email protected]>
2026-04-17 19:48:18 -07:00
Julius Marmingeandcodex 493fbfab91 Add T3 Code mobile app and shared remote runtime
Rebuild PR #2013 on top of current origin/main without the duplicated commit lineage.

Co-authored-by: codex <[email protected]>
2026-04-17 19:48:18 -07:00
397 changed files with 52137 additions and 6539 deletions

No files matched your search

+27
View File
@@ -74,6 +74,33 @@ jobs:
test -f apps/desktop/dist-electron/preload.cjs
grep -nE "desktopBridge|getLocalEnvironmentBootstrap|PICK_FOLDER_CHANNEL|wsUrl" apps/desktop/dist-electron/preload.cjs
mobile_native_static_analysis:
name: Mobile Native Static Analysis
runs-on: blacksmith-12vcpu-macos-26
timeout-minutes: 10
steps:
- name: Checkout
uses: actions/checkout@v6
- name: Setup Bun
uses: oven-sh/setup-bun@v2
with:
bun-version-file: package.json
- name: Setup Node
uses: actions/setup-node@v6
with:
node-version-file: package.json
- name: Install dependencies
run: bun install --frozen-lockfile
- name: Install mobile native static analysis tools
run: brew bundle install --file apps/mobile/Brewfile
- name: Lint mobile native sources
run: node scripts/mobile-native-static-check.ts
release_smoke:
name: Release Smoke
runs-on: blacksmith-8vcpu-ubuntu-2404
+3
View File
@@ -9,8 +9,11 @@
"bun.lock",
"*.tsbuildinfo",
"**/routeTree.gen.ts",
"apps/mobile/android/**",
"apps/mobile/ios/**",
"apps/web/public/mockServiceWorker.js",
"apps/web/src/lib/vendor/qrcodegen.ts",
"apps/mobile/uniwind-types.d.ts",
"*.icon/**"
],
"sortPackageJson": {},
+5 -1
View File
@@ -6,7 +6,10 @@
"node_modules",
"bun.lock",
"*.tsbuildinfo",
"**/routeTree.gen.ts"
"**/routeTree.gen.ts",
"apps/mobile/android/**",
"apps/mobile/ios/**",
"apps/mobile/uniwind-types.d.ts"
],
"plugins": ["eslint", "oxc", "react", "unicorn", "typescript"],
"jsPlugins": ["./oxlint-plugin-t3code/index.ts"],
@@ -16,6 +19,7 @@
"perf": "warn"
},
"rules": {
"unicorn/no-array-sort": "off",
"react-in-jsx-scope": "off",
"eslint/no-shadow": "off",
"eslint/no-await-in-loop": "off",
+1
View File
@@ -3,6 +3,7 @@
## Task Completion Requirements
- All of `bun fmt`, `bun lint`, and `bun typecheck` must pass before considering tasks completed.
- If changing native mobile code, `bun lint:mobile` must also pass.
- NEVER run `bun test`. Always use `bun run test` (runs Vitest).
## Project Snapshot
+12
View File
@@ -0,0 +1,12 @@
root = false
[*.{kt,kts}]
indent_size = 2
ktlint_code_style = android_studio
ktlint_standard_blank-line-between-when-conditions = disabled
ktlint_standard_class-signature = disabled
ktlint_standard_function-signature = disabled
ktlint_standard_import-ordering = disabled
ktlint_standard_multiline-expression-wrapping = disabled
ktlint_standard_trailing-comma-on-call-site = disabled
ktlint_standard_when-entry-bracing = disabled
+41
View File
@@ -0,0 +1,41 @@
# Learn more https://docs.github.com/en/get-started/getting-started-with-git/ignoring-files
# dependencies
node_modules/
# Expo
.expo/
dist/
web-build/
expo-env.d.ts
# Native
.kotlin/
*.orig.*
*.jks
*.p8
*.p12
*.key
*.mobileprovision
# Metro
.metro-health-check*
# debug
npm-debug.*
yarn-debug.*
yarn-error.*
# macOS
.DS_Store
*.pem
# local env files
.env*.local
# typescript
*.tsbuildinfo
# generated native folders
/ios
/android
+58
View File
@@ -0,0 +1,58 @@
included:
- ios/T3Code
- modules/t3-terminal/ios
- modules/t3-review-diff/ios
excluded:
- ios/Pods
- ios/build
- modules/t3-terminal/Vendor
reporter: xcode
disabled_rules:
- file_length
- function_body_length
- identifier_name
- line_length
- lower_acl_than_parent
- modifier_order
- trailing_comma
- type_body_length
opt_in_rules:
- array_init
- closure_end_indentation
- closure_spacing
- collection_alignment
- contains_over_filter_count
- contains_over_filter_is_empty
- contains_over_first_not_nil
- contains_over_range_nil_comparison
- empty_collection_literal
- empty_count
- empty_string
- enum_case_associated_values_count
- fallthrough
- fatal_error_message
- first_where
- flatmap_over_map_reduce
- force_unwrapping
- implicitly_unwrapped_optional
- last_where
- legacy_multiple
- legacy_random
- operator_usage_whitespace
- overridden_super_call
- prefer_self_type_over_type_of_self
- private_action
- private_outlet
- prohibited_super_call
- reduce_into
- redundant_nil_coalescing
- sorted_first_last
- static_operator
- toggle_bool
- unneeded_parentheses_in_closure_argument
- vertical_parameter_alignment_on_call
- yoda_condition
+3
View File
@@ -0,0 +1,3 @@
brew "swiftlint"
brew "ktlint"
brew "detekt"
+81
View File
@@ -0,0 +1,81 @@
# T3 Code Mobile
> [!WARNING]
> T3 Code Mobile is currently in development and is not distributed yet. If you want to try it out, you can build it from source.
## Quickstart
> [!NOTE]
> Uses native modules so using Expo Go is not supported. You need to use the Expo Dev Client.
This app has three variants:
- `development`: Expo dev client, installable side-by-side as `T3 Code Dev`
- `preview`: persistent internal preview build, installable side-by-side as `T3 Code Preview`
- `production`: store/release build as `T3 Code`
Run commands from `apps/mobile`.
## Development
Start Metro for the dev client:
```bash
bun run dev:client
```
Build and run the local iOS dev client:
```bash
bun run ios:dev
```
Build and run the local iOS preview app:
```bash
bun run ios:preview
```
Force the review diff highlighter engine:
```bash
EXPO_PUBLIC_REVIEW_HIGHLIGHTER_ENGINE=javascript bun run ios:dev
```
`javascript` is the default and recommended setting for the review diff screen. Set `EXPO_PUBLIC_REVIEW_HIGHLIGHTER_ENGINE=native` only when you explicitly want to test the native Shiki engine.
Inspect the resolved Expo config for a variant:
```bash
bun run config:dev
bun run config:preview
```
Run static checks for mobile native code:
```bash
node ../../scripts/mobile-native-static-check.ts
```
The native lint task runs SwiftLint for Swift plus ktlint and detekt for Kotlin. Missing native tools are reported as warnings and skipped locally. CI installs the default toolset from `apps/mobile/Brewfile` before running the native checks.
## EAS Builds
Create a cloud dev-client build:
```bash
bun run eas:ios:dev
```
Create a persistent preview build:
```bash
bun run eas:ios:preview
```
Android equivalents:
```bash
bun run eas:android:dev
bun run eas:android:preview
```
+147
View File
@@ -0,0 +1,147 @@
import type { ExpoConfig } from "expo/config";
type AppVariant = "development" | "preview" | "production";
const APP_VARIANT = resolveAppVariant(process.env.APP_VARIANT);
const VARIANT_CONFIG: Record<
AppVariant,
{
readonly appName: string;
readonly scheme: string;
readonly iosIcon: string;
readonly iosBundleIdentifier: string;
readonly androidPackage: string;
}
> = {
development: {
appName: "T3 Code Dev",
scheme: "t3code-dev",
iosIcon: "./assets/icon-composer-dev.icon",
iosBundleIdentifier: "com.t3tools.t3code.dev",
androidPackage: "com.t3tools.t3code.dev",
},
preview: {
appName: "T3 Code Preview",
scheme: "t3code-preview",
iosIcon: "./assets/icon-composer-prod.icon",
iosBundleIdentifier: "com.t3tools.t3code.preview",
androidPackage: "com.t3tools.t3code.preview",
},
production: {
appName: "T3 Code",
scheme: "t3code",
iosIcon: "./assets/icon-composer-prod.icon",
iosBundleIdentifier: "com.t3tools.t3code",
androidPackage: "com.t3tools.t3code",
},
};
function resolveAppVariant(value: string | undefined): AppVariant {
switch (value) {
case "development":
case "preview":
case "production":
return value;
default:
return "production";
}
}
const variant = VARIANT_CONFIG[APP_VARIANT];
const allowsCleartextTraffic = APP_VARIANT === "development";
const config: ExpoConfig = {
name: variant.appName,
slug: "t3-code",
scheme: variant.scheme,
version: "0.1.0",
runtimeVersion: {
policy: "appVersion",
},
orientation: "portrait",
icon: "./assets/icon.png",
userInterfaceStyle: "automatic",
updates: {
enabled: true,
url: "https://u.expo.dev/d763fcb8-d37c-41ea-a773-b54a0ab4a454",
checkAutomatically: "ON_LOAD",
fallbackToCacheTimeout: 0,
},
splash: {
image: "./assets/splash-icon.png",
resizeMode: "contain",
backgroundColor: "#ffffff",
},
ios: {
icon: variant.iosIcon,
supportsTablet: true,
bundleIdentifier: variant.iosBundleIdentifier,
infoPlist: {
...(allowsCleartextTraffic
? {
NSAppTransportSecurity: {
NSAllowsArbitraryLoads: true,
},
}
: {}),
ITSAppUsesNonExemptEncryption: false,
},
},
android: {
icon: "./assets/icon.png",
package: variant.androidPackage,
adaptiveIcon: {
backgroundColor: "#E6F4FE",
foregroundImage: "./assets/android-icon-foreground.png",
backgroundImage: "./assets/android-icon-background.png",
monochromeImage: "./assets/android-icon-monochrome.png",
},
predictiveBackGestureEnabled: false,
},
web: {
favicon: "./assets/favicon.png",
},
plugins: [
[
"expo-camera",
{
cameraPermission: "Allow T3 Code to access your camera so you can scan pairing QR codes.",
barcodeScannerEnabled: true,
},
],
[
"expo-splash-screen",
{
image: "./assets/splash-icon.png",
resizeMode: "contain",
backgroundColor: "#ffffff",
imageWidth: 220,
dark: {
image: "./assets/splash-icon.png",
backgroundColor: "#0a0a0a",
},
},
],
[
"expo-build-properties",
{
ios: {
deploymentTarget: "16.1",
},
},
],
"expo-secure-store",
"expo-router",
...(allowsCleartextTraffic ? ["./plugins/withAndroidCleartextTraffic.cjs"] : []),
],
extra: {
appVariant: APP_VARIANT,
eas: {
projectId: "d763fcb8-d37c-41ea-a773-b54a0ab4a454",
},
},
owner: "pingdotgg",
};
export default config;
Binary file not shown.

After

Width:  |  Height:  |  Size: 323 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 323 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 323 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 74 KiB

@@ -0,0 +1,3 @@
<svg width="77" height="47" viewBox="0 0 77 47" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M14.56 45.5V8.58H1.69082e-06V-3.09944e-06H39.65V8.58H25.09V45.5H14.56ZM57.8454 46.28C54.6821 46.28 51.5404 45.8683 48.4204 45.045C45.3004 44.1783 42.6571 42.965 40.4904 41.405L44.5854 33.345C46.3188 34.6017 48.3338 35.5983 50.6304 36.335C52.9271 37.0717 55.2454 37.44 57.5854 37.44C60.2288 37.44 62.3088 36.92 63.8254 35.88C65.3421 34.84 66.1004 33.41 66.1004 31.59C66.1004 29.8567 65.4288 28.4917 64.0854 27.495C62.7421 26.4983 60.5754 26 57.5854 26H52.7754V19.045L65.4504 4.68L66.6204 8.45H42.7654V-3.09944e-06H74.6154V6.825L62.0054 21.19L56.6754 18.135H59.7304C65.3204 18.135 69.5454 19.3917 72.4054 21.905C75.2654 24.4183 76.6954 27.6467 76.6954 31.59C76.6954 34.1467 76.0238 36.5517 74.6804 38.805C73.3371 41.015 71.2788 42.8133 68.5054 44.2C65.7321 45.5867 62.1788 46.28 57.8454 46.28Z" fill="white"/>
</svg>

After

Width:  |  Height:  |  Size: 920 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 MiB

@@ -0,0 +1,45 @@
{
"fill": {
"solid": "display-p3:0.00000,0.00000,0.00000,1.00000"
},
"groups": [
{
"layers": [
{
"hidden": false,
"image-name": "gpt-image-1.5-jd70szmrd03p36z4zv48ycsbax81egvr.png",
"name": "gpt-image-1.5-jd70szmrd03p36z4zv48ycsbax81egvr",
"position": {
"scale": 1.1,
"translation-in-points": [0, 0]
}
},
{
"image-name": "T3.svg",
"name": "T3",
"position": {
"scale": 10,
"translation-in-points": [0, 0]
}
},
{
"hidden": true,
"image-name": "Texturelabs_Paper_381XL.jpg",
"name": "Texturelabs_Paper_381XL"
}
],
"shadow": {
"kind": "neutral",
"opacity": 0.5
},
"translucency": {
"enabled": true,
"value": 0.5
}
}
],
"supported-platforms": {
"circles": ["watchOS"],
"squares": "shared"
}
}
@@ -0,0 +1,3 @@
<svg width="77" height="47" viewBox="0 0 77 47" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M14.56 45.5V8.58H1.69082e-06V-3.09944e-06H39.65V8.58H25.09V45.5H14.56ZM57.8454 46.28C54.6821 46.28 51.5404 45.8683 48.4204 45.045C45.3004 44.1783 42.6571 42.965 40.4904 41.405L44.5854 33.345C46.3188 34.6017 48.3338 35.5983 50.6304 36.335C52.9271 37.0717 55.2454 37.44 57.5854 37.44C60.2288 37.44 62.3088 36.92 63.8254 35.88C65.3421 34.84 66.1004 33.41 66.1004 31.59C66.1004 29.8567 65.4288 28.4917 64.0854 27.495C62.7421 26.4983 60.5754 26 57.5854 26H52.7754V19.045L65.4504 4.68L66.6204 8.45H42.7654V-3.09944e-06H74.6154V6.825L62.0054 21.19L56.6754 18.135H59.7304C65.3204 18.135 69.5454 19.3917 72.4054 21.905C75.2654 24.4183 76.6954 27.6467 76.6954 31.59C76.6954 34.1467 76.0238 36.5517 74.6804 38.805C73.3371 41.015 71.2788 42.8133 68.5054 44.2C65.7321 45.5867 62.1788 46.28 57.8454 46.28Z" fill="white"/>
</svg>

After

Width:  |  Height:  |  Size: 920 B

@@ -0,0 +1,31 @@
{
"fill": {
"solid": "display-p3:0.00000,0.00000,0.00000,1.00000"
},
"groups": [
{
"layers": [
{
"image-name": "T3.svg",
"name": "T3",
"position": {
"scale": 10,
"translation-in-points": [0, 0]
}
}
],
"shadow": {
"kind": "neutral",
"opacity": 0.5
},
"translucency": {
"enabled": true,
"value": 0.5
}
}
],
"supported-platforms": {
"circles": ["watchOS"],
"squares": "shared"
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.0 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.0 MiB

+6
View File
@@ -0,0 +1,6 @@
module.exports = function (api) {
api.cache(true);
return {
presets: [["babel-preset-expo", { unstable_transformImportMeta: true }]],
};
};
+19
View File
@@ -0,0 +1,19 @@
config:
validation: true
build:
maxIssues: 0
complexity:
LongMethod:
active: true
threshold: 80
TooManyFunctions:
active: false
style:
MagicNumber:
active: false
MaxLineLength:
active: true
maxLineLength: 120
+37
View File
@@ -0,0 +1,37 @@
{
"cli": {
"version": ">= 18.4.0",
"appVersionSource": "remote"
},
"build": {
"development": {
"env": {
"APP_VARIANT": "development"
},
"channel": "development",
"developmentClient": true,
"distribution": "internal"
},
"preview": {
"env": {
"APP_VARIANT": "preview"
},
"channel": "preview",
"distribution": "internal"
},
"production": {
"env": {
"APP_VARIANT": "production"
},
"channel": "production",
"autoIncrement": true
}
},
"submit": {
"production": {
"ios": {
"ascAppId": "6761315631"
}
}
}
}
+202
View File
@@ -0,0 +1,202 @@
@import "tailwindcss";
@import "uniwind";
/* ─── Theme tokens ──────────────────────────────────────────────────── */
@layer theme {
:root {
@variant light {
/* Page backgrounds */
--color-screen: #f2f2f7;
--color-sheet: rgba(242, 242, 247, 0.98);
/* Card / surface */
--color-card: #ffffff;
--color-card-alt: #f5f5f5;
--color-card-translucent: rgba(255, 255, 255, 0.94);
/* Text */
--color-foreground: #262626;
--color-foreground-secondary: #525252;
--color-foreground-muted: #737373;
--color-foreground-tertiary: #a3a3a3;
/* Borders & separators */
--color-border: rgba(0, 0, 0, 0.08);
--color-border-subtle: rgba(0, 0, 0, 0.06);
--color-separator: rgba(0, 0, 0, 0.04);
/* Subtle backgrounds (badges, pills, overlays) */
--color-subtle: rgba(0, 0, 0, 0.04);
--color-subtle-strong: rgba(0, 0, 0, 0.08);
/* Primary action */
--color-primary: #262626;
--color-primary-foreground: #ffffff;
--color-primary-shadow: rgba(0, 0, 0, 0.18);
/* Secondary action */
--color-secondary: #ffffff;
--color-secondary-foreground: #262626;
--color-secondary-border: rgba(0, 0, 0, 0.08);
/* Danger */
--color-danger: #fef2f2;
--color-danger-border: rgba(239, 68, 68, 0.12);
--color-danger-foreground: #dc2626;
/* Inputs */
--color-input: #ffffff;
--color-input-border: rgba(0, 0, 0, 0.1);
--color-placeholder: #a3a3a3;
/* Icons */
--color-icon: #262626;
--color-icon-muted: #525252;
--color-icon-subtle: #a3a3a3;
/* Header / glass chrome */
--color-header: rgba(255, 255, 255, 0.97);
--color-header-border: rgba(0, 0, 0, 0.06);
/* StatusBar */
--color-status-bar: #f2f2f7;
/* Markdown */
--color-md-body: #111111;
--color-md-strong: #000000;
--color-md-link: #2563eb;
--color-md-blockquote-border: rgba(0, 0, 0, 0.08);
--color-md-blockquote-bg: rgba(0, 0, 0, 0.02);
--color-md-code-bg: rgba(0, 0, 0, 0.04);
--color-md-code-text: #262626;
--color-md-user-code-bg: rgba(255, 255, 255, 0.22);
--color-md-user-code-text: #ffffff;
--color-md-user-fence-bg: rgba(0, 0, 0, 0.16);
--color-md-user-fence-text: #ffffff;
--color-md-hr: rgba(0, 0, 0, 0.08);
/* iMessage-style user bubble */
--color-user-bubble: #007aff;
--color-user-bubble-foreground: #ffffff;
--color-user-bubble-foreground-muted: rgba(255, 255, 255, 0.78);
/* Drawer / modal backdrop */
--color-backdrop: rgba(0, 0, 0, 0.22);
--color-drawer: rgba(255, 255, 255, 0.99);
--color-drawer-shadow: rgba(0, 0, 0, 0.12);
/* Misc */
--color-dot-separator: rgba(0, 0, 0, 0.2);
--color-wordmark: #262626;
--color-chevron: rgba(0, 0, 0, 0.2);
}
@variant dark {
/* Page backgrounds */
--color-screen: #0a0a0a;
--color-sheet: rgba(14, 14, 14, 0.98);
/* Card / surface */
--color-card: #171717;
--color-card-alt: #1c1c1c;
--color-card-translucent: rgba(17, 17, 17, 0.94);
/* Text */
--color-foreground: #f5f5f5;
--color-foreground-secondary: #a3a3a3;
--color-foreground-muted: #737373;
--color-foreground-tertiary: #525252;
/* Borders & separators */
--color-border: rgba(255, 255, 255, 0.06);
--color-border-subtle: rgba(255, 255, 255, 0.04);
--color-separator: rgba(255, 255, 255, 0.03);
/* Subtle backgrounds (badges, pills, overlays) */
--color-subtle: rgba(255, 255, 255, 0.04);
--color-subtle-strong: rgba(255, 255, 255, 0.08);
/* Primary action */
--color-primary: #f5f5f5;
--color-primary-foreground: #0a0a0a;
--color-primary-shadow: rgba(0, 0, 0, 0.22);
/* Secondary action */
--color-secondary: rgba(255, 255, 255, 0.04);
--color-secondary-foreground: #f5f5f5;
--color-secondary-border: rgba(255, 255, 255, 0.06);
/* Danger */
--color-danger: rgba(239, 68, 68, 0.14);
--color-danger-border: rgba(248, 113, 113, 0.18);
--color-danger-foreground: #fca5a5;
/* Inputs */
--color-input: #141414;
--color-input-border: rgba(255, 255, 255, 0.08);
--color-placeholder: #737373;
/* Icons */
--color-icon: #f5f5f5;
--color-icon-muted: #a3a3a3;
--color-icon-subtle: #737373;
/* Header / glass chrome */
--color-header: rgba(10, 10, 10, 0.97);
--color-header-border: rgba(255, 255, 255, 0.06);
/* StatusBar */
--color-status-bar: #0a0a0a;
/* Markdown */
--color-md-body: #e5e5e5;
--color-md-strong: #f5f5f5;
--color-md-link: #60a5fa;
--color-md-blockquote-border: rgba(255, 255, 255, 0.1);
--color-md-blockquote-bg: rgba(255, 255, 255, 0.03);
--color-md-code-bg: rgba(255, 255, 255, 0.06);
--color-md-code-text: #e5e5e5;
--color-md-user-code-bg: rgba(255, 255, 255, 0.18);
--color-md-user-code-text: #ffffff;
--color-md-user-fence-bg: rgba(0, 0, 0, 0.28);
--color-md-user-fence-text: #ffffff;
--color-md-hr: rgba(255, 255, 255, 0.08);
/* iMessage-style user bubble */
--color-user-bubble: #0a84ff;
--color-user-bubble-foreground: #ffffff;
--color-user-bubble-foreground-muted: rgba(255, 255, 255, 0.78);
/* Drawer / modal backdrop */
--color-backdrop: rgba(0, 0, 0, 0.48);
--color-drawer: rgba(14, 14, 14, 0.99);
--color-drawer-shadow: rgba(0, 0, 0, 0.32);
/* Misc */
--color-dot-separator: rgba(255, 255, 255, 0.2);
--color-wordmark: #f5f5f5;
--color-chevron: rgba(255, 255, 255, 0.2);
}
}
}
/* ─── Font family ───────────────────────────────────────────────────── */
@theme {
--font-sans: "DMSans_400Regular";
--font-medium: "DMSans_500Medium";
--font-bold: "DMSans_700Bold";
}
/* ─── Custom utilities ──────────────────────────────────────────────── */
@utility font-t3-medium {
font-family: "DMSans_500Medium";
}
@utility font-t3-bold {
font-family: "DMSans_700Bold";
}
@utility font-t3-extrabold {
font-family: "DMSans_700Bold";
font-weight: 800;
}
+2
View File
@@ -0,0 +1,2 @@
import "react-native-gesture-handler";
import "expo-router/entry";
+45
View File
@@ -0,0 +1,45 @@
const fs = require("node:fs");
const path = require("node:path");
const { getDefaultConfig } = require("expo/metro-config");
const { withUniwindConfig } = require("uniwind/metro");
/** @type {import("expo/metro-config").MetroConfig} */
const config = getDefaultConfig(__dirname);
const workspaceRoot = path.resolve(__dirname, "../..");
const mobileShikiRoot = path.dirname(require.resolve("shiki/package.json", { paths: [__dirname] }));
const resolveShikiDependencyRoot = (packageName) => {
const entryPath = require.resolve(packageName, { paths: [mobileShikiRoot] });
let currentDir = path.dirname(entryPath);
while (!fs.existsSync(path.join(currentDir, "package.json"))) {
const parentDir = path.dirname(currentDir);
if (parentDir === currentDir) {
throw new Error(`Could not resolve package root for ${packageName}`);
}
currentDir = parentDir;
}
return currentDir;
};
config.watchFolders = [...new Set([...(config.watchFolders ?? []), workspaceRoot])];
config.resolver = {
...config.resolver,
extraNodeModules: {
// oxlint-disable-next-line unicorn/no-useless-fallback-in-spread
...(config.resolver?.extraNodeModules ?? {}),
shiki: mobileShikiRoot,
"@shikijs/core": resolveShikiDependencyRoot("@shikijs/core"),
"@shikijs/engine-javascript": resolveShikiDependencyRoot("@shikijs/engine-javascript"),
"@shikijs/engine-oniguruma": resolveShikiDependencyRoot("@shikijs/engine-oniguruma"),
"@shikijs/langs": resolveShikiDependencyRoot("@shikijs/langs"),
"@shikijs/themes": resolveShikiDependencyRoot("@shikijs/themes"),
"@shikijs/types": resolveShikiDependencyRoot("@shikijs/types"),
"@shikijs/vscode-textmate": resolveShikiDependencyRoot("@shikijs/vscode-textmate"),
},
};
module.exports = withUniwindConfig(config, {
cssEntryFile: "./global.css",
polyfills: { rem: 14 },
});
@@ -0,0 +1,19 @@
require 'json'
package = JSON.parse(File.read(File.join(__dir__, 'package.json')))
Pod::Spec.new do |s|
s.name = 'T3ReviewDiffNative'
s.version = package['version']
s.summary = 'Native review diff debug surface for T3 Code mobile.'
s.description = 'Native iOS review diff renderer used to prototype fast mobile review scrolling.'
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.frameworks = 'CoreGraphics', 'UIKit'
s.swift_version = '5.9'
s.dependency 'ExpoModulesCore'
end
@@ -0,0 +1,7 @@
{
"platforms": ["apple"],
"apple": {
"modules": ["T3ReviewDiffModule"],
"podspecPath": "T3ReviewDiffNative.podspec"
}
}
@@ -0,0 +1,63 @@
import ExpoModulesCore
public class T3ReviewDiffModule: Module {
public func definition() -> ModuleDefinition {
Name("T3ReviewDiffSurface")
View(T3ReviewDiffView.self) {
Prop("rowsJson") { (view: T3ReviewDiffView, rowsJson: String) in
view.setRowsJson(rowsJson)
}
Prop("tokensJson") { (view: T3ReviewDiffView, tokensJson: String) in
view.setTokensJson(tokensJson)
}
Prop("tokensPatchJson") { (view: T3ReviewDiffView, tokensPatchJson: String) in
view.setTokensPatchJson(tokensPatchJson)
}
Prop("tokensResetKey") { (view: T3ReviewDiffView, tokensResetKey: String) in
view.setTokensResetKey(tokensResetKey)
}
Prop("collapsedFileIdsJson") { (view: T3ReviewDiffView, collapsedFileIdsJson: String) in
view.setCollapsedFileIdsJson(collapsedFileIdsJson)
}
Prop("viewedFileIdsJson") { (view: T3ReviewDiffView, viewedFileIdsJson: String) in
view.setViewedFileIdsJson(viewedFileIdsJson)
}
Prop("selectedRowIdsJson") { (view: T3ReviewDiffView, selectedRowIdsJson: String) in
view.setSelectedRowIdsJson(selectedRowIdsJson)
}
Prop("collapsedCommentIdsJson") { (view: T3ReviewDiffView, collapsedCommentIdsJson: String) in
view.setCollapsedCommentIdsJson(collapsedCommentIdsJson)
}
Prop("appearanceScheme") { (view: T3ReviewDiffView, appearanceScheme: String) in
view.setAppearanceScheme(appearanceScheme)
}
Prop("themeJson") { (view: T3ReviewDiffView, themeJson: String) in
view.setThemeJson(themeJson)
}
Prop("styleJson") { (view: T3ReviewDiffView, styleJson: String) in
view.setStyleJson(styleJson)
}
Prop("rowHeight") { (view: T3ReviewDiffView, rowHeight: Double) in
view.setRowHeight(CGFloat(rowHeight))
}
Prop("contentWidth") { (view: T3ReviewDiffView, contentWidth: Double) in
view.setContentWidth(CGFloat(contentWidth))
}
Events("onDebug", "onToggleFile", "onToggleViewedFile", "onPressLine", "onToggleComment")
}
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,12 @@
{
"name": "@t3tools/mobile-review-diff-native",
"version": "0.0.0",
"private": true,
"expo-module": {
"ios": {
"modules": [
"T3ReviewDiffModule"
]
}
}
}
+38
View File
@@ -0,0 +1,38 @@
# 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 Ghostty custom-I/O
fork, with T3's iOS 16 compatibility patch applied. `T3TerminalView` owns a `libghostty` surface and
uses that callback 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`.
## Rebuilding GhosttyKit
The checked-in `GhosttyKit.xcframework` is built from the Ghostty custom-I/O fork (https://github.com/Yash-Singh1/ghostty/tree/custom-io).
Set the directory to the cloned repository checked out on the `custom-io` branch to `GHOSTTY_SOURCE_DIR`.
```bash
apps/mobile/modules/t3-terminal/scripts/build-libghostty-ios16.sh
```
The script builds Ghostty with Zig 0.15.2, strips the iOS archives, and replaces only the
`ios-arm64` and `ios-arm64-simulator` slices. Xcode's Metal toolchain must be installed; if `metal`
fails, run `xcodebuild -downloadComponent MetalToolchain`.
@@ -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,16 @@
# Third-Party Notices
## Ghostty / libghostty
The iOS terminal renderer vendors `GhosttyKit.xcframework`, a libghostty build produced from T3's
iOS 16 support fork. That fork was created from VVTerm's custom-I/O Ghostty fork.
- Upstream project: https://github.com/ghostty-org/ghostty
- Custom-I/O base fork: https://github.com/wiedymi/ghostty/tree/custom-io
- Vendored source fork: https://github.com/Yash-Singh1/ghostty/tree/custom-io
- Vendored revision: `d36c3b8dffd0d756dd5e5f4933962f774a0e6753`
- 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`.
@@ -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>
@@ -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 */
@@ -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 */
@@ -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 */
@@ -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 */
@@ -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 */
@@ -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 */
@@ -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 */
@@ -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 */
@@ -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 */
@@ -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 */
@@ -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 */
@@ -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 *
}
@@ -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 */
@@ -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 */
@@ -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 */
@@ -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 */
@@ -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 */
@@ -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 */
@@ -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 */
@@ -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 */
@@ -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 */
@@ -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 */
@@ -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 */
@@ -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 *
}
@@ -0,0 +1 @@
d36c3b8dffd0d756dd5e5f4933962f774a0e6753
@@ -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" />
@@ -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")
}
}
}
@@ -0,0 +1,211 @@
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 = 10f
set(value) {
field = value
textView.textSize = value
inputView.textSize = max(value, 13f)
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,560 @@
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 = 10 {
didSet {
guard oldValue != fontSize else { return }
inputField.font = UIFont.monospacedSystemFont(ofSize: max(fontSize, 13), weight: .regular)
refreshSurface()
}
}
var appearanceScheme: String = TerminalAppearanceScheme.dark.rawValue {
didSet {
guard oldValue != appearanceScheme else { return }
appearance = TerminalAppearanceScheme(value: appearanceScheme)
refreshSurface()
}
}
var themeConfig: String = "" {
didSet {
guard oldValue != themeConfig else { return }
refreshSurface()
}
}
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 false },
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 refreshSurface() {
resetSurface()
createSurfaceIfPossible()
}
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 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"
]
}
}
}
@@ -0,0 +1,106 @@
#!/usr/bin/env bash
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
MODULE_DIR="$(cd "${SCRIPT_DIR}/.." && pwd)"
VENDOR_DIR="${MODULE_DIR}/Vendor/libghostty"
GHOSTTY_SOURCE_DIR="${GHOSTTY_SOURCE_DIR:-${HOME}/ghostty}"
GHOSTTY_ZIG_VERSION="${GHOSTTY_ZIG_VERSION:-0.15.2}"
GHOSTTY_ZIG="${GHOSTTY_ZIG:-}"
log() {
printf '[libghostty-ios16] %s\n' "$*"
}
die() {
printf '[libghostty-ios16] error: %s\n' "$*" >&2
exit 1
}
require_cmd() {
command -v "$1" >/dev/null 2>&1 || die "missing required command: $1"
}
ensure_zig() {
if [[ -n "${GHOSTTY_ZIG}" ]]; then
[[ -x "${GHOSTTY_ZIG}" ]] || die "GHOSTTY_ZIG is not executable: ${GHOSTTY_ZIG}"
return
fi
if command -v zig >/dev/null 2>&1 && [[ "$(zig version)" == "${GHOSTTY_ZIG_VERSION}" ]]; then
GHOSTTY_ZIG="$(command -v zig)"
return
fi
local cache_dir="${HOME}/.cache/t3code/zig-${GHOSTTY_ZIG_VERSION}"
local archive_arch
archive_arch="$(uname -m)"
case "${archive_arch}" in
arm64) archive_arch="aarch64" ;;
x86_64) archive_arch="x86_64" ;;
*) die "unsupported macOS architecture for Zig download: ${archive_arch}" ;;
esac
GHOSTTY_ZIG="${cache_dir}/zig"
if [[ -x "${GHOSTTY_ZIG}" ]]; then
return
fi
require_cmd curl
require_cmd tar
mkdir -p "${cache_dir}"
log "downloading Zig ${GHOSTTY_ZIG_VERSION}"
curl -fsSL "https://ziglang.org/download/${GHOSTTY_ZIG_VERSION}/zig-${archive_arch}-macos-${GHOSTTY_ZIG_VERSION}.tar.xz" \
| tar -xJ --strip-components=1 -C "${cache_dir}"
}
require_cmd git
require_cmd xcodebuild
require_cmd xcrun
require_cmd rsync
ensure_zig
ghostty_ref="$(git -C "${GHOSTTY_SOURCE_DIR}" rev-parse HEAD)"
log "using Ghostty source: ${GHOSTTY_SOURCE_DIR} @ ${ghostty_ref}"
log "using Zig: ${GHOSTTY_ZIG} ($("${GHOSTTY_ZIG}" version))"
log "building GhosttyKit.xcframework"
(
cd "${GHOSTTY_SOURCE_DIR}"
PATH="$(dirname "${GHOSTTY_ZIG}"):${PATH}" "${GHOSTTY_ZIG}" build \
-Dapp-runtime=none \
-Demit-xcframework=true \
-Demit-macos-app=false \
-Demit-exe=false \
-Demit-docs=false \
-Demit-webdata=false \
-Demit-helpgen=false \
-Demit-terminfo=false \
-Demit-termcap=false \
-Demit-themes=false \
-Doptimize=ReleaseFast \
-Dstrip \
-Dxcframework-target=universal
)
xcframework="${GHOSTTY_SOURCE_DIR}/macos/GhosttyKit.xcframework"
ios_archive="${xcframework}/ios-arm64/libghostty-fat.a"
sim_archive="${xcframework}/ios-arm64-simulator/libghostty-fat.a"
[[ -f "${ios_archive}" ]] || die "missing built iOS archive: ${ios_archive}"
[[ -f "${sim_archive}" ]] || die "missing built iOS simulator archive: ${sim_archive}"
log "stripping iOS archives"
xcrun strip -S -x "${ios_archive}"
xcrun strip -S -x "${sim_archive}"
log "copying iOS archives into ${VENDOR_DIR}/GhosttyKit.xcframework"
cp "${ios_archive}" "${VENDOR_DIR}/GhosttyKit.xcframework/ios-arm64/libghostty-fat.a"
cp "${sim_archive}" "${VENDOR_DIR}/GhosttyKit.xcframework/ios-arm64-simulator/libghostty-fat.a"
rsync -a --delete "${xcframework}/ios-arm64/Headers/" \
"${VENDOR_DIR}/GhosttyKit.xcframework/ios-arm64/Headers/"
rsync -a --delete "${xcframework}/ios-arm64-simulator/Headers/" \
"${VENDOR_DIR}/GhosttyKit.xcframework/ios-arm64-simulator/Headers/"
log "done"
+103
View File
@@ -0,0 +1,103 @@
{
"name": "@t3tools/mobile",
"version": "0.0.0",
"private": true,
"main": "index.ts",
"scripts": {
"dev": "expo start --clear",
"dev:client": "APP_VARIANT=development expo start --dev-client --clear",
"start": "expo start",
"start:dev": "APP_VARIANT=development expo start",
"start:preview": "APP_VARIANT=preview expo start",
"start:prod": "APP_VARIANT=production expo start",
"android": "EXPO_NO_GIT_STATUS=1 expo prebuild --clean --platform android && expo run:android",
"android:dev": "APP_VARIANT=development EXPO_NO_GIT_STATUS=1 expo prebuild --clean --platform android && expo run:android",
"android:preview": "APP_VARIANT=preview EXPO_NO_GIT_STATUS=1 expo prebuild --clean --platform android && expo run:android",
"android:prod": "APP_VARIANT=production EXPO_NO_GIT_STATUS=1 expo prebuild --clean --platform android && expo run:android",
"eas:android:dev": "eas build --profile development -p android",
"eas:android:preview": "eas build --profile preview -p android",
"eas:android:prod": "eas build --profile production -p android",
"ios": "EXPO_NO_GIT_STATUS=1 expo prebuild --clean --platform ios && expo run:ios",
"ios:dev": "APP_VARIANT=development EXPO_NO_GIT_STATUS=1 expo prebuild --clean --platform ios && expo run:ios",
"ios:preview": "APP_VARIANT=preview EXPO_NO_GIT_STATUS=1 expo prebuild --clean --platform ios && expo run:ios",
"ios:prod": "APP_VARIANT=production EXPO_NO_GIT_STATUS=1 expo prebuild --clean --platform ios && expo run:ios",
"eas:ios:dev": "eas build --profile development -p ios",
"eas:ios:preview": "eas build --profile preview -p ios",
"eas:ios:prod": "eas build --profile production -p ios",
"eas:dev": "eas build --profile development",
"eas:preview": "eas build --profile preview",
"eas:prod": "eas build --profile production",
"config:dev": "APP_VARIANT=development expo config",
"config:preview": "APP_VARIANT=preview expo config",
"config:prod": "APP_VARIANT=production expo config",
"profile:android:hermes": "mkdir -p profiles/review && react-native profile-hermes profiles/review",
"test": "vitest run",
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@callstack/liquid-glass": "^0.7.1",
"@effect/atom-react": "catalog:",
"@expo-google-fonts/dm-sans": "^0.4.2",
"@legendapp/list": "3.0.0-beta.44",
"@pierre/diffs": "catalog:",
"@react-native-menu/menu": "^2.0.0",
"@shikijs/core": "3.23.0",
"@shikijs/engine-javascript": "3.23.0",
"@shikijs/langs": "3.23.0",
"@shikijs/themes": "3.23.0",
"@t3tools/client-runtime": "workspace:*",
"@t3tools/contracts": "workspace:*",
"@t3tools/mobile-review-diff-native": "file:./modules/t3-review-diff",
"@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",
"expo-dev-client": "~55.0.26",
"expo-file-system": "~55.0.16",
"expo-font": "^55.0.4",
"expo-glass-effect": "~55.0.8",
"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",
"expo-splash-screen": "~55.0.13",
"expo-symbols": "~55.0.5",
"expo-updates": "~55.0.16",
"punycode": "^2.3.1",
"react": "19.2.5",
"react-dom": "19.2.5",
"react-native": "0.83.4",
"react-native-gesture-handler": "~2.30.0",
"react-native-image-viewing": "^0.2.2",
"react-native-keyboard-controller": "1.20.7",
"react-native-nitro-markdown": "^0.5.0",
"react-native-nitro-modules": "^0.35.4",
"react-native-reanimated": "4.2.1",
"react-native-safe-area-context": "~5.6.2",
"react-native-screens": "~4.23.0",
"react-native-shiki-engine": "^0.3.9",
"react-native-svg": "15.15.3",
"react-native-worklets": "0.7.2",
"shiki": "3.23.0",
"tailwind-merge": "^3.5.0",
"uniwind": "^1.6.2"
},
"devDependencies": {
"@types/react": "~19.2.0",
"babel-preset-expo": "~55.0.8",
"tailwindcss": "^4.0.0",
"typescript": "catalog:"
},
"overrides": {
"react-native-nitro-markdown": "file:deps/react-native-nitro-markdown-0.5.0.tgz"
}
}
@@ -0,0 +1,18 @@
const { withAndroidManifest } = require("expo/config-plugins");
module.exports = function withAndroidCleartextTraffic(config) {
return withAndroidManifest(config, (nextConfig) => {
const application = nextConfig.modResults.manifest.application?.[0];
if (application == null) {
throw new Error(
"AndroidManifest.xml is missing the application element required for cleartext traffic configuration.",
);
}
application.$ ??= {};
application.$["android:usesCleartextTraffic"] = "true";
return nextConfig;
});
};
+43
View File
@@ -0,0 +1,43 @@
import { Link } from "expo-router";
import { Pressable, ScrollView, StyleSheet } from "react-native";
import { useResolveClassNames } from "uniwind";
import { AppText as Text } from "../components/AppText";
export default function NotFoundRoute() {
const screenBgStyle = StyleSheet.flatten(useResolveClassNames("bg-screen"));
const primaryBgStyle = StyleSheet.flatten(useResolveClassNames("bg-primary"));
return (
<ScrollView
contentInsetAdjustmentBehavior="automatic"
contentContainerStyle={{
flexGrow: 1,
alignItems: "center",
justifyContent: "center",
gap: 16,
paddingHorizontal: 24,
paddingVertical: 32,
}}
style={[{ flex: 1 }, screenBgStyle]}
>
<Text className="text-[28px] font-t3-bold text-foreground" selectable>
Route not found
</Text>
<Link href="/" asChild>
<Pressable
style={[
{
borderRadius: 999,
paddingHorizontal: 20,
paddingVertical: 14,
},
primaryBgStyle,
]}
>
<Text className="text-[16px] font-t3-bold text-primary-foreground">Return home</Text>
</Pressable>
</Link>
</ScrollView>
);
}
+104
View File
@@ -0,0 +1,104 @@
import "../../global.css";
import {
DMSans_400Regular,
DMSans_500Medium,
DMSans_700Bold,
useFonts,
} from "@expo-google-fonts/dm-sans";
import Stack from "expo-router/stack";
import { StatusBar, useColorScheme } from "react-native";
import { GestureHandlerRootView } from "react-native-gesture-handler";
import { KeyboardProvider } from "react-native-keyboard-controller";
import { SafeAreaProvider } from "react-native-safe-area-context";
import { useCSSVariable, useResolveClassNames } from "uniwind";
import { LoadingScreen } from "../components/LoadingScreen";
import {
useRemoteEnvironmentBootstrap,
useRemoteEnvironmentState,
} from "../state/use-remote-environment-registry";
import { RegistryContext } from "@effect/atom-react";
import { appAtomRegistry } from "../state/atom-registry";
function AppNavigator() {
const { isLoadingSavedConnection } = useRemoteEnvironmentState();
const colorScheme = useColorScheme();
const statusBarBg = useCSSVariable("--color-status-bar");
const sheetStyle = useResolveClassNames("bg-sheet");
const newTaskScreenOptions = {
contentStyle: sheetStyle,
gestureEnabled: true,
headerShown: false,
presentation: "formSheet" as const,
sheetAllowedDetents: [0.92],
sheetGrabberVisible: true,
};
const connectionSheetScreenOptions = {
contentStyle: sheetStyle,
gestureEnabled: true,
headerShown: false,
presentation: "formSheet" as const,
sheetAllowedDetents: [0.55, 0.7],
sheetGrabberVisible: true,
};
if (isLoadingSavedConnection) {
return <LoadingScreen message="Loading remote workspace…" />;
}
return (
<>
<StatusBar
barStyle={colorScheme === "dark" ? "light-content" : "dark-content"}
backgroundColor={statusBarBg as string}
translucent
/>
<Stack screenOptions={{ headerShown: false }}>
<Stack.Screen
name="index"
options={{
contentStyle: { backgroundColor: "transparent" },
headerShown: true,
headerTransparent: true,
headerShadowVisible: false,
}}
/>
<Stack.Screen name="connections" options={connectionSheetScreenOptions} />
<Stack.Screen name="new" options={newTaskScreenOptions} />
<Stack.Screen
name="threads/[environmentId]/[threadId]"
options={{
animation: "slide_from_right",
contentStyle: { backgroundColor: "transparent" },
gestureEnabled: true,
headerShown: false,
}}
/>
</Stack>
</>
);
}
export default function RootLayout() {
const [fontsLoaded] = useFonts({
DMSans_400Regular,
DMSans_500Medium,
DMSans_700Bold,
});
useRemoteEnvironmentBootstrap();
return (
<RegistryContext value={appAtomRegistry}>
<GestureHandlerRootView style={{ flex: 1 }}>
<KeyboardProvider statusBarTranslucent>
<SafeAreaProvider>
{fontsLoaded ? <AppNavigator /> : <LoadingScreen message="Loading remote workspace…" />}
</SafeAreaProvider>
</KeyboardProvider>
</GestureHandlerRootView>
</RegistryContext>
);
}
@@ -0,0 +1,30 @@
import Stack from "expo-router/stack";
import { useResolveClassNames } from "uniwind";
import { useThemeColor } from "../../lib/useThemeColor";
export const unstable_settings = {
anchor: "index",
};
export default function ConnectionsLayout() {
const contentStyle = useResolveClassNames("bg-sheet");
const connSheetBg = String(useThemeColor("--color-sheet"));
const headerTint = String(useThemeColor("--color-icon"));
return (
<Stack
screenOptions={{
contentStyle,
headerStyle: { backgroundColor: connSheetBg },
headerTintColor: headerTint,
headerTitleStyle: { fontFamily: "DMSans_700Bold" },
headerShadowVisible: false,
headerBackButtonDisplayMode: "minimal",
}}
>
<Stack.Screen name="index" options={{ animation: "none" }} />
<Stack.Screen name="new" options={{ animation: "slide_from_right" }} />
</Stack>
);
}
+103
View File
@@ -0,0 +1,103 @@
import { Link, Stack } from "expo-router";
import { SymbolView } from "expo-symbols";
import type { EnvironmentId } from "@t3tools/contracts";
import { useCallback, useState } from "react";
import { Pressable, ScrollView, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { useThemeColor } from "../../lib/useThemeColor";
import { AppText as Text } from "../../components/AppText";
import { cn } from "../../lib/cn";
import { useRemoteConnections } from "../../state/use-remote-environment-registry";
import { ConnectionEnvironmentRow } from "../../features/connection/ConnectionEnvironmentRow";
export default function ConnectionsRouteScreen() {
const {
connectedEnvironments,
onReconnectEnvironment,
onRemoveEnvironmentPress,
onUpdateEnvironment,
} = useRemoteConnections();
const insets = useSafeAreaInsets();
const hasEnvironments = connectedEnvironments.length > 0;
const [expandedId, setExpandedId] = useState<EnvironmentId | null>(null);
const primaryFg = useThemeColor("--color-primary-foreground");
const accentColor = useThemeColor("--color-icon-muted");
const handleToggle = useCallback((environmentId: EnvironmentId) => {
setExpandedId((prev) => (prev === environmentId ? null : environmentId));
}, []);
return (
<View collapsable={false} className="flex-1 bg-sheet">
<Stack.Screen
options={{
title: "Backends",
headerRight: () => (
<Link href="/connections/new" asChild>
<Pressable className="h-10 w-10 items-center justify-center rounded-full bg-primary active:opacity-70">
<SymbolView
name="plus"
size={18}
tintColor={primaryFg}
type="monochrome"
weight="semibold"
/>
</Pressable>
</Link>
),
}}
/>
<ScrollView
contentInsetAdjustmentBehavior="automatic"
showsVerticalScrollIndicator={false}
style={{ flex: 1 }}
contentContainerStyle={{
paddingHorizontal: 20,
paddingTop: 16,
paddingBottom: Math.max(insets.bottom, 18) + 18,
}}
>
{hasEnvironments ? (
<View collapsable={false} className="overflow-hidden rounded-[24px] bg-card">
{connectedEnvironments.map((environment, index) => (
<View
key={environment.environmentId}
collapsable={false}
style={{
borderTopWidth: index === 0 ? 0 : 1,
}}
className={cn(index !== 0 && "border-border")}
>
<ConnectionEnvironmentRow
environment={environment}
expanded={expandedId === environment.environmentId}
onToggle={() => handleToggle(environment.environmentId)}
onReconnect={onReconnectEnvironment}
onRemove={onRemoveEnvironmentPress}
onUpdate={onUpdateEnvironment}
/>
</View>
))}
</View>
) : (
<View collapsable={false} className="items-center gap-3 rounded-[24px] bg-card px-6 py-8">
<View className="h-12 w-12 items-center justify-center rounded-[16px] bg-subtle">
<SymbolView
name="point.3.connected.trianglepath.dotted"
size={20}
tintColor={accentColor}
type="monochrome"
/>
</View>
<Text className="text-center text-[14px] leading-[20px] text-foreground-muted">
No backends connected yet.{"\n"}Tap{" "}
<Text className="font-t3-bold text-foreground">+</Text> to add one.
</Text>
</View>
)}
</ScrollView>
</View>
);
}
+253
View File
@@ -0,0 +1,253 @@
import { CameraView, useCameraPermissions } from "expo-camera";
import { Stack, useLocalSearchParams, useRouter } from "expo-router";
import { SymbolView } from "expo-symbols";
import { useCallback, useEffect, useState } from "react";
import { Alert, Pressable, ScrollView, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { useThemeColor } from "../../lib/useThemeColor";
import { AppText as Text, AppTextInput as TextInput } from "../../components/AppText";
import { ErrorBanner } from "../../components/ErrorBanner";
import { dismissRoute } from "../../lib/routes";
import { ConnectionSheetButton } from "../../features/connection/ConnectionSheetButton";
import { extractPairingUrlFromQrPayload } from "../../features/connection/pairing";
import { useRemoteConnections } from "../../state/use-remote-environment-registry";
import { buildPairingUrl, parsePairingUrl } from "../../features/connection/pairing";
export default function ConnectionsNewRouteScreen() {
const {
connectionError,
connectionPairingUrl,
connectionState,
onChangeConnectionPairingUrl,
onConnectPress,
} = useRemoteConnections();
const router = useRouter();
const params = useLocalSearchParams<{ mode?: string }>();
const insets = useSafeAreaInsets();
const [hostInput, setHostInput] = useState("");
const [codeInput, setCodeInput] = useState("");
const [isSubmitting, setIsSubmitting] = useState(false);
const [showScanner, setShowScanner] = useState(params.mode === "scan_qr");
const [cameraPermission, requestCameraPermission] = useCameraPermissions();
const [scannerLocked, setScannerLocked] = useState(false);
const textColor = useThemeColor("--color-icon");
const placeholderColor = useThemeColor("--color-placeholder");
const connectDisabled =
isSubmitting || connectionState === "connecting" || hostInput.trim().length === 0;
useEffect(() => {
const { host, code } = parsePairingUrl(connectionPairingUrl);
setHostInput(host);
setCodeInput(code);
}, [connectionPairingUrl]);
useEffect(() => {
if (connectionError) {
setIsSubmitting(false);
}
}, [connectionError]);
const handleHostChange = useCallback((value: string) => {
setHostInput(value);
}, []);
const handleCodeChange = useCallback((value: string) => {
setCodeInput(value);
}, []);
const openScanner = useCallback(async () => {
if (cameraPermission?.granted) {
setScannerLocked(false);
setShowScanner(true);
return;
}
const permission = await requestCameraPermission();
if (permission.granted) {
setScannerLocked(false);
setShowScanner(true);
return;
}
Alert.alert("Camera access needed", "Allow camera access to scan a backend pairing QR code.");
}, [cameraPermission?.granted, requestCameraPermission]);
const closeScanner = useCallback(() => {
setShowScanner(false);
setScannerLocked(false);
}, []);
const handleQrScan = useCallback(
({ data }: { readonly data: string }) => {
if (scannerLocked) {
return;
}
setScannerLocked(true);
try {
const pairingUrl = extractPairingUrlFromQrPayload(data);
const { host, code } = parsePairingUrl(pairingUrl);
setHostInput(host);
setCodeInput(code);
onChangeConnectionPairingUrl(pairingUrl);
setShowScanner(false);
} catch (error) {
Alert.alert(
"Invalid QR code",
error instanceof Error ? error.message : "Scanned QR code was not recognized.",
);
} finally {
setTimeout(() => {
setScannerLocked(false);
}, 600);
}
},
[onChangeConnectionPairingUrl, scannerLocked],
);
const handleSubmit = useCallback(async () => {
setIsSubmitting(true);
try {
const pairingUrl = buildPairingUrl(hostInput, codeInput);
onChangeConnectionPairingUrl(pairingUrl);
await onConnectPress(pairingUrl);
dismissRoute(router);
} catch {
setIsSubmitting(false);
}
}, [codeInput, hostInput, onChangeConnectionPairingUrl, onConnectPress, router]);
return (
<View collapsable={false} className="flex-1 bg-sheet">
<Stack.Screen
options={{
title: showScanner ? "Scan QR Code" : "Add Backend",
headerRight: () => (
<Pressable
className="h-10 w-10 items-center justify-center rounded-full border border-border bg-secondary"
onPress={() => {
if (showScanner) {
closeScanner();
} else {
void openScanner();
}
}}
>
<SymbolView
name={showScanner ? "xmark" : "qrcode.viewfinder"}
size={showScanner ? 14 : 18}
tintColor={textColor}
type="monochrome"
weight="semibold"
/>
</Pressable>
),
}}
/>
<ScrollView
contentInsetAdjustmentBehavior="automatic"
showsVerticalScrollIndicator={false}
style={{ flex: 1 }}
contentContainerStyle={{
paddingHorizontal: 20,
paddingTop: 16,
paddingBottom: Math.max(insets.bottom, 18) + 18,
}}
>
<View collapsable={false} className="gap-5">
{showScanner ? (
cameraPermission?.granted ? (
<View
className="overflow-hidden rounded-[24px]"
style={{ borderCurve: "continuous" }}
>
<CameraView
barcodeScannerSettings={{ barcodeTypes: ["qr"] }}
onBarcodeScanned={handleQrScan}
style={{ aspectRatio: 1, width: "100%" }}
/>
</View>
) : (
<View
className="items-center gap-3 rounded-[24px] bg-card px-5 py-8"
style={{ borderCurve: "continuous" }}
>
<Text className="text-center text-[14px] leading-[20px] text-foreground-muted">
Camera permission is required to scan a QR code.
</Text>
<ConnectionSheetButton
compact
icon="camera"
label="Allow camera"
tone="secondary"
onPress={() => {
void openScanner();
}}
/>
</View>
)
) : (
<View collapsable={false} className="gap-4 rounded-[24px] bg-card p-4">
<View collapsable={false} className="gap-1.5">
<Text
className="text-[11px] font-t3-bold uppercase text-foreground-muted"
style={{ letterSpacing: 0.8 }}
>
Host
</Text>
<TextInput
autoCapitalize="none"
autoCorrect={false}
keyboardType="url"
placeholder="192.168.1.100:8080"
placeholderTextColor={placeholderColor}
value={hostInput}
onChangeText={handleHostChange}
className="rounded-[14px] border border-input-border bg-input px-4 py-3.5 text-[15px] text-foreground"
/>
</View>
<View collapsable={false} className="gap-1.5">
<Text
className="text-[11px] font-t3-bold uppercase text-foreground-muted"
style={{ letterSpacing: 0.8 }}
>
Pairing code
</Text>
<TextInput
autoCapitalize="none"
autoCorrect={false}
placeholder="abc-123-xyz"
placeholderTextColor={placeholderColor}
value={codeInput}
onChangeText={handleCodeChange}
className="rounded-[14px] border border-input-border bg-input px-4 py-3.5 text-[15px] text-foreground"
/>
</View>
{connectionError ? <ErrorBanner message={connectionError} /> : null}
<ConnectionSheetButton
icon="plus"
label={
isSubmitting || connectionState === "connecting" ? "Pairing..." : "Add backend"
}
disabled={connectDisabled}
tone="primary"
onPress={() => {
void handleSubmit();
}}
/>
</View>
)}
</View>
</ScrollView>
</View>
);
}
+110
View File
@@ -0,0 +1,110 @@
import { Stack, useRouter } from "expo-router";
import { useState } from "react";
import { Text as RNText, View, useColorScheme } from "react-native";
import { useThemeColor } from "../lib/useThemeColor";
import { buildThreadRoutePath } from "../lib/routes";
import { useRemoteCatalog } from "../state/use-remote-catalog";
import { useRemoteEnvironmentState } from "../state/use-remote-environment-registry";
import { HomeScreen } from "../features/home/HomeScreen";
/* ─── Route screen ───────────────────────────────────────────────────── */
export default function HomeRouteScreen() {
const { projects, threads } = useRemoteCatalog();
const { savedConnectionsById } = useRemoteEnvironmentState();
const router = useRouter();
const [searchQuery, setSearchQuery] = useState("");
const isDark = useColorScheme() === "dark";
const iconColor = String(useThemeColor("--color-icon"));
return (
<>
<Stack.Screen
options={{
headerShown: true,
headerTransparent: true,
headerStyle: { backgroundColor: "transparent" },
headerShadowVisible: false,
headerTintColor: iconColor,
headerTitle: "",
headerSearchBarOptions: {
placeholder: "Search threads",
onChangeText: (event) => {
setSearchQuery(event.nativeEvent.text);
},
allowToolbarIntegration: true,
},
}}
/>
{/* Header left: plain text, no Liquid Glass button chrome */}
<Stack.Toolbar placement="left">
<Stack.Toolbar.View hidesSharedBackground>
<View style={{ flexDirection: "row", alignItems: "center", gap: 8 }}>
<RNText
style={{
fontFamily: "DMSans_700Bold",
fontSize: 17,
color: iconColor,
letterSpacing: -0.4,
}}
>
T3 Code
</RNText>
<View
style={{
backgroundColor: isDark ? "rgba(255,255,255,0.04)" : "rgba(0,0,0,0.04)",
borderRadius: 99,
paddingHorizontal: 8,
paddingVertical: 3,
}}
>
<RNText
style={{
fontFamily: "DMSans_700Bold",
fontSize: 10,
color: "#737373",
letterSpacing: 1.1,
textTransform: "uppercase",
}}
>
Alpha
</RNText>
</View>
</View>
</Stack.Toolbar.View>
</Stack.Toolbar>
<Stack.Toolbar placement="right">
<Stack.Toolbar.Button
icon="network"
onPress={() => router.push("/connections")}
separateBackground
/>
</Stack.Toolbar>
{/* Bottom toolbar: search + compose, visually split like iMessage */}
<Stack.Toolbar placement="bottom">
<Stack.Toolbar.SearchBarSlot />
<Stack.Toolbar.Spacer width={8} sharesBackground={false} />
<Stack.Toolbar.Button
icon="square.and.pencil"
onPress={() => router.push("/new")}
separateBackground
/>
</Stack.Toolbar>
<HomeScreen
projects={projects}
threads={threads}
savedConnectionsById={savedConnectionsById}
searchQuery={searchQuery}
onSelectThread={(thread) => {
router.push(buildThreadRoutePath(thread));
}}
/>
</>
);
}
+25
View File
@@ -0,0 +1,25 @@
import Stack from "expo-router/stack";
import { useResolveClassNames } from "uniwind";
import { NewTaskFlowProvider } from "../../features/threads/new-task-flow-provider";
export const unstable_settings = {
anchor: "index",
};
export default function NewTaskLayout() {
const sheetStyle = useResolveClassNames("bg-sheet");
return (
<NewTaskFlowProvider>
<Stack
screenOptions={{
contentStyle: sheetStyle,
}}
>
<Stack.Screen name="index" options={{ animation: "none" }} />
<Stack.Screen name="draft" options={{ animation: "slide_from_right" }} />
</Stack>
</NewTaskFlowProvider>
);
}
+24
View File
@@ -0,0 +1,24 @@
import { Stack, useLocalSearchParams } from "expo-router";
import { NewTaskDraftScreen } from "../../features/threads/NewTaskDraftScreen";
export default function NewTaskDraftRoute() {
const params = useLocalSearchParams<{
environmentId?: string | string[];
projectId?: string | string[];
}>();
return (
<>
<Stack.Screen options={{ headerShown: false }} />
<NewTaskDraftScreen
initialProjectRef={{
environmentId: Array.isArray(params.environmentId)
? params.environmentId[0]
: params.environmentId,
projectId: Array.isArray(params.projectId) ? params.projectId[0] : params.projectId,
}}
/>
</>
);
}
+135
View File
@@ -0,0 +1,135 @@
import { Link, Stack } from "expo-router";
import { SymbolView } from "expo-symbols";
import { useMemo } from "react";
import { Pressable, ScrollView, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { useThemeColor } from "../../lib/useThemeColor";
import { AppText as Text } from "../../components/AppText";
import { ProjectFavicon } from "../../components/ProjectFavicon";
import { groupProjectsByRepository } from "../../lib/repositoryGroups";
import { useRemoteCatalog } from "../../state/use-remote-catalog";
import { useRemoteEnvironmentState } from "../../state/use-remote-environment-registry";
export default function NewTaskRoute() {
const { projects, threads } = useRemoteCatalog();
const { savedConnectionsById } = useRemoteEnvironmentState();
const insets = useSafeAreaInsets();
const chevronColor = useThemeColor("--color-chevron");
const borderSubtleColor = useThemeColor("--color-border-subtle");
const repositoryGroups = useMemo(
() => groupProjectsByRepository({ projects, threads }),
[projects, threads],
);
const items = useMemo(
() =>
repositoryGroups
.map((group) => {
const project = group.projects[0]?.project;
if (!project) {
return null;
}
return {
environmentId: project.environmentId,
id: project.id,
key: group.key,
title: project.title,
workspaceRoot: project.workspaceRoot,
};
})
.filter((entry) => entry !== null),
[repositoryGroups],
);
return (
<View collapsable={false} className="flex-1 bg-sheet">
<Stack.Screen options={{ headerShown: false }} />
<View style={{ minHeight: 16, paddingTop: 8 }} />
<View className="items-center gap-1 px-5 pb-3 pt-4">
<Text
className="text-[12px] font-t3-bold uppercase text-foreground-muted"
style={{ letterSpacing: 1 }}
>
New task
</Text>
<Text className="text-[28px] font-t3-bold">Choose project</Text>
</View>
<ScrollView
showsVerticalScrollIndicator={false}
style={{ flex: 1 }}
contentContainerStyle={{
paddingHorizontal: 20,
paddingTop: 8,
paddingBottom: Math.max(insets.bottom, 18) + 18,
}}
>
{items.length === 0 ? (
<View collapsable={false} className="items-center rounded-[24px] bg-card px-6 py-8">
<Text className="text-[16px] font-medium text-foreground-muted">
Loading projects...
</Text>
</View>
) : (
<View collapsable={false} className="overflow-hidden rounded-[24px] bg-card">
{items.map((item, index) => {
const isFirst = index === 0;
const isLast = index === items.length - 1;
return (
<Link
key={item.key}
href={{
pathname: "/new/draft",
params: {
environmentId: item.environmentId,
projectId: item.id,
title: item.title,
},
}}
asChild
>
<Pressable
className="bg-card"
style={{
paddingHorizontal: 16,
paddingVertical: 18,
borderTopWidth: isFirst ? 0 : 1,
borderTopColor: borderSubtleColor,
borderTopLeftRadius: isFirst ? 24 : 0,
borderTopRightRadius: isFirst ? 24 : 0,
borderBottomLeftRadius: isLast ? 24 : 0,
borderBottomRightRadius: isLast ? 24 : 0,
}}
>
<View className="flex-row items-center justify-between gap-3">
<ProjectFavicon
size={22}
projectTitle={item.title}
httpBaseUrl={savedConnectionsById[item.environmentId]?.httpBaseUrl ?? null}
workspaceRoot={item.workspaceRoot}
bearerToken={savedConnectionsById[item.environmentId]?.bearerToken ?? null}
/>
<View className="flex-1">
<Text className="text-[18px] font-t3-bold">{item.title}</Text>
</View>
<SymbolView
name="chevron.right"
size={14}
tintColor={chevronColor}
type="monochrome"
/>
</View>
</Pressable>
</Link>
);
})}
</View>
)}
</ScrollView>
</View>
);
}
@@ -0,0 +1,80 @@
import Stack from "expo-router/stack";
import { StyleSheet } from "react-native";
import { useResolveClassNames } from "uniwind";
export default function ThreadLayout() {
const sheetStyle = StyleSheet.flatten(useResolveClassNames("bg-sheet"));
const headerBg = {
backgroundColor: (sheetStyle as { backgroundColor?: string })?.backgroundColor,
};
return (
<Stack screenOptions={{ headerShown: false }}>
<Stack.Screen
name="index"
options={{
contentStyle: { backgroundColor: "transparent" },
headerShown: true,
headerTransparent: true,
headerShadowVisible: false,
}}
/>
<Stack.Screen
name="git"
options={{
contentStyle: sheetStyle,
gestureEnabled: true,
headerShown: false,
presentation: "formSheet" as const,
sheetAllowedDetents: [0.85],
sheetGrabberVisible: true,
}}
/>
<Stack.Screen
name="git-confirm"
options={{
contentStyle: sheetStyle,
gestureEnabled: true,
headerShown: false,
presentation: "formSheet" as const,
sheetAllowedDetents: [0.4],
sheetGrabberVisible: true,
}}
/>
<Stack.Screen
name="review"
options={{
animation: "slide_from_right",
contentStyle: sheetStyle,
headerBackButtonDisplayMode: "minimal",
headerShown: true,
headerTitle: "Files changed",
headerBackTitle: "",
headerShadowVisible: false,
headerStyle: headerBg,
}}
/>
<Stack.Screen
name="review-comment"
options={{
contentStyle: sheetStyle,
gestureEnabled: true,
headerShown: false,
presentation: "formSheet" as const,
sheetAllowedDetents: [0.72, 0.92],
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 { GitConfirmSheet } from "../../../../features/threads/git/GitConfirmSheet";
export default function GitConfirmRoute() {
return <GitConfirmSheet />;
}
@@ -0,0 +1,58 @@
import Stack from "expo-router/stack";
import { StyleSheet } from "react-native";
import { useResolveClassNames } from "uniwind";
export const unstable_settings = {
anchor: "index",
};
export default function GitSheetLayout() {
const sheetStyle = StyleSheet.flatten(useResolveClassNames("bg-sheet"));
const headerBg = {
backgroundColor: (sheetStyle as { backgroundColor?: string })?.backgroundColor,
};
return (
<Stack
screenOptions={{
contentStyle: sheetStyle,
headerShown: false,
}}
>
<Stack.Screen name="index" options={{ animation: "none" }} />
<Stack.Screen
name="commit"
options={{
animation: "slide_from_right",
headerShown: true,
headerTitle: "Commit changes",
headerBackTitle: "",
headerShadowVisible: false,
headerStyle: headerBg,
}}
/>
<Stack.Screen
name="branches"
options={{
animation: "slide_from_right",
headerShown: true,
headerTitle: "Branches & worktrees",
headerBackTitle: "",
headerShadowVisible: false,
headerStyle: headerBg,
}}
/>
<Stack.Screen
name="review"
options={{
animation: "slide_from_right",
headerShown: true,
headerTitle: "Review changes",
headerBackTitle: "",
headerShadowVisible: false,
headerStyle: headerBg,
}}
/>
</Stack>
);
}
@@ -0,0 +1,5 @@
import { GitBranchesSheet } from "../../../../../features/threads/git/GitBranchesSheet";
export default function GitBranchesRoute() {
return <GitBranchesSheet />;
}
@@ -0,0 +1,5 @@
import { GitCommitSheet } from "../../../../../features/threads/git/GitCommitSheet";
export default function GitCommitRoute() {
return <GitCommitSheet />;
}
@@ -0,0 +1,5 @@
import { GitOverviewSheet } from "../../../../../features/threads/git/GitOverviewSheet";
export default function GitRoute() {
return <GitOverviewSheet />;
}
@@ -0,0 +1,18 @@
import { Redirect, useLocalSearchParams } from "expo-router";
import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
export default function ReviewRoute() {
const { environmentId, threadId } = useLocalSearchParams<{
environmentId: EnvironmentId;
threadId: ThreadId;
}>();
return (
<Redirect
href={{
pathname: "/threads/[environmentId]/[threadId]/review",
params: { environmentId, threadId },
}}
/>
);
}
@@ -0,0 +1,5 @@
import { ThreadRouteScreen } from "../../../../features/threads/ThreadRouteScreen";
export default function ThreadRoute() {
return <ThreadRouteScreen />;
}
@@ -0,0 +1,5 @@
import { ReviewCommentComposerSheet } from "../../../../features/review/ReviewCommentComposerSheet";
export default function ReviewCommentRoute() {
return <ReviewCommentComposerSheet />;
}
@@ -0,0 +1,5 @@
import { ReviewSheet } from "../../../../features/review/ReviewSheet";
export default function ReviewRoute() {
return <ReviewSheet />;
}
@@ -0,0 +1,5 @@
import { ThreadTerminalRouteScreen } from "../../../../features/terminal/ThreadTerminalRouteScreen";
export default function ThreadTerminalRoute() {
return <ThreadTerminalRouteScreen />;
}
+40
View File
@@ -0,0 +1,40 @@
import {
Text as RNText,
TextInput as RNTextInput,
type TextInputProps as RNTextInputProps,
type TextProps as RNTextProps,
} from "react-native";
import { useThemeColor } from "../lib/useThemeColor";
import { cn } from "../lib/cn";
export type AppTextProps = RNTextProps & { readonly className?: string };
/**
* Thin wrapper around RN Text with default font-family and foreground color.
* Uses Uniwind className — no manual style parsing.
*/
export function AppText({ className, ...props }: AppTextProps) {
return <RNText className={cn("font-sans text-foreground", className)} {...props} />;
}
export type AppTextInputProps = RNTextInputProps & { readonly className?: string };
/**
* Thin wrapper around RN TextInput with default input styling.
* Uses Uniwind className — no manual style parsing.
*/
export function AppTextInput({ className, placeholderTextColor, ...props }: AppTextInputProps) {
const placeholderColor = useThemeColor("--color-placeholder");
return (
<RNTextInput
className={cn(
"min-h-[54px] rounded-2xl border border-input-border bg-input px-3.5 py-3 font-sans text-[15px] text-foreground",
className,
)}
placeholderTextColor={placeholderTextColor ?? placeholderColor}
{...props}
/>
);
}
+48
View File
@@ -0,0 +1,48 @@
import { Image, View } from "react-native";
import { AppText as Text } from "./AppText";
const BRAND_MARK_SOURCE = require("../../../../assets/dev/blueprint-ios-1024.png");
export function BrandMark(props: { readonly compact?: boolean; readonly stageLabel?: string }) {
const compact = props.compact ?? false;
const iconSize = compact ? 32 : 44;
const stageLabel = props.stageLabel ?? "Alpha";
return (
<View className="flex-row items-center gap-3">
<Image
source={BRAND_MARK_SOURCE}
accessibilityIgnoresInvertColors
style={{
width: iconSize,
height: iconSize,
borderRadius: compact ? 10 : 14,
}}
/>
<View className="gap-1">
<View className="flex-row items-center gap-2">
<Text
className="text-[17px] font-t3-bold text-foreground"
style={{ letterSpacing: -0.4 }}
>
T3 Code
</Text>
<View className="rounded-full bg-subtle px-2 py-1">
<Text
className="text-[10px] font-t3-bold uppercase text-foreground-muted"
style={{ letterSpacing: 1.1 }}
>
{stageLabel}
</Text>
</View>
</View>
{!compact ? (
<Text className="text-[12px] font-medium text-foreground-muted">
Mobile control surface for your live coding environments
</Text>
) : null}
</View>
</View>
);
}
Loaded 100 of 397 files, more files were not shown because too many files have changed in this diff. Show more