Compare commits

..
Author SHA1 Message Date
Cursor AgentandJulius Marminge 477c9aae5e perf(web): avoid rerendering branch picker while scrolling
Co-authored-by: Julius Marminge <[email protected]>
2026-07-15 17:07:25 +00:00
Julius Marmingeandcodex ecb35f7583 Fix Legal modal header crash (#4000)
Co-authored-by: codex <[email protected]>
2026-07-15 10:48:55 +00:00
Julius Marmingeandcodex d359789ed4 docs: Add T3 Code Legal Docs (#3972)
Co-authored-by: codex <[email protected]>
2026-07-15 11:44:03 +02:00
Kriday Dave 462442667e fix(docs): replace stale codething-mvp absolute paths with repo-relative links (#3992) 2026-07-15 10:55:01 +02:00
Kriday Dave c69120f484 fix(docs): repair broken source links in architecture overview (#3991) 2026-07-15 10:54:40 +02:00
Kriday Dave 7b928d5488 fix(docs): correct CI task-runner commands in ci.md (#3990) 2026-07-15 10:53:48 +02:00
Theo Browne 2fdc704bbb perf(web): duty-cycle status animations and remove fixed noise overlay (#3978) 2026-07-15 09:08:33 +02:00
Julius Marminge 3513fa04fb Prepare Android beta branding and review diff UI (#3967) 2026-07-14 19:21:12 +02:00
Julius Marminge 735240f316 Skip stale working-task notifications (#3961) 2026-07-14 18:00:16 +02:00
Julius Marminge 8de254a685 Use client-side fallbacks for missing project favicons (#3959) 2026-07-14 17:59:00 +02:00
c1ec1915fc [codex] Add Android mobile support (#3579)
Co-authored-by: Horus Lugo <[email protected]>
Co-authored-by: Claude Fable 5 <[email protected]>
Co-authored-by: maria-rcks <[email protected]>
Co-authored-by: Shivam Sharma <[email protected]>
Co-authored-by: Ben Davis <[email protected]>
Co-authored-by: Alex <[email protected]>
Co-authored-by: codex <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-07-12 12:03:35 +02:00
Vedank Purohit 619b0ece94 fix(marketing): show platform-appropriate commit shortcut on the website (#3644) 2026-07-12 09:58:55 +00:00
Jake Leventhal ef943a26ab Fix truncated chat error alert layout (#3899) 2026-07-12 09:50:15 +00:00
Julius Marmingeandcodex f61fa9499d Expose mobile PR indicator labels to accessibility (#3828)
Co-authored-by: codex <[email protected]>
2026-07-09 14:00:51 +00:00
Julius Marmingeandcodex 8619ef22e9 Show compact PR number badges in mobile thread rows (#3827)
Co-authored-by: codex <[email protected]>
2026-07-09 15:29:55 +02:00
Julius Marmingeandcodex 843cf176ea fix(mobile): embed fonts and render project favicons reliably (#3823)
Co-authored-by: codex <[email protected]>
2026-07-09 13:49:16 +02:00
Julius Marmingeandcodex ca1e08b5a0 [codex] Label max and ultra reasoning (#3824)
Co-authored-by: codex <[email protected]>
2026-07-09 10:20:32 +00:00
2250e3ee7a feat(client): persist offline environment data and mobile preferences (#3795)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-07-09 11:23:51 +02:00
295 changed files with 26528 additions and 3918 deletions

No files matched your search

@@ -43,6 +43,15 @@ Review changed TypeScript and directly affected call sites for the conventions b
- Keep implementation-specific names when an abstract port module contains one of several possible implementations, for example `makeCloudflaredRelayClient` and `layerCloudflared` in `RelayClient.ts`.
- `infra/relay/src/db.ts` is an intentional exception: an inline `Layer.succeed(RelayDb, db)` is acceptable without generic `make`/`layer` exports.
## Dependency acquisition and runtime boundaries
- Production service construction must acquire Effect service dependencies from the environment with `yield* Foo.Foo`, and its `make`/`layer` types must expose those requirements. Flag factories or constructors that accept `Foo["Service"]` (or a plain object whose methods return `Effect`) when that value is an implementation dependency owned by the service. Passing service instances explicitly is acceptable in tests and integration harnesses; passing pure configuration, immutable domain values, or deliberate callback strategies is not service injection.
- Do not hide dependencies in module globals, closures over singleton services, or `Layer.succeed` implementations that call runtime-backed or imperative APIs. Trace helpers used by a supposedly synchronous layer far enough to verify that asynchronous services are represented in the Effect environment.
- `ManagedRuntime.make`, `runPromise`, and `runPromiseExit` belong at explicit application/framework boundaries such as React, native callback, CLI, or HTTP adapters. Flag their use in domain services, repositories, persistence implementations, and service constructors. A clearly named imperative adapter may bridge an Effect service into a Promise API, but it must not become a dependency of another Effect service.
- Do not create per-feature managed runtimes or Atom runtimes to smuggle the same owned resource into multiple consumers. Compose the resource once in an application-owned layer/runtime and provide its context to integration runtimes.
- When acquisition can fail but a caller must retain fallback behavior, keep the failure typed in Effect rather than bypassing the layer through an imperative runtime. Model unavailability in service operations or with an explicit optional-service layer so downstream recovery remains visible and testable.
- During review, search touched code and affected call sites for service-instance parameters, `Layer.succeed`, `ManagedRuntime.make`, and `.runPromise`/`.runPromiseExit`. Verify that each occurrence is a legitimate test seam, pure value injection, or application boundary—not fake dependency injection or a hidden runtime.
## Errors and predicates
- Define service failures with `Schema.TaggedErrorClass` and structured attributes. Derive `message` from those attributes rather than storing an unstructured message as the only data.
+3
View File
@@ -0,0 +1,3 @@
{
"expo": {}
}
@@ -0,0 +1,414 @@
---
import Layout from "../layouts/Layout.astro";
interface Props {
readonly title: string;
readonly description: string;
readonly heading: string;
readonly lede: string;
readonly effectiveDate: string;
readonly lastUpdated: string;
readonly sections: ReadonlyArray<readonly [id: string, label: string]>;
}
const { title, description, heading, lede, effectiveDate, lastUpdated, sections } = Astro.props;
---
<Layout title={title} description={description} pageClass="legal-document-page">
<div class="legal-page">
<a class="legal-index-link" href="/legal"><span aria-hidden="true">&#8592;</span> All legal documents</a>
<header class="legal-hero">
<p class="eyebrow">T3 Tools, Inc. / Legal</p>
<h1>{heading}</h1>
<p class="legal-lede">{lede}</p>
<dl class="legal-dates" aria-label="Document dates">
<div>
<dt>Effective Date</dt>
<dd>{effectiveDate}</dd>
</div>
<div>
<dt>Last Updated</dt>
<dd>{lastUpdated}</dd>
</div>
</dl>
</header>
<div class="legal-rule" aria-hidden="true"></div>
<div class="legal-layout">
<aside class="legal-nav" aria-label="On this page">
<p class="legal-nav-label">On this page</p>
<ol>
{sections.map(([id, label], index) => (
<li>
<a href={`#${id}`} data-legal-nav-link={id}>
<span>{String(index + 1).padStart(2, "0")}</span>
{label}
</a>
</li>
))}
</ol>
</aside>
<article class="legal-copy">
<slot />
</article>
</div>
</div>
</Layout>
<script>
const navLinks = Array.from(
document.querySelectorAll<HTMLAnchorElement>("[data-legal-nav-link]"),
);
const sections = navLinks
.map((link) => {
const id = link.dataset.legalNavLink;
const section = id ? document.getElementById(id) : null;
return section ? { link, section } : null;
})
.filter((entry): entry is { link: HTMLAnchorElement; section: HTMLElement } => entry !== null);
let activeId = "";
let frame = 0;
const updateActiveSection = () => {
frame = 0;
const marker = Math.min(180, window.innerHeight * 0.28);
let active = sections[0];
for (const entry of sections) {
if (entry.section.getBoundingClientRect().top > marker) break;
active = entry;
}
if (window.scrollY + window.innerHeight >= document.documentElement.scrollHeight - 2) {
active = sections[sections.length - 1];
}
if (!active || active.section.id === activeId) return;
activeId = active.section.id;
for (const { link, section } of sections) {
if (section.id === activeId) {
link.setAttribute("aria-current", "location");
} else {
link.removeAttribute("aria-current");
}
}
};
const scheduleUpdate = () => {
if (frame) return;
frame = window.requestAnimationFrame(updateActiveSection);
};
updateActiveSection();
window.addEventListener("scroll", scheduleUpdate, { passive: true });
window.addEventListener("resize", scheduleUpdate);
</script>
<style is:global>
.legal-page {
width: min(1120px, calc(100% - 64px));
margin: 0 auto;
padding: clamp(72px, 10vw, 132px) 0 112px;
}
.legal-index-link {
display: none;
}
.legal-hero {
max-width: 820px;
animation: fade-in 0.8s ease-out both;
}
.legal-hero h1 {
margin-top: 18px;
font-size: clamp(3.4rem, 8vw, 7.4rem);
font-weight: 500;
letter-spacing: -0.02em;
line-height: 0.9;
}
.legal-lede {
max-width: 720px;
margin-top: 34px;
color: var(--fg-muted);
font-size: clamp(1.05rem, 1.8vw, 1.3rem);
line-height: 1.65;
letter-spacing: -0.012em;
}
.legal-dates {
display: flex;
flex-wrap: wrap;
gap: 36px;
margin-top: 38px;
}
.legal-dates div {
display: grid;
gap: 4px;
}
.legal-dates dt,
.legal-nav-label,
.section-number {
color: var(--fg-dim);
font-family: var(--font-mono);
font-size: 0.68rem;
font-weight: 500;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.legal-dates dd {
color: var(--fg);
font-family: var(--font-mono);
font-size: 0.8rem;
}
.legal-rule {
height: 1px;
margin: 72px 0;
background: linear-gradient(90deg, var(--border-strong), var(--border) 65%, transparent);
}
.legal-layout {
display: grid;
grid-template-columns: 210px minmax(0, 720px);
gap: clamp(64px, 10vw, 140px);
align-items: start;
}
.legal-nav {
position: sticky;
top: 88px;
max-height: calc(100vh - 112px);
overflow-y: auto;
scrollbar-width: thin;
}
.legal-nav ol {
display: grid;
gap: 2px;
margin-top: 16px;
padding-bottom: 12px;
list-style: none;
}
.legal-nav a {
display: grid;
grid-template-columns: 24px 1fr;
gap: 9px;
margin-left: -10px;
padding: 7px 8px 7px 10px;
border-radius: 6px;
color: var(--fg-dim);
font-size: 0.78rem;
line-height: 1.35;
transition:
color 0.16s ease,
background-color 0.16s ease,
box-shadow 0.16s ease;
}
.legal-nav a span {
color: var(--fg-faint);
font-family: var(--font-mono);
font-size: 0.64rem;
line-height: 1.7;
}
.legal-nav a:hover {
color: var(--fg);
}
.legal-nav a[aria-current="location"] {
color: var(--fg);
background: color-mix(in srgb, var(--accent) 8%, transparent);
box-shadow: inset 2px 0 var(--accent);
}
.legal-nav a[aria-current="location"] span {
color: var(--accent);
}
.legal-copy {
min-width: 0;
}
.legal-copy section {
scroll-margin-top: 104px;
}
.legal-copy section + section {
margin-top: 82px;
padding-top: 82px;
border-top: 1px solid var(--border);
}
.section-number {
color: var(--accent);
}
.legal-copy h2 {
margin: 8px 0 28px;
color: var(--fg);
font-size: clamp(1.75rem, 3vw, 2.45rem);
font-weight: 500;
letter-spacing: -0.04em;
line-height: 1.1;
}
.legal-copy h3 {
margin: 32px 0 10px;
color: var(--fg);
font-size: 1rem;
font-weight: 600;
letter-spacing: -0.015em;
}
.legal-copy h4 {
margin: 24px 0 8px;
color: var(--fg);
font-size: 0.94rem;
font-weight: 600;
}
.legal-copy p,
.legal-copy li,
.legal-copy address {
color: var(--fg-muted);
font-size: 0.98rem;
font-style: normal;
line-height: 1.78;
}
.legal-copy p + p {
margin-top: 18px;
}
.legal-copy strong {
color: var(--fg);
font-weight: 600;
}
.legal-copy ul,
.legal-copy ol {
display: grid;
gap: 12px;
margin: 18px 0 20px;
padding-left: 1.2rem;
}
.legal-copy li {
padding-left: 7px;
}
.legal-copy li::marker {
color: var(--accent);
}
.legal-copy .provider-list {
gap: 28px;
}
.provider-list a,
.legal-copy a {
overflow-wrap: anywhere;
}
.legal-copy a {
color: var(--fg);
text-decoration: underline;
text-decoration-color: color-mix(in srgb, var(--accent) 55%, transparent);
text-underline-offset: 4px;
transition: text-decoration-color 0.16s ease;
}
.legal-copy a:hover {
text-decoration-color: var(--accent);
}
.legal-notice {
color: var(--fg) !important;
font-weight: 600;
}
.legal-copy address {
margin-top: 20px;
}
.contact-link {
display: inline-block;
margin-top: 18px;
font-family: var(--font-mono);
font-size: 0.9rem;
}
@media (max-width: 820px) {
.legal-index-link {
display: inline-flex;
align-items: center;
gap: 8px;
margin-bottom: 38px;
color: var(--fg-dim);
font-family: var(--font-mono);
font-size: 0.72rem;
letter-spacing: 0.04em;
text-transform: uppercase;
}
.legal-page {
width: min(100% - 40px, 720px);
padding-top: 56px;
padding-bottom: 80px;
}
.legal-hero h1 {
font-size: clamp(3.1rem, 16vw, 5rem);
}
.legal-rule {
margin: 52px 0;
}
.legal-layout {
display: block;
}
.legal-nav {
display: none;
}
.legal-copy section + section {
margin-top: 62px;
padding-top: 62px;
}
}
@media (max-width: 420px) {
.legal-page {
width: calc(100% - 32px);
padding-top: 42px;
}
.legal-lede {
margin-top: 26px;
font-size: 1rem;
}
.legal-dates {
gap: 24px;
}
.legal-copy p,
.legal-copy li,
.legal-copy address {
font-size: 0.94rem;
}
}
</style>
+31 -2
View File
@@ -4,11 +4,13 @@ import { GITHUB_REPOSITORY_URL, MARKETING_STATS } from "../lib/site";
interface Props {
title?: string;
description?: string;
pageClass?: string;
}
const {
title = "T3 Code",
description = "T3 Code — The open-source control plane for coding agents.",
pageClass,
} = Astro.props;
---
@@ -30,7 +32,7 @@ const {
<title>{title}</title>
</head>
<body>
<div class="page">
<div class:list={["page", pageClass]}>
<nav class="nav">
<div class="nav-inner">
<a href="/" class="nav-brand" aria-label="T3 Code home">
@@ -67,6 +69,9 @@ const {
<a href={GITHUB_REPOSITORY_URL} target="_blank" rel="noopener noreferrer">GitHub</a>
<a href="https://discord.gg/jn4EGJjrvv" target="_blank" rel="noopener noreferrer">Discord</a>
<a href="/download">Download</a>
<a href="/terms-of-service">Terms</a>
<a href="/privacy-policy">Privacy</a>
<a href="/security-policy">Security</a>
</div>
</div>
</footer>
@@ -279,7 +284,7 @@ const {
min-height: 100vh;
display: flex;
flex-direction: column;
overflow-x: hidden;
overflow-x: clip;
}
.nav {
@@ -402,6 +407,8 @@ const {
.footer-links {
display: flex;
flex-wrap: wrap;
justify-content: flex-end;
gap: 20px;
}
@@ -421,6 +428,28 @@ const {
padding-left: 20px;
padding-right: 20px;
}
.legal-document-page .nav {
display: none;
}
.footer {
padding-bottom: max(32px, env(safe-area-inset-bottom));
}
.footer-inner {
align-items: flex-start;
flex-direction: column;
gap: 28px;
}
.footer-links {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
width: 100%;
gap: 14px 20px;
justify-content: initial;
}
}
@media (max-width: 420px) {
+3 -1
View File
@@ -254,7 +254,7 @@ const mobileEndorsementRows = [
<button class="pr-button">
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><circle cx="6" cy="6" r="2.2"/><circle cx="6" cy="18" r="2.2"/><circle cx="18" cy="6" r="2.2"/><path d="M6 8v8M18 8v5a3 3 0 01-3 3h-3M13 13l-2 3 2 3"/></svg>
Commit &amp; push
<span class="pr-button-kbd">⌘⏎</span>
<span id="pr-button-kbd" class="pr-button-kbd">⌘⏎</span>
</button>
</div>
</div>
@@ -403,12 +403,14 @@ const mobileEndorsementRows = [
const label = document.getElementById("download-label");
const ctaBtn = document.getElementById("cta-download-btn") as HTMLAnchorElement | null;
const ctaLabel = document.getElementById("cta-download-label");
const kbd = document.getElementById("pr-button-kbd");
const platform = detectPlatform();
if (!platform) return;
document.documentElement.dataset.platform = platform.os;
if (label) label.textContent = platform.label;
if (ctaLabel) ctaLabel.textContent = platform.label;
if (kbd && platform.os !== "mac") kbd.textContent = "Ctrl ⏎";
try {
const release = await fetchLatestRelease();
+172
View File
@@ -0,0 +1,172 @@
---
import Layout from "../layouts/Layout.astro";
const documents = [
{
number: "01",
title: "Privacy Policy",
description: "How T3 Code handles information, connected services, and your privacy choices.",
href: "/privacy-policy",
},
{
number: "02",
title: "Terms of Service",
description: "The terms that govern your use of T3 Code and T3 Tools-operated services.",
href: "/terms-of-service",
},
{
number: "03",
title: "Security Policy",
description: "Our security practices, responsible disclosure process, and shared responsibilities.",
href: "/security-policy",
},
] as const;
---
<Layout
title="Legal — T3 Code"
description="Privacy, terms, and security documents for T3 Code."
pageClass="legal-document-page"
>
<div class="legal-index">
<header class="legal-index-hero">
<p class="eyebrow">T3 Tools, Inc. / Legal</p>
<h1>Legal</h1>
<p>Policies and terms for T3 Code, collected in one place.</p>
</header>
<nav class="document-list" aria-label="Legal documents">
{documents.map((document) => (
<a href={document.href} class="document-card">
<span class="document-number">{document.number}</span>
<span class="document-copy">
<strong>{document.title}</strong>
<span>{document.description}</span>
</span>
<span class="document-arrow" aria-hidden="true">&#8599;</span>
</a>
))}
</nav>
</div>
</Layout>
<style>
.legal-index {
width: min(960px, calc(100% - 64px));
margin: 0 auto;
padding: clamp(72px, 10vw, 132px) 0 112px;
}
.legal-index-hero {
max-width: 680px;
animation: fade-in 0.7s ease-out both;
}
.legal-index h1 {
margin-top: 18px;
font-size: clamp(4rem, 10vw, 7.4rem);
font-weight: 500;
letter-spacing: -0.04em;
line-height: 0.9;
}
.legal-index-hero > p:last-child {
margin-top: 30px;
color: var(--fg-muted);
font-size: clamp(1.05rem, 2vw, 1.3rem);
line-height: 1.65;
}
.document-list {
display: grid;
margin-top: clamp(64px, 9vw, 96px);
border-top: 1px solid var(--border);
}
.document-card {
display: grid;
grid-template-columns: 42px minmax(0, 1fr) auto;
gap: 24px;
align-items: center;
padding: 30px 8px;
border-bottom: 1px solid var(--border);
transition: background-color 0.18s ease, padding 0.18s ease;
}
.document-number {
color: var(--accent);
font-family: var(--font-mono);
font-size: 0.7rem;
letter-spacing: 0.1em;
}
.document-copy {
display: grid;
gap: 7px;
}
.document-copy strong {
color: var(--fg);
font-size: 1.2rem;
font-weight: 500;
letter-spacing: -0.02em;
}
.document-copy > span {
color: var(--fg-dim);
font-size: 0.9rem;
line-height: 1.55;
}
.document-arrow {
color: var(--fg-dim);
font-size: 1.25rem;
transition: color 0.18s ease, transform 0.18s ease;
}
@media (hover: hover) and (pointer: fine) {
.document-card:hover {
padding-left: 16px;
padding-right: 16px;
background: rgba(255, 255, 255, 0.025);
}
.document-card:hover .document-arrow {
color: var(--fg);
transform: translate(2px, -2px);
}
}
@media (max-width: 820px) {
.legal-index {
width: min(100% - 40px, 720px);
padding-top: 56px;
padding-bottom: 80px;
}
.document-card {
grid-template-columns: 30px minmax(0, 1fr) auto;
gap: 14px;
padding: 24px 4px;
}
}
@media (max-width: 420px) {
.legal-index {
width: calc(100% - 32px);
padding-top: 42px;
}
.legal-index h1 {
font-size: 4.4rem;
}
.document-copy strong {
font-size: 1.08rem;
}
.document-copy > span {
font-size: 0.84rem;
}
}
</style>
@@ -0,0 +1,445 @@
---
import LegalPage from "../components/LegalPage.astro";
const sections = [
["introduction", "Introduction"],
["information", "Personal information we collect"],
["uses", "How we use your personal information"],
["sharing", "How we share your personal information"],
["choices", "Your choices regarding your personal information"],
["security", "Security of your personal information"],
["international", "International users"],
["children", "Children"],
["do-not-track", "Do Not Track"],
["updates", "Updates to this Privacy Policy"],
["contact", "Contact us"],
] as const;
---
<LegalPage
title="Privacy Policy — T3 Code"
description="How T3 Tools, Inc. handles information when you use T3 Code, app.t3.codes, and t3.codes."
heading="T3 Code Privacy Policy"
lede="This Privacy Policy describes how T3 Tools, Inc. collects, uses, and shares personal information when you use the T3 Code desktop, mobile, and hosted web applications, visit the t3.codes marketing site, or use the optional T3 Connect service."
effectiveDate="2026-07-14"
lastUpdated="2026-07-14"
sections={sections}
>
<section id="introduction">
<p class="section-number">01</p>
<h2>Introduction</h2>
<p>
This Privacy Policy (the “Policy”) describes how T3 Tools, Inc. (the “Company,” “T3
Tools,” “we,” or “us”) collects, uses, and shares personal information when you use the T3
Code desktop and mobile applications, the hosted T3 Code web application located at
{" "}<a href="https://app.t3.codes">https://app.t3.codes</a>, or the optional T3 Connect
service (together, the “Services”), or visit the T3 Code marketing website located at
{" "}<a href="https://t3.codes">https://t3.codes</a> (the “Site”). This Policy applies to
personal information we collect through the Site and the Services, as well as personal
information you provide to us directly.
</p>
<p>
By using the Site or the Services, you acknowledge the practices described in this
Policy. If you do not agree with this Policy, please do not use the Site or the Services.
This Policy does not govern third-party coding agents, artificial-intelligence providers,
identity providers, or environments that you choose to connect to T3 Code; those third
parties process information under their own terms and privacy policies.
</p>
</section>
<section id="information">
<p class="section-number">02</p>
<h2>Personal Information We Collect</h2>
<p>
We collect personal information about you in different ways depending on how you use
T3 Code and which optional features you enable.
</p>
<h3>Personal Information From Users of T3 Code</h3>
<p>
When you use T3 Code, we may collect the following categories of personal information:
</p>
<ul>
<li>
<strong>Account information.</strong> If you create or sign in to a T3 account, we
receive general identifiers and profile information from our authentication provider
and the identity provider you select. This may include your name, email address,
profile image, user ID, sign-in method, and authentication credentials or tokens.
</li>
<li>
<strong>Environment and device information.</strong> If you enable T3 Connect, we
process information needed to connect and secure your environments and devices,
including identifiers, labels you assign, public keys, connection endpoints,
credential hashes, connection status, app and operating-system versions, and
notification preferences.
</li>
<li>
<strong>Agent activity and notifications.</strong> If you enable notifications or Live
Activities, we process push tokens and limited activity information needed to provide
those features, such as project and thread titles, model name, status, and activity
headline.
</li>
<li>
<strong>Information you provide to us.</strong> We collect information that you choose
to provide when you request support, send feedback, or otherwise communicate with us.
</li>
</ul>
<h3>Personal Information From Users of Our Site Generally</h3>
<p>
When you visit the Site or use online portions of the Services, we and our service
providers may automatically log online identifiers and internet-activity information,
including your Internet Protocol (IP) address, device and operating-system type, browser
or app type and version, pages viewed, access times, request timestamps, connection
events, latency, error details, and diagnostic traces. The amount of information we
collect depends on the Services you use and your device and browser settings.
</p>
<p>
We use operational and diagnostic information to provide, secure, maintain, and
troubleshoot the Services, not for targeted advertising.
</p>
<h3>Information We Get From Others</h3>
<p>
We may receive personal information from service providers that help us operate the
Services, such as authentication and identity providers, app stores, device-platform
providers, and coding-agent providers you choose to use. We may combine this information
with information we collect through the Site and the Services.
</p>
<h3>Cookies and Local Storage</h3>
<p>
The Site and online portions of the Services may use cookies or similar technologies to
operate essential features, maintain sessions, remember preferences, and understand
whether the Services are functioning correctly. T3 Code also stores connection settings,
credentials, preferences, drafts, and cached thread, file, branch, and server metadata on
your device. Credentials and session tokens use platform-provided protected storage where
supported. Information stored only on your device is not collected by T3 Tools unless it
is transmitted as part of a feature you use.
</p>
<h3>Device Permissions</h3>
<ul>
<li>
<strong>Camera.</strong> Used when you choose to scan a pairing QR code. Camera frames
are processed on your device.
</li>
<li>
<strong>Photos and files.</strong> Items you select are accessed only to preview them or
attach them to a request you initiate.
</li>
<li>
<strong>Notifications.</strong> Used only if you enable agent-status notifications or
Live Activities.
</li>
<li>
<strong>Local network.</strong> Used to discover or connect to T3 Code environments
accessible from your machine over the network.
</li>
</ul>
</section>
<section id="uses">
<p class="section-number">03</p>
<h2>How We Use Your Personal Information</h2>
<p>
Subject to this Policy and applicable terms governing third-party applications and
services, we may use personal information for the following purposes:
</p>
<ul>
<li>To establish and verify your identity and authenticate your account;</li>
<li>To link and protect devices and environments and deliver optional notifications;</li>
<li>To process and fulfill requests you make through the Services;</li>
<li>To provide customer service and respond to support requests and feedback;</li>
<li>To communicate with you about the Services and your relationship with us;</li>
<li>To monitor reliability, prevent abuse, and investigate security incidents;</li>
<li>To comply with applicable law and enforce the terms governing the Services; and</li>
<li>
To analyze and improve T3 Code using aggregated, de-identified, or other anonymous
operational information.
</li>
</ul>
<h3>Training of AI Models</h3>
<p>
We do not use your personal information, source code, prompts, or agent responses to
train artificial-intelligence models.
</p>
<h3>Compliance and Protection</h3>
<p>We may use personal information to:</p>
<ul>
<li>Comply with applicable laws, lawful requests, and legal process;</li>
<li>Protect the rights, privacy, safety, and property of T3 Tools, our users, and others;</li>
<li>Audit our internal processes for legal, contractual, and policy compliance;</li>
<li>Enforce the terms and conditions that govern the Site and the Services; and</li>
<li>
Prevent, identify, investigate, and deter fraudulent, harmful, unauthorized,
unethical, or illegal activity, including cyberattacks and identity theft.
</li>
</ul>
<p>
We may also use personal information for other purposes consistent with this Policy or
explained to you when we collect the information.
</p>
</section>
<section id="sharing">
<p class="section-number">04</p>
<h2>How We Share Your Personal Information</h2>
<p>
We may disclose the categories of personal information described above to the following
categories of third parties:
</p>
<h3>Providers You Choose</h3>
<p>
At your direction, prompts, files, and related content are sent to coding agents and
artificial-intelligence providers configured in your environment. Because you bring and
configure your own coding-agent harness and provider, the applicable third parties vary.
Those providers process information under their own terms and privacy policies.
</p>
<h3>Third-Party Service Providers</h3>
<p>
We use third-party service providers to help provide the Services and operate our
business. Depending on the features you use, these providers may include:
</p>
<ul class="provider-list">
<li>
<strong>Clerk</strong> <em>(Clerk, Inc.)</em>.<br />
We use Clerk to provide account authentication.<br />
You can view Clerk's privacy policy here:{" "}<a href="https://clerk.com/legal/privacy"
>https://clerk.com/legal/privacy</a
>.
</li>
<li>
<strong>Cloudflare</strong> <em>(Cloudflare, Inc.)</em>.<br />
We use Cloudflare for networking, T3 Connect infrastructure, and content delivery.<br />
You can view Cloudflare's privacy policy here:{" "}<a
href="https://www.cloudflare.com/policies/privacy/"
>https://www.cloudflare.com/policies/privacy/</a
>.
</li>
<li>
<strong>PlanetScale</strong> <em>(PlanetScale, Inc.)</em>.<br />
We use PlanetScale to host the database that supports T3 Connect.<br />
You can view PlanetScale's privacy policy here:{" "}<a
href="https://planetscale.com/legal/privacy"
>https://planetscale.com/legal/privacy</a
>.
</li>
<li>
<strong>Vercel</strong> <em>(Vercel Inc.)</em>.<br />
We use Vercel to host and deploy the T3 Code Site.<br />
You can view Vercel's privacy notice here:{" "}<a
href="https://vercel.com/legal/privacy-notice"
>https://vercel.com/legal/privacy-notice</a
>.
</li>
<li>
<strong>Axiom</strong> <em>(Axiom, Inc.)</em>.<br />
We use Axiom for operational diagnostics that help us maintain and troubleshoot the
Services.<br />
You can view Axiom's privacy policy here:{" "}<a
href="https://axiom.co/docs/legal/privacy">https://axiom.co/docs/legal/privacy</a
>.
</li>
<li>
<strong>Expo</strong> <em>(650 Industries, Inc.)</em>.<br />
We use Expo for application updates and related mobile-app services.<br />
You can view Expo's privacy policy here:{" "}<a href="https://expo.dev/privacy"
>https://expo.dev/privacy</a
>.
</li>
<li>
<strong>Apple</strong> <em>(Apple Inc.)</em>.<br />
We use Apple services for app distribution, optional authentication, and platform
notifications.<br />
You can view Apple's privacy policy here:{" "}<a
href="https://www.apple.com/legal/privacy/">https://www.apple.com/legal/privacy/</a
>.
</li>
<li>
<strong>Google</strong> <em>(Google LLC)</em>.<br />
We use Google services for app distribution and optional authentication.<br />
You can view Google's privacy policy here:{" "}<a
href="https://policies.google.com/privacy">https://policies.google.com/privacy</a
>.
</li>
</ul>
<p>
These providers process information for us under their own contractual and privacy
obligations.
</p>
<h3>Affiliates and Professional Advisors</h3>
<p>
We may share personal information with our affiliates for purposes consistent with this
Policy and with lawyers, accountants, bankers, and other professional advisors in the
course of the services they provide to us.
</p>
<h3>Corporate Restructuring</h3>
<p>
We may share some or all personal information in connection with or during negotiation of
a merger, financing, acquisition, reorganization, bankruptcy, dissolution, sale of
assets, or similar transaction. If another company acquires T3 Tools or its assets, that
company may possess the personal information collected by us and assume the rights and
obligations described in this Policy.
</p>
<h3>Legal and Safety Disclosures</h3>
<p>
We may disclose personal information if we believe in good faith that disclosure is
necessary to comply with law or legal process; protect or defend the rights, property, or
safety of T3 Tools, users of the Site or the Services, or others; investigate or prevent
fraud, abuse, or unlawful activity; or enforce this Policy and the terms governing the
Services. We may also share personal information at your direction, with your consent, or
as described to you when the information is collected.
</p>
<h3>No Sale of Personal Information</h3>
<p>
We do not sell your personal information or share it for cross-context behavioral or
targeted advertising.
</p>
<h3>Third-Party Websites and Services</h3>
<p>
The Site and the Services may contain links to third-party websites or services. When you
follow a third-party link or connect a third-party service, that third party may collect
personal information from you. We do not control and are not responsible for the privacy
practices or content of third parties.
</p>
</section>
<section id="choices">
<p class="section-number">05</p>
<h2>Your Choices Regarding Your Personal Information</h2>
<h3>Account and Connection Choices</h3>
<p>
You may use local or direct connections without signing in to a T3 account. You can
disconnect environments, sign out, disable optional notifications and Live Activities,
and clear local caches from Settings. You can grant or revoke camera, photo, local-network,
and notification permissions in your device settings.
</p>
<h3>Cookies and Local Data</h3>
<p>
You can use your browser settings to stop accepting or to delete cookies, although some
portions of the Site or the Services may not function correctly as a result. Information
stored only on your device remains there until you clear it, remove the relevant
connection, or uninstall the app. The mobile app provides cache controls under
{" "}<strong>Settings → App → Client Storage</strong>.
</p>
<h3>Retention and Deletion</h3>
<p>
We retain account, environment-link, device-registration, notification, and security
information while your account or the relevant feature is active and for as long as
reasonably necessary to provide the Services, protect them from abuse, comply with law,
and resolve disputes. Operational diagnostic traces are configured to expire after 30
days. Some records may remain longer in backups or where retention is required for
security, fraud prevention, or legal compliance.
</p>
<p>
To request deletion of your T3 account and associated T3 Connect data, email{" "}<a
href="mailto:[email protected]">[email protected]</a
>{" "}from the email address associated with your account. We may need to verify your
identity. Deleting a T3 account does not delete information held by an environment or
coding-agent provider you control; contact those providers or delete that information
directly.
</p>
<h3>Your Privacy Rights</h3>
<p>
Depending on where you live, you may have rights to request access to, correction of,
deletion of, or a portable copy of your personal information, or to restrict or object
to certain processing. You may also have the right to appeal our response or complain to
a data-protection authority. We will honor applicable rights after verifying your
request.
</p>
</section>
<section id="security">
<p class="section-number">06</p>
<h2>Security of Your Personal Information</h2>
<p>
T3 Tools is committed to protecting the security of your personal information. We use
administrative, technical, and organizational safeguards designed to protect personal
information from unauthorized access, use, or disclosure. These safeguards include
encrypted network transport, scoped and proof-bound access tokens for supported
connection flows, protected credential storage, and redaction of authorization headers
from relay diagnostics.
</p>
<p>
No method of transmission over the Internet or method of electronic storage is completely
secure. While we use reasonable efforts to protect personal information, we cannot
guarantee its absolute security. You are responsible for securing the environments,
coding-agent accounts, credentials, and networks that you connect to T3 Code.
</p>
</section>
<section id="international">
<p class="section-number">07</p>
<h2>International Users</h2>
<p>
The Site and the Services are provided from the United States and are governed by United
States law. If you use the Site or the Services from outside the United States, your
personal information may be transferred to and processed in the United States and other
countries where we or our service providers operate. Where required, we use lawful
safeguards for international transfers of personal information.
</p>
</section>
<section id="children">
<p class="section-number">08</p>
<h2>Children</h2>
<p>
The Site and the Services are not intended for children under 13 years of age, and you
must be at least 13 years old to use them. We do not knowingly collect, use, or disclose
personal information from children under 13. If you believe a child under 13 has provided
us with personal information, please contact us so that we can take appropriate action.
</p>
</section>
<section id="do-not-track">
<p class="section-number">09</p>
<h2>Do Not Track</h2>
<p>
We currently do not respond to browser “Do Not Track” signals. T3 Code does not use
personal information for cross-context behavioral or targeted advertising.
</p>
</section>
<section id="updates">
<p class="section-number">10</p>
<h2>Updates to This Privacy Policy</h2>
<p>
We reserve the right to update this Policy from time to time. If we make material changes,
we will post the revised Policy at this URL, update the “Last Updated” and “Effective Date”
above, and provide any additional notice required by law. Except as otherwise indicated,
changes become effective when the revised Policy is posted.
</p>
</section>
<section id="contact">
<p class="section-number">11</p>
<h2>Contact Us</h2>
<p>
If you have questions about this Policy or wish to make a privacy or deletion request,
please contact us at:
</p>
<address>
<strong>T3 Tools, Inc.</strong><br />
2261 Market Street #5309<br />
San Francisco, CA 94114<br />
United States
</address>
<a class="contact-link" href="mailto:[email protected]">[email protected]</a>
</section>
</LegalPage>
@@ -0,0 +1,187 @@
---
import LegalPage from "../components/LegalPage.astro";
const sections = [
["introduction", "Introduction"],
["reporting", "Reporting security issues"],
["safe-harbor", "Responsible research and safe harbor"],
["practices", "Our security practices"],
["responsibilities", "Your responsibilities"],
["updates", "Updates to this policy"],
["contact", "Contact us"],
] as const;
---
<LegalPage
title="Security Policy — T3 Code"
description="How to report security issues in T3 Code and how T3 Tools approaches product security."
heading="T3 Code Security Policy"
lede="Security is a shared responsibility. This policy explains how to report a vulnerability, how we protect T3 Tools-operated services, and how you can secure the environments and providers you connect to T3 Code."
effectiveDate="2026-07-15"
lastUpdated="2026-07-15"
sections={sections}
>
<section id="introduction">
<p class="section-number">01</p>
<h2>Introduction</h2>
<p>
This Security Policy describes the vulnerability-reporting process and security practices for
the T3 Code desktop and mobile applications, the hosted application at{" "}<a
href="https://app.t3.codes">https://app.t3.codes</a
>, the optional T3 Connect service, and the T3 Code website at{" "}<a href="https://t3.codes"
>https://t3.codes</a
>.
</p>
<p>
T3 Code connects software running on your devices and in environments you control with
coding-agent harnesses and providers you choose. We secure the software and infrastructure
operated by T3 Tools, but we do not control the security of your devices, environments,
repositories, networks, credentials, or third-party providers. Please review the shared
responsibilities below when assessing risk.
</p>
</section>
<section id="reporting">
<p class="section-number">02</p>
<h2>Reporting Security Issues</h2>
<p>
If you believe you have found a security vulnerability affecting T3 Code or T3 Tools-operated
infrastructure, email{" "}<a href="mailto:[email protected]">[email protected]</a>. Please do not
disclose the issue publicly until we have had a reasonable opportunity to investigate and
remediate it.
</p>
<p>Please include, when available:</p>
<ul>
<li>A description of the issue and its potential impact;</li>
<li>The affected application, version, URL, endpoint, or component;</li>
<li>Clear reproduction steps or a minimal proof of concept;</li>
<li>Relevant logs, screenshots, or request and response details with secrets removed; and</li>
<li>Your preferred contact information and whether you want public credit.</li>
</ul>
<p>
We aim to acknowledge complete reports within one business day, keep reporters informed of
material progress, and coordinate disclosure after a fix is available. Resolution time varies
with severity, complexity, and dependencies on third parties.
</p>
</section>
<section id="safe-harbor">
<p class="section-number">03</p>
<h2>Responsible Research and Safe Harbor</h2>
<p>
We support good-faith security research. If you make a genuine effort to comply with this
policy, avoid harm, respect privacy, and report findings promptly, we will treat your research
as authorized and will not initiate legal action against you for accidental, good-faith
violations of this policy. If a third party initiates legal action concerning compliant
research, we will make our authorization known where appropriate.
</p>
<p>To remain within this safe harbor, you must:</p>
<ul>
<li>Test only accounts, data, and systems you own or have explicit permission to test;</li>
<li>Stop and report immediately if you encounter personal, confidential, or production data;</li>
<li>Access only the minimum information needed to demonstrate the issue;</li>
<li>Avoid disrupting availability, degrading performance, or damaging or deleting data;</li>
<li>Not use social engineering, phishing, physical attacks, or denial-of-service testing;</li>
<li>Not test third-party services or infrastructure outside T3 Tools’ control; and</li>
<li>Give us reasonable time to address the issue before public disclosure.</li>
</ul>
<p>
This safe harbor does not authorize violations of law or activity outside the scope of this
policy. Vulnerability rewards are not guaranteed and, if offered, are determined by T3 Tools
in its discretion.
</p>
</section>
<section id="practices">
<p class="section-number">04</p>
<h2>Our Security Practices</h2>
<p>
We use administrative, technical, and organizational safeguards designed for the nature of T3
Code and the information processed by T3 Tools-operated services. These practices include:
</p>
<ul>
<li>
<strong>Data minimization.</strong> T3 Code is designed so coding-session content can remain
between your clients, your environment, and the harnesses and providers you configure. We
process information through T3 Tools-operated infrastructure only when needed for a feature
you enable.
</li>
<li>
<strong>Encrypted transport.</strong> T3 Tools-operated network services use encrypted
transport. Supported connection flows use scoped credentials and security controls designed
to reduce unauthorized reuse.
</li>
<li>
<strong>Credential protection.</strong> T3 Code uses platform-provided protected storage for
credentials and session tokens where supported. We design operational logging to avoid
collecting secrets that are not needed to operate or troubleshoot the Services.
</li>
<li>
<strong>Access controls.</strong> Access to production systems and operational data is limited
according to job responsibilities and protected using authentication and authorization
controls.
</li>
<li>
<strong>Maintenance and monitoring.</strong> We monitor T3 Tools-operated services for
reliability and security events, review dependencies, and deploy updates and mitigations as
appropriate.
</li>
<li>
<strong>Established providers.</strong> We use specialized providers for services such as
authentication, hosting, and application distribution and evaluate the controls relevant to
their role.
</li>
</ul>
<p>
No system is completely secure. These practices reduce risk but do not guarantee that the Site
or Services will be free from vulnerabilities or unauthorized access.
</p>
</section>
<section id="responsibilities">
<p class="section-number">05</p>
<h2>Your Responsibilities</h2>
<p>
Because you control much of the T3 Code execution path, you play an important role in securing
it. You are responsible for:
</p>
<ul>
<li>Keeping T3 Code, your operating systems, and connected tools up to date;</li>
<li>Securing your devices, repositories, environments, networks, and backups;</li>
<li>Protecting account, provider, repository, and environment credentials;</li>
<li>Using multi-factor authentication where your identity and coding-agent providers support it;</li>
<li>Granting providers and integrations only the permissions they need;</li>
<li>Reviewing commands, source changes, and other agent output before applying or executing it;</li>
<li>Removing lost or unused devices and revoking credentials you believe may be compromised; and</li>
<li>Following the security policies of your selected harnesses, providers, and infrastructure.</li>
</ul>
<p>
Do not send passwords, API keys, access tokens, or private keys in a vulnerability report.
Revoke any secret that may have been exposed before sharing sanitized evidence with us.
</p>
</section>
<section id="updates">
<p class="section-number">06</p>
<h2>Updates to This Policy</h2>
<p>
We may update this Security Policy as T3 Code, our infrastructure, and security practices
evolve. We will post revisions at this URL and update the dates above. Material changes to the
vulnerability-reporting process or safe-harbor terms will apply prospectively.
</p>
</section>
<section id="contact">
<p class="section-number">07</p>
<h2>Contact Us</h2>
<p>
Report security issues or ask security-related questions at{" "}<a
href="mailto:[email protected]">[email protected]</a
>.
</p>
<p>
For general legal questions, contact{" "}<a href="mailto:[email protected]">[email protected]</a>.
For privacy requests, contact{" "}<a href="mailto:[email protected]">[email protected]</a>.
</p>
</section>
</LegalPage>
@@ -0,0 +1,396 @@
---
import LegalPage from "../components/LegalPage.astro";
const sections = [
["introduction", "Introduction"],
["accounts", "Accounts"],
["content", "Your content and providers"],
["rights", "T3 Code and proprietary rights"],
["acceptable-use", "Acceptable use"],
["availability", "Availability and changes"],
["fees", "Fees"],
["privacy", "Privacy"],
["termination", "Suspension and termination"],
["beta", "Beta services"],
["disclaimers", "Disclaimers"],
["liability", "Limitation of liability"],
["indemnification", "Indemnification"],
["copyright", "Copyright complaints"],
["third-parties", "Third-party services"],
["feedback", "Feedback"],
["disputes", "Dispute resolution"],
["miscellaneous", "Miscellaneous"],
["changes", "Changes to these Terms"],
["contact", "Contact us"],
] as const;
---
<LegalPage
title="Terms of Service — T3 Code"
description="The terms that govern your use of T3 Code, app.t3.codes, T3 Connect, and t3.codes."
heading="T3 Code Terms of Service"
lede="These Terms govern your use of T3 Code, including its desktop, mobile, and hosted applications, the optional T3 Connect service, and the t3.codes website."
effectiveDate="2026-07-15"
lastUpdated="2026-07-15"
sections={sections}
>
<section id="introduction">
<p class="section-number">01</p>
<h2>Introduction</h2>
<p>
These Terms of Service (the “Terms”) are a binding agreement between you and T3 Tools, Inc.
(“T3 Tools,” “we,” “us,” or “our”). They govern your access to and use of the T3 Code desktop
and mobile applications, the hosted T3 Code application at{" "}<a href="https://app.t3.codes"
>https://app.t3.codes</a
>, and the optional T3 Connect service (together, the “Services”), as well as the T3 Code
marketing website at{" "}<a href="https://t3.codes">https://t3.codes</a> (the “Site”).
</p>
<p>
By accessing or using the Site or Services, you agree to these Terms. If you use the Services
for an organization, you represent that you have authority to bind that organization, and
“you” includes the organization. If you do not agree to these Terms, do not use the Site or
Services.
</p>
<p>
You must be at least 13 years old to use the Site or Services. If the law where you live
requires a greater age to enter into these Terms, you must meet that requirement or have a
parent or legal guardian agree on your behalf.
</p>
</section>
<section id="accounts">
<p class="section-number">02</p>
<h2>Accounts</h2>
<p>
You can use some T3 Code features without creating a T3 account. An account may be required
for account-backed features, including T3 Connect. You agree to provide accurate account
information, keep your credentials secure, and promptly notify us if you suspect unauthorized
access. You are responsible for activity performed through your account and connected devices,
except to the extent caused by our failure to use reasonable security measures.
</p>
<p>
You may not share credentials in a way that compromises the Services, impersonate another
person, or create accounts through unauthorized automated means. We may require reasonable
verification before restoring access or acting on an account request.
</p>
</section>
<section id="content">
<p class="section-number">03</p>
<h2>Your Content and Providers</h2>
<p>
T3 Code can help you send prompts, source files, images, attachments, review comments, and
instructions to coding-agent harnesses and providers you choose, and display their responses,
command output, file changes, source code, and diffs (collectively, “User Content”). You retain
all rights you have in your User Content.
</p>
<p>
You bring and configure your own coding-agent harness and provider. Your User Content is
ordinarily processed in the environment you control and by the providers you select, not by
T3 Tools. When you enable a T3 Tools-operated feature that must transmit or process User
Content, you grant us a limited, non-exclusive license to host, transmit, reproduce, and
process that content only as reasonably necessary to provide, secure, and troubleshoot that
feature. This license ends when the content is no longer needed for those purposes, subject to
reasonable backup, security, and legal-retention requirements.
</p>
<p>
You represent that you have the rights and permissions needed to use and submit User Content
and to direct its processing by your selected harnesses and providers. You are responsible for
reviewing those providers’ terms, privacy practices, data controls, and output before using
them with confidential, proprietary, regulated, or personal information.
</p>
</section>
<section id="rights">
<p class="section-number">04</p>
<h2>T3 Code and Proprietary Rights</h2>
<p>
T3 Tools and its licensors own the Site, the Services, and their branding, designs, hosted
infrastructure, documentation, and other materials, excluding User Content and third-party
materials. These Terms do not transfer ownership of either party’s intellectual property.
</p>
<p>
Portions of T3 Code are available as open-source software. Your use, copying, modification, and
distribution of that source code are governed by the license included with the applicable
repository or component. These Terms govern your use of the hosted Services and do not limit
rights granted to you by an applicable open-source license.
</p>
<p>
Subject to these Terms, we grant you a limited, non-exclusive, non-transferable, revocable right
to access and use the Services for lawful personal or internal business purposes. You may not
use our trademarks, service marks, or trade dress without written permission.
</p>
</section>
<section id="acceptable-use">
<p class="section-number">05</p>
<h2>Acceptable Use</h2>
<p>You may not use the Site or Services to:</p>
<ul>
<li>Violate applicable law or another person’s rights;</li>
<li>Upload, transmit, or generate content you do not have the right to use;</li>
<li>Distribute malware, exploit code, or harmful content except in authorized security work;</li>
<li>Probe, attack, disrupt, or gain unauthorized access to the Services or another system;</li>
<li>Bypass rate limits, access controls, security measures, or usage restrictions;</li>
<li>Interfere with other users or place an unreasonable load on shared infrastructure;</li>
<li>Use the Services to facilitate fraud, harassment, abuse, or deceptive conduct; or</li>
<li>Misrepresent that output or activity from a third-party agent was produced or endorsed by us.</li>
</ul>
<p>
Authorized security research must follow our{" "}<a href="/security-policy">Security Policy</a>.
We may investigate suspected violations and take proportionate action to protect users and the
Services.
</p>
</section>
<section id="availability">
<p class="section-number">06</p>
<h2>Availability and Changes</h2>
<p>
We may add, change, suspend, or discontinue features, integrations, or supported platforms. We
aim to provide reasonable notice when a change materially reduces an account-backed feature,
but urgent security, legal, or reliability changes may take effect immediately. The Services
may be unavailable because of maintenance, provider outages, network conditions, or events
outside our control.
</p>
<p>
T3 Code depends on software, environments, networks, and coding-agent providers that you
configure or that third parties operate. We do not control their availability, compatibility,
pricing, or behavior.
</p>
</section>
<section id="fees">
<p class="section-number">07</p>
<h2>Fees</h2>
<p>
T3 Code is currently offered without a T3 Tools subscription fee unless we clearly state
otherwise for a feature. You remain responsible for charges from your coding-agent providers,
cloud infrastructure, network operators, app stores, and other third parties. If we introduce
a paid feature, we will present its price and applicable payment terms before you purchase it.
</p>
</section>
<section id="privacy">
<p class="section-number">08</p>
<h2>Privacy</h2>
<p>
Our{" "}<a href="/privacy-policy">Privacy Policy</a> explains how T3 Tools collects, uses, and
shares personal information when you use the Site and Services. Third-party environments,
harnesses, identity providers, and coding-agent providers process information under their own
terms and privacy policies.
</p>
</section>
<section id="termination">
<p class="section-number">09</p>
<h2>Suspension and Termination</h2>
<p>
You may stop using the Services at any time. You may disconnect environments and devices from
within T3 Code and may request deletion of an account as described in our Privacy Policy.
</p>
<p>
We may suspend or terminate access to account-backed or hosted features if we reasonably
believe you materially violated these Terms, created a security or legal risk, failed to pay an
applicable fee, or used the Services in a way that could harm other users or shared
infrastructure. When practicable, we will give notice and an opportunity to cure. We may act
immediately where needed to prevent harm or comply with law.
</p>
<p>
Provisions that by their nature should survive termination—including ownership, disclaimers,
limitations of liability, indemnification, and dispute terms—will survive.
</p>
</section>
<section id="beta">
<p class="section-number">10</p>
<h2>Beta Services</h2>
<p>
T3 Code is an early-stage product, and some or all features may be identified as alpha, beta,
preview, experimental, or pre-release (“Beta Services”). Beta Services may be incomplete,
change without notice, contain errors, or lose data. Do not rely on Beta Services as the sole
copy of important work, and review proposed commands and file changes before applying them.
</p>
</section>
<section id="disclaimers">
<p class="section-number">11</p>
<h2>Disclaimers</h2>
<p class="legal-notice">
TO THE MAXIMUM EXTENT PERMITTED BY LAW, THE SITE AND SERVICES ARE PROVIDED “AS IS” AND “AS
AVAILABLE,” WITHOUT WARRANTIES OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE, AND NON-INFRINGEMENT.
</p>
<p>
Coding agents and artificial-intelligence systems can produce incorrect, insecure, incomplete,
or harmful output. You are responsible for reviewing output, commands, patches, and other
actions before relying on or executing them. We do not warrant that the Services or third-party
output will be uninterrupted, secure, accurate, error-free, or suitable for your purpose.
</p>
<p>
Some jurisdictions do not allow certain warranty exclusions, so some of the foregoing may not
apply to you.
</p>
</section>
<section id="liability">
<p class="section-number">12</p>
<h2>Limitation of Liability</h2>
<p class="legal-notice">
TO THE MAXIMUM EXTENT PERMITTED BY LAW, T3 TOOLS AND ITS AFFILIATES, OFFICERS, EMPLOYEES,
AGENTS, AND LICENSORS WILL NOT BE LIABLE FOR INDIRECT, INCIDENTAL, SPECIAL, CONSEQUENTIAL,
EXEMPLARY, OR PUNITIVE DAMAGES, OR FOR LOST PROFITS, REVENUE, DATA, GOODWILL, OR BUSINESS
OPPORTUNITIES, ARISING FROM OR RELATED TO THE SITE, SERVICES, OR THESE TERMS.
</p>
<p>
To the maximum extent permitted by law, our aggregate liability for all claims arising from or
relating to the Site, Services, or these Terms will not exceed the greater of $100 or the amount
you paid directly to T3 Tools for the Services during the 12 months before the event giving rise
to the claim. These limitations apply regardless of the legal theory and even if a remedy fails
of its essential purpose. They do not limit liability that cannot lawfully be limited.
</p>
</section>
<section id="indemnification">
<p class="section-number">13</p>
<h2>Indemnification</h2>
<p>
To the extent permitted by law, you will defend, indemnify, and hold harmless T3 Tools and its
affiliates, officers, employees, and agents from third-party claims, damages, losses, and
reasonable legal fees arising from your User Content, your use of the Site or Services in
violation of these Terms or law, or your infringement of another person’s rights. We will
promptly notify you of a covered claim and reasonably cooperate in its defense. You may not
settle a claim in a way that admits fault by or imposes obligations on us without our written
consent.
</p>
</section>
<section id="copyright">
<p class="section-number">14</p>
<h2>Copyright Complaints</h2>
<p>
If you believe material available through a T3 Tools-operated part of the Site or Services
infringes your copyright, send a notice to{" "}<a href="mailto:[email protected]">[email protected]</a
>{" "}identifying the copyrighted work, the allegedly infringing material and its location, your
contact information, a statement of good-faith belief, a statement under penalty of perjury
that the notice is accurate and you are authorized to act, and your physical or electronic
signature.
</p>
<p>
T3 Tools does not control content stored only in a user’s environment or held by a user-selected
provider. Requests concerning that material should be directed to the operator that hosts it.
</p>
</section>
<section id="third-parties">
<p class="section-number">15</p>
<h2>Third-Party Services</h2>
<p>
The Services may connect to or display content from third-party coding agents, model providers,
identity providers, repositories, app stores, websites, and infrastructure. Your use of those
services is governed by their terms. We do not endorse or control third-party services and are
not responsible for their content, security, availability, output, or data practices.
</p>
<p>
Third-party and open-source software included with T3 Code is governed by its applicable
license notices. Where those licenses conflict with these Terms for that software, the
applicable open-source license controls.
</p>
</section>
<section id="feedback">
<p class="section-number">16</p>
<h2>Feedback</h2>
<p>
If you send us ideas, suggestions, or other feedback about T3 Code, you grant T3 Tools a
perpetual, irrevocable, worldwide, royalty-free right to use and commercialize that feedback
without restriction or compensation. This does not transfer ownership of your User Content.
</p>
</section>
<section id="disputes">
<p class="section-number">17</p>
<h2>Dispute Resolution</h2>
<p class="legal-notice">
PLEASE READ THIS SECTION CAREFULLY. IT REQUIRES MOST DISPUTES TO BE RESOLVED BY INDIVIDUAL
BINDING ARBITRATION AND WAIVES JURY TRIALS AND CLASS OR REPRESENTATIVE ACTIONS.
</p>
<h3>Informal Resolution</h3>
<p>
Before starting arbitration or a court proceeding, the party raising a dispute must send a
written notice describing the dispute and requested relief. Notices to us must be sent to{" "}<a
href="mailto:[email protected]">[email protected]</a
>. The parties will try in good faith to resolve the dispute for at least 30 days.
</p>
<h3>Binding Arbitration</h3>
<p>
Except for disputes eligible for small-claims court and requests for injunctive relief to
protect intellectual property or prevent unauthorized access, unresolved disputes will be
resolved by binding individual arbitration administered by JAMS under its applicable consumer
or comprehensive rules. The Federal Arbitration Act governs this agreement. Arbitration may
take place remotely unless the arbitrator determines that an in-person hearing is necessary.
</p>
<h3>No Class Actions</h3>
<p>
Disputes must be brought only on an individual basis. Neither party may participate in a class,
collective, consolidated, or representative action or arbitration to the extent permitted by
law.
</p>
<h3>Opt Out</h3>
<p>
You may opt out of this arbitration agreement by emailing{" "}<a href="mailto:[email protected]"
>[email protected]</a
> within 30 days after you first accept these Terms. Include your name, the email associated
with your account if any, and a clear statement that you opt out of arbitration.
</p>
<p>
If the arbitration agreement does not apply, exclusive jurisdiction and venue will lie in the
state and federal courts located in San Francisco County, California, and each party consents
to those courts.
</p>
</section>
<section id="miscellaneous">
<p class="section-number">18</p>
<h2>Miscellaneous</h2>
<p>
California law governs these Terms without regard to conflict-of-law principles, except that
the Federal Arbitration Act governs the arbitration provisions. These Terms and documents
incorporated by reference are the entire agreement between you and us regarding the Site and
Services. If a provision is unenforceable, it will be modified to the minimum extent necessary
or severed, and the remaining provisions will continue in effect.
</p>
<p>
Our failure to enforce a provision is not a waiver. You may not assign these Terms without our
written consent. We may assign them in connection with a merger, acquisition, reorganization,
or sale of assets. We are not liable for delays or failures caused by events beyond our
reasonable control. Headings are for convenience only, and “including” means “including without
limitation.”
</p>
</section>
<section id="changes">
<p class="section-number">19</p>
<h2>Changes to These Terms</h2>
<p>
We may update these Terms from time to time. We will post updated Terms at this URL and update
the dates above. If a change materially affects your rights, we will provide additional notice
when reasonably practicable or as required by law. Changes apply prospectively from their
effective date. Your continued use of the Site or Services after that date means you accept the
updated Terms.
</p>
</section>
<section id="contact">
<p class="section-number">20</p>
<h2>Contact Us</h2>
<p>If you have questions about these Terms, contact us at:</p>
<address>
<strong>T3 Tools, Inc.</strong><br />
2261 Market Street #5309<br />
San Francisco, CA 94114<br />
United States
</address>
<a class="contact-link" href="mailto:[email protected]">[email protected]</a>
</section>
</LegalPage>
+24
View File
@@ -34,6 +34,30 @@ Build and run the local iOS dev client:
vp run ios:dev
```
If your Xcode account only has a Personal Team, use a bundle identifier you control and opt into the
reduced-capability local build. Personal Team builds omit the widget extension, push entitlement, and
native Sign in with Apple entitlement; builds without this opt-in are unchanged.
```bash
T3CODE_IOS_PERSONAL_TEAM=1 \
T3CODE_IOS_PERSONAL_TEAM_BUNDLE_ID=com.example.t3code.dev \
vp run ios:dev
```
Build and install a self-contained Release app that does not need Metro:
```bash
vp run ios:release
```
The Personal Team equivalent also needs a unique bundle identifier:
```bash
T3CODE_IOS_PERSONAL_TEAM=1 \
T3CODE_IOS_PERSONAL_TEAM_BUNDLE_ID=com.example.t3code \
vp run ios:release
```
Build and run the local iOS preview app:
```bash
+142 -52
View File
@@ -8,47 +8,69 @@ const repoEnv = loadRepoEnv();
Object.assign(process.env, repoEnv);
const APP_VARIANT = resolveAppVariant(repoEnv.APP_VARIANT);
const isIosPersonalTeamBuild = repoEnv.T3CODE_IOS_PERSONAL_TEAM === "1";
const VARIANT_CONFIG: Record<
AppVariant,
{
readonly appName: string;
readonly scheme: string;
readonly iosIcon: string;
readonly splashIcon: string;
readonly iosBundleIdentifier: string;
readonly androidPackage: string;
readonly relyingParty?: string;
}
> = {
const personalTeamBundleIdentifier = repoEnv.T3CODE_IOS_PERSONAL_TEAM_BUNDLE_ID?.trim();
const IOS_BUNDLE_IDENTIFIER_PATTERN = /^[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)+$/;
if (
isIosPersonalTeamBuild &&
(!personalTeamBundleIdentifier ||
!IOS_BUNDLE_IDENTIFIER_PATTERN.test(personalTeamBundleIdentifier))
) {
throw new Error(
"T3CODE_IOS_PERSONAL_TEAM_BUNDLE_ID must be a reverse-DNS identifier such as com.example.t3code when T3CODE_IOS_PERSONAL_TEAM=1.",
);
}
const DEVELOPMENT_ASSETS = {
appIcon: "./assets/splash-icon-dev.png",
iosIcon: "./assets/icon-composer-dev.icon",
splashIcon: "./assets/splash-icon-dev.png",
androidAdaptiveForeground: "./assets/android-icon-dev-foreground.png",
androidAdaptiveBackgroundColor: "#00639B",
androidMonochromeIcon: "./assets/android-icon-mark.png",
androidNotificationIcon: "./assets/android-notification-icon.png",
androidNotificationColor: "#00639B",
} as const;
const RELEASE_ASSETS = {
appIcon: "./assets/splash-icon-prod.png",
iosIcon: "./assets/icon-composer-prod.icon",
splashIcon: "./assets/splash-icon-prod.png",
androidAdaptiveForeground: "./assets/android-icon-mark.png",
androidAdaptiveBackgroundColor: "#000000",
androidMonochromeIcon: "./assets/android-icon-mark.png",
androidNotificationIcon: "./assets/android-notification-icon.png",
androidNotificationColor: "#FFFFFF",
} as const;
const VARIANT_CONFIG = {
development: {
appName: "T3 Code Dev",
scheme: "t3code-dev",
iosIcon: "./assets/icon-composer-dev.icon",
splashIcon: "./assets/splash-icon-dev.png",
iosBundleIdentifier: "com.t3tools.t3code.dev",
androidPackage: "com.t3tools.t3code.dev",
relyingParty: "clerk.t3.codes",
assets: DEVELOPMENT_ASSETS,
},
preview: {
appName: "T3 Code Preview",
scheme: "t3code-preview",
iosIcon: "./assets/icon-composer-prod.icon",
splashIcon: "./assets/splash-icon-prod.png",
iosBundleIdentifier: "com.t3tools.t3code.preview",
androidPackage: "com.t3tools.t3code.preview",
relyingParty: "clerk.t3.codes",
assets: RELEASE_ASSETS,
},
production: {
appName: "T3 Code",
scheme: "t3code",
iosIcon: "./assets/icon-composer-prod.icon",
splashIcon: "./assets/splash-icon-prod.png",
iosBundleIdentifier: "com.t3tools.t3code",
androidPackage: "com.t3tools.t3code",
relyingParty: "clerk.t3.codes",
assets: RELEASE_ASSETS,
},
};
} as const;
function resolveAppVariant(value: string | undefined): AppVariant {
switch (value) {
@@ -63,6 +85,36 @@ function resolveAppVariant(value: string | undefined): AppVariant {
const variant = VARIANT_CONFIG[APP_VARIANT];
const dmSansFonts = {
regular: "@expo-google-fonts/dm-sans/400Regular/DMSans_400Regular.ttf",
medium: "@expo-google-fonts/dm-sans/500Medium/DMSans_500Medium.ttf",
bold: "@expo-google-fonts/dm-sans/700Bold/DMSans_700Bold.ttf",
} as const;
const widgetsPlugin: NonNullable<ExpoConfig["plugins"]>[number] = [
"expo-widgets",
{
bundleIdentifier: `${variant.iosBundleIdentifier}.widgets`,
groupIdentifier: `group.${variant.iosBundleIdentifier}`,
enablePushNotifications: true,
// Agent activity can update many times an hour; without the
// frequent-updates entitlement iOS throttles the update budget sooner.
frequentUpdates: true,
widgets: [
{
name: "AgentActivity",
displayName: "Agent Activity",
description: "Shows the current state of active T3 Code agents.",
supportedFamilies: ["systemSmall", "systemMedium", "accessoryRectangular"],
},
],
},
];
// These aliases match the fonts' PostScript names on iOS. Register the same
// names on Android so React Native and the native composer use one set of
// family names without waiting for runtime font loading.
const config: ExpoConfig = {
name: variant.appName,
slug: "t3-code",
@@ -77,7 +129,7 @@ const config: ExpoConfig = {
policy: process.env.MOBILE_VERSION_POLICY ?? "fingerprint",
},
orientation: "portrait",
icon: "./assets/icon.png",
icon: variant.assets.appIcon,
userInterfaceStyle: "automatic",
updates: {
enabled: true,
@@ -86,7 +138,7 @@ const config: ExpoConfig = {
fallbackToCacheTimeout: 0,
},
ios: {
icon: variant.iosIcon,
icon: variant.assets.iosIcon,
supportsTablet: true,
bundleIdentifier: variant.iosBundleIdentifier,
// Pin code signing to the T3 Tools team so non-interactive `expo run:ios`
@@ -107,40 +159,91 @@ const config: ExpoConfig = {
},
},
android: {
icon: "./assets/icon.png",
icon: variant.assets.appIcon,
package: variant.androidPackage,
adaptiveIcon: {
backgroundColor: "#E6F4FE",
foregroundImage: "./assets/android-icon-foreground.png",
backgroundImage: "./assets/android-icon-background.png",
monochromeImage: "./assets/android-icon-monochrome.png",
backgroundColor: variant.assets.androidAdaptiveBackgroundColor,
foregroundImage: variant.assets.androidAdaptiveForeground,
monochromeImage: variant.assets.androidMonochromeIcon,
},
predictiveBackGestureEnabled: false,
// Opts into OnBackInvokedCallback-based back dispatch (Android 13+).
// JS back handling survives it via react-native's Android 16 shim plus
// withAndroidPredictiveBackCompat on Android 13-15.
predictiveBackGestureEnabled: true,
},
web: {
favicon: "./assets/favicon.png",
favicon: variant.assets.appIcon,
},
plugins: [
"expo-font",
"expo-asset",
[
"expo-font",
{
ios: {
fonts: [dmSansFonts.regular, dmSansFonts.medium, dmSansFonts.bold],
},
android: {
fonts: [
{
fontFamily: "DMSans-Regular",
fontDefinitions: [{ path: dmSansFonts.regular, weight: 400 }],
},
{
fontFamily: "DMSans-Medium",
fontDefinitions: [{ path: dmSansFonts.medium, weight: 500 }],
},
{
fontFamily: "DMSans-Bold",
fontDefinitions: [{ path: dmSansFonts.bold, weight: 700 }],
},
],
},
},
],
"expo-secure-store",
["@clerk/expo", { theme: "./clerk-theme.json" }],
"expo-sqlite",
[
"expo-notifications",
{
icon: variant.assets.androidNotificationIcon,
color: variant.assets.androidNotificationColor,
mode: APP_VARIANT === "development" ? "development" : "production",
},
],
// appleSignIn must be gated here: withoutIosPersonalTeamCapabilities.cjs runs before
// plugins earlier in this array, so it cannot strip the entitlement Clerk would add.
["@clerk/expo", { theme: "./clerk-theme.json", appleSignIn: !isIosPersonalTeamBuild }],
"expo-web-browser",
[
"expo-quick-actions",
{
// Adaptive launcher-shortcut icon; referenced by resource name from
// the shortcut items set in src/features/shortcuts.
androidIcons: {
shortcut_icon: {
foregroundImage: variant.assets.androidAdaptiveForeground,
backgroundColor: variant.assets.androidAdaptiveBackgroundColor,
},
},
},
],
[
"expo-camera",
{
cameraPermission: "Allow T3 Code to access your camera so you can scan pairing QR codes.",
barcodeScannerEnabled: true,
recordAudioAndroid: false,
},
],
[
"expo-splash-screen",
{
image: variant.splashIcon,
image: variant.assets.splashIcon,
resizeMode: "contain",
backgroundColor: "#ffffff",
imageWidth: 220,
dark: {
image: variant.splashIcon,
image: variant.assets.splashIcon,
backgroundColor: "#0a0a0a",
},
},
@@ -164,31 +267,18 @@ const config: ExpoConfig = {
// expo-widgets' — its dangerous mod wipes ios/ExpoWidgetsTarget/ (which
// would delete the asset catalog) and its xcodeproj mod creates the widget
// target (which must exist before the compile phase can be attached).
"./plugins/withWidgetLogoAsset.cjs",
[
"expo-widgets",
{
bundleIdentifier: `${variant.iosBundleIdentifier}.widgets`,
groupIdentifier: `group.${variant.iosBundleIdentifier}`,
enablePushNotifications: true,
// Agent activity can update many times an hour; without the
// frequent-updates entitlement iOS throttles the update budget sooner.
frequentUpdates: true,
widgets: [
{
name: "AgentActivity",
displayName: "Agent Activity",
description: "Shows the current state of active T3 Code agents.",
supportedFamilies: ["systemSmall", "systemMedium", "accessoryRectangular"],
},
],
},
],
...(!isIosPersonalTeamBuild ? ["./plugins/withWidgetLogoAsset.cjs", widgetsPlugin] : []),
"./plugins/withIosSceneLifecycle.cjs",
"./plugins/withAndroidCleartextTraffic.cjs",
"./plugins/withAndroidGradleHeap.cjs",
"./plugins/withAndroidModernPopupMenu.cjs",
"./plugins/withAndroidModernAlertDialog.cjs",
"./plugins/withAndroidPredictiveBackCompat.cjs",
...(isIosPersonalTeamBuild ? ["./plugins/withoutIosPersonalTeamCapabilities.cjs"] : []),
],
extra: {
appVariant: APP_VARIANT,
iosPersonalTeamBuild: isIosPersonalTeamBuild,
relay: {
url: repoEnv.T3CODE_RELAY_URL ?? null,
},
File renamed without changes.

Before

Width:  |  Height:  |  Size: 323 KiB

After

Width:  |  Height:  |  Size: 323 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 323 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 323 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 733 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 74 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.0 MiB

+8 -4
View File
@@ -8,7 +8,8 @@
"development": {
"corepack": true,
"env": {
"APP_VARIANT": "development"
"APP_VARIANT": "development",
"NODE_OPTIONS": "--max-old-space-size=4096"
},
"channel": "development",
"developmentClient": true,
@@ -17,7 +18,8 @@
"preview": {
"corepack": true,
"env": {
"APP_VARIANT": "preview"
"APP_VARIANT": "preview",
"NODE_OPTIONS": "--max-old-space-size=4096"
},
"channel": "preview",
"environment": "preview",
@@ -27,7 +29,8 @@
"corepack": true,
"env": {
"APP_VARIANT": "preview",
"MOBILE_VERSION_POLICY": "fingerprint"
"MOBILE_VERSION_POLICY": "fingerprint",
"NODE_OPTIONS": "--max-old-space-size=4096"
},
"channel": "preview",
"environment": "preview",
@@ -40,7 +43,8 @@
"production": {
"corepack": true,
"env": {
"APP_VARIANT": "production"
"APP_VARIANT": "production",
"NODE_OPTIONS": "--max-old-space-size=4096"
},
"channel": "production",
"environment": "production",
+11 -8
View File
@@ -12,7 +12,7 @@
/* Card / surface */
--color-card: #ffffff;
--color-card-alt: #f5f5f5;
--color-card-translucent: rgba(255, 255, 255, 0.94);
--color-card-translucent: rgba(255, 255, 255, 0.8);
/* Text */
--color-foreground: #262626;
@@ -51,6 +51,7 @@
/* Inputs */
--color-input: #ffffff;
--color-input-border: rgba(0, 0, 0, 0.1);
--color-sidebar-search: rgba(118, 118, 128, 0.12);
--color-placeholder: #a3a3a3;
/* Icons */
@@ -105,7 +106,7 @@
/* Card / surface */
--color-card: #171717;
--color-card-alt: #1c1c1c;
--color-card-translucent: rgba(17, 17, 17, 0.94);
--color-card-translucent: rgba(17, 17, 17, 0.8);
/* Text */
--color-foreground: #f5f5f5;
@@ -144,6 +145,7 @@
/* Inputs */
--color-input: #141414;
--color-input-border: rgba(255, 255, 255, 0.08);
--color-sidebar-search: rgba(118, 118, 128, 0.24);
--color-placeholder: #8e8e93;
/* Icons */
@@ -194,9 +196,10 @@
/* ─── Typography ────────────────────────────────────────────────────── */
@theme {
--font-sans: "DMSans_400Regular";
--font-medium: "DMSans_500Medium";
--font-bold: "DMSans_700Bold";
/* Keep these native family names aligned with app.config.ts. */
--font-sans: "DMSans-Regular";
--font-medium: "DMSans-Medium";
--font-bold: "DMSans-Bold";
/* Keep this scale aligned with src/lib/typography.ts for native style props. */
--text-3xs: 11px;
@@ -221,14 +224,14 @@
/* ─── Custom utilities ──────────────────────────────────────────────── */
@utility font-t3-medium {
font-family: "DMSans_500Medium";
font-family: var(--font-medium);
}
@utility font-t3-bold {
font-family: "DMSans_700Bold";
font-family: var(--font-bold);
}
@utility font-t3-extrabold {
font-family: "DMSans_700Bold";
font-family: var(--font-bold);
font-weight: 800;
}
+9
View File
@@ -6,6 +6,7 @@ const { withUniwindConfig } = require("uniwind/metro");
/** @type {import("expo/metro-config").MetroConfig} */
const config = getDefaultConfig(__dirname);
const workspaceRoot = path.resolve(__dirname, "../..");
const escapedWorkspaceRoot = workspaceRoot.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
const mobileShikiRoot = path.dirname(require.resolve("shiki/package.json", { paths: [__dirname] }));
const resolveShikiDependencyRoot = (packageName) => {
const entryPath = require.resolve(packageName, { paths: [mobileShikiRoot] });
@@ -25,6 +26,14 @@ const resolveShikiDependencyRoot = (packageName) => {
config.watchFolders = [...new Set([...(config.watchFolders ?? []), workspaceRoot])];
config.resolver = {
...config.resolver,
blockList: [
...(Array.isArray(config.resolver?.blockList)
? config.resolver.blockList
: config.resolver?.blockList
? [config.resolver.blockList]
: []),
new RegExp(`${escapedWorkspaceRoot}[/\\\\]\\.t3[/\\\\].*`),
],
extraNodeModules: {
// oxlint-disable-next-line unicorn/no-useless-fallback-in-spread
...(config.resolver?.extraNodeModules ?? {}),
@@ -0,0 +1,19 @@
apply plugin: 'com.android.library'
apply plugin: 'org.jetbrains.kotlin.android'
group = 'com.t3tools.composereditor'
version = '0.0.0'
android {
namespace 'expo.modules.t3composereditor'
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,72 @@
package expo.modules.t3composereditor
import expo.modules.kotlin.modules.Module
import expo.modules.kotlin.modules.ModuleDefinition
class T3ComposerEditorModule : Module() {
override fun definition() = ModuleDefinition {
Name("T3ComposerEditor")
View(T3ComposerEditorView::class) {
Prop("controlledDocumentJson") { view: T3ComposerEditorView, documentJson: String ->
view.setControlledDocumentJson(documentJson)
}
Prop("themeJson") { view: T3ComposerEditorView, themeJson: String ->
view.setThemeJson(themeJson)
}
Prop("placeholder") { view: T3ComposerEditorView, placeholder: String ->
view.setPlaceholder(placeholder)
}
Prop("fontFamily") { view: T3ComposerEditorView, fontFamily: String ->
view.setFontFamily(fontFamily)
}
Prop("fontSize") { view: T3ComposerEditorView, fontSize: Double ->
view.setFontSize(fontSize.toFloat())
}
Prop("lineHeight") { view: T3ComposerEditorView, lineHeight: Double ->
view.setLineHeight(lineHeight.toFloat())
}
Prop("contentInsetVertical") { view: T3ComposerEditorView, contentInsetVertical: Double ->
view.setContentInsetVertical(contentInsetVertical.toInt())
}
Prop("singleLineCentered") { view: T3ComposerEditorView, singleLineCentered: Boolean ->
view.setSingleLineCentered(singleLineCentered)
}
Prop("editable") { view: T3ComposerEditorView, editable: Boolean ->
view.setEditable(editable)
}
Prop("scrollEnabled") { view: T3ComposerEditorView, scrollEnabled: Boolean ->
view.setScrollEnabled(scrollEnabled)
}
Prop("autoFocus") { view: T3ComposerEditorView, autoFocus: Boolean ->
view.setAutoFocus(autoFocus)
}
Prop("autoCorrect") { view: T3ComposerEditorView, autoCorrect: Boolean ->
view.setAutoCorrect(autoCorrect)
}
Prop("spellCheck") { view: T3ComposerEditorView, spellCheck: Boolean ->
view.setSpellCheck(spellCheck)
}
Events(
"onComposerChange",
"onComposerSelectionChange",
"onComposerFocus",
"onComposerBlur",
"onComposerPasteImages",
"onComposerContentSizeChange",
)
AsyncFunction("focus") { view: T3ComposerEditorView ->
view.focusEditor()
}
AsyncFunction("blur") { view: T3ComposerEditorView ->
view.blurEditor()
}
AsyncFunction("setSelection") { view: T3ComposerEditorView, start: Int, end: Int ->
view.setSelection(start, end)
}
}
}
}
@@ -0,0 +1,480 @@
package expo.modules.t3composereditor
import android.content.Context
import android.content.ClipboardManager
import android.graphics.Color
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.RectF
import android.graphics.Typeface
import android.text.Editable
import android.text.InputType
import android.text.Spanned
import android.text.TextWatcher
import android.text.style.ReplacementSpan
import android.view.Gravity
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import expo.modules.kotlin.AppContext
import expo.modules.kotlin.viewevent.EventDispatcher
import expo.modules.kotlin.views.ExpoView
import org.json.JSONObject
import kotlin.math.max
class T3ComposerEditorView(context: Context, appContext: AppContext) : ExpoView(
context,
appContext
) {
private val editor = SelectionAwareEditText(context)
private val onComposerChange by EventDispatcher()
private val onComposerSelectionChange by EventDispatcher()
private val onComposerFocus by EventDispatcher()
private val onComposerBlur by EventDispatcher()
private val onComposerPasteImages by EventDispatcher()
private val onComposerContentSizeChange by EventDispatcher()
private var applyingNativeValue = false
private var desiredLineHeightPx = 0
private var lastContentHeight = 0
private var contentInsetVertical = 0
private var tokensJson = "[]"
private var tokens: List<ComposerToken> = emptyList()
private var chipTheme = ComposerChipTheme.default()
private var autoCorrect = true
private var spellCheck = true
private var nativeEventCount = 0
init {
editor.setBackgroundColor(Color.TRANSPARENT)
editor.gravity = Gravity.TOP or Gravity.START
editor.includeFontPadding = false
editor.isSingleLine = false
editor.minLines = 1
editor.inputType =
InputType.TYPE_CLASS_TEXT or
InputType.TYPE_TEXT_FLAG_MULTI_LINE or
InputType.TYPE_TEXT_FLAG_CAP_SENTENCES
editor.setTextColor(Color.BLACK)
editor.setHintTextColor(Color.GRAY)
editor.setPadding(0, 0, 0, 0)
editor.selectionListener = { start, end ->
if (!applyingNativeValue) {
emitSelectionChange(start, end)
}
}
editor.pasteImagesListener = { uris ->
onComposerPasteImages(mapOf("uris" to uris))
}
editor.setOnFocusChangeListener { _, hasFocus ->
if (hasFocus) {
onComposerFocus(emptyMap<String, Any>())
} else {
onComposerBlur(emptyMap<String, Any>())
}
}
editor.addTextChangedListener(
object : TextWatcher {
override fun beforeTextChanged(
text: CharSequence?,
start: Int,
count: Int,
after: Int
) = Unit
override fun onTextChanged(text: CharSequence?, start: Int, before: Int, count: Int) = Unit
override fun afterTextChanged(editable: Editable?) {
if (applyingNativeValue) return
val nextValue = editable.toString()
val selection = currentSelectionPayload()
nativeEventCount += 1
onComposerChange(
mapOf(
"value" to nextValue,
"selection" to selection,
"eventCount" to nativeEventCount,
),
)
emitContentSizeIfNeeded()
}
},
)
editor.addOnLayoutChangeListener { _, _, _, _, _, _, _, _, _ -> emitContentSizeIfNeeded() }
addView(
editor,
LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT),
)
}
@Suppress("ReturnCount")
fun setControlledDocumentJson(documentJson: String) {
val document = try {
JSONObject(documentJson)
} catch (_: Exception) {
return
}
val mostRecentEventCount = document.optInt("mostRecentEventCount", -1)
if (mostRecentEventCount < nativeEventCount) return
val value = document.optString("value")
if (document.optBoolean("isNativeEcho") && editor.text.toString() != value) return
val nextTokensJson = document.optString("tokensJson", "[]")
val nextTokens = if (nextTokensJson == tokensJson) tokens else parseTokens(nextTokensJson)
val requestedSelection = document.optJSONObject("selection")
val previousSelectionStart = editor.selectionStart.coerceAtLeast(0)
val previousSelectionEnd = editor.selectionEnd.coerceAtLeast(0)
val valueChanged = editor.text.toString() != value
applyingNativeValue = true
try {
if (valueChanged) {
editor.setText(value)
}
tokensJson = nextTokensJson
tokens = nextTokens
applyTokenSpans()
if (requestedSelection != null) {
applySelection(
requestedSelection.optInt("start", previousSelectionStart),
requestedSelection.optInt("end", previousSelectionEnd),
)
} else if (valueChanged) {
applySelection(previousSelectionStart, previousSelectionEnd)
}
} finally {
applyingNativeValue = false
}
emitContentSizeIfNeeded()
}
fun setThemeJson(themeJson: String) {
try {
val theme = JSONObject(themeJson)
editor.setTextColor(parseColor(theme.optString("text"), Color.BLACK))
editor.setHintTextColor(parseColor(theme.optString("placeholder"), Color.GRAY))
chipTheme = ComposerChipTheme(
chipBackground = parseColor(theme.optString("chipBackground"), chipTheme.chipBackground),
chipBorder = parseColor(theme.optString("chipBorder"), chipTheme.chipBorder),
chipText = parseColor(theme.optString("chipText"), chipTheme.chipText),
skillBackground = parseColor(
theme.optString("skillBackground"),
chipTheme.skillBackground,
),
skillBorder = parseColor(theme.optString("skillBorder"), chipTheme.skillBorder),
skillText = parseColor(theme.optString("skillText"), chipTheme.skillText),
)
applyTokenSpans()
} catch (_: Exception) {
}
}
fun setPlaceholder(placeholder: String) {
editor.hint = placeholder
}
fun setFontFamily(fontFamily: String) {
editor.typeface = if (fontFamily.contains("Mono", ignoreCase = true)) {
Typeface.MONOSPACE
} else {
Typeface.DEFAULT
}
}
fun setFontSize(fontSize: Float) {
editor.textSize = fontSize
applyLineHeight()
}
fun setLineHeight(lineHeight: Float) {
desiredLineHeightPx = (lineHeight * resources.displayMetrics.density).toInt()
applyLineHeight()
}
fun setSingleLineCentered(centered: Boolean) {
editor.gravity = if (centered) {
Gravity.CENTER_VERTICAL or Gravity.START
} else {
Gravity.TOP or Gravity.START
}
}
fun setContentInsetVertical(contentInsetVertical: Int) {
this.contentInsetVertical =
max(0, (contentInsetVertical * resources.displayMetrics.density).toInt())
editor.setPadding(0, this.contentInsetVertical, 0, this.contentInsetVertical)
emitContentSizeIfNeeded()
}
fun setEditable(editable: Boolean) {
editor.isEnabled = editable
editor.isFocusable = editable
editor.isFocusableInTouchMode = editable
editor.isCursorVisible = editable
}
fun setScrollEnabled(scrollEnabled: Boolean) {
editor.isVerticalScrollBarEnabled = scrollEnabled
}
fun setAutoFocus(autoFocus: Boolean) {
if (autoFocus) {
post { focusEditor() }
}
}
fun setAutoCorrect(autoCorrect: Boolean) {
this.autoCorrect = autoCorrect
updateInputFlags()
}
fun setSpellCheck(spellCheck: Boolean) {
this.spellCheck = spellCheck
updateInputFlags()
}
fun focusEditor() {
editor.requestFocus()
val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager
imm?.showSoftInput(editor, InputMethodManager.SHOW_IMPLICIT)
}
fun blurEditor() {
editor.clearFocus()
val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager
imm?.hideSoftInputFromWindow(editor.windowToken, 0)
}
fun setSelection(start: Int, end: Int) {
applySelection(start, end)
}
private fun applySelection(start: Int, end: Int) {
val textLength = editor.text?.length ?: 0
val safeStart = start.coerceIn(0, textLength)
val safeEnd = end.coerceIn(0, textLength)
editor.setSelection(safeStart, safeEnd)
}
private fun updateInputFlags() {
var flags =
InputType.TYPE_CLASS_TEXT or
InputType.TYPE_TEXT_FLAG_MULTI_LINE or
InputType.TYPE_TEXT_FLAG_CAP_SENTENCES
flags = if (autoCorrect && spellCheck) {
flags or InputType.TYPE_TEXT_FLAG_AUTO_CORRECT
} else {
flags or InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS
}
editor.inputType = flags
}
private fun applyLineHeight() {
if (desiredLineHeightPx <= 0) return
val fontHeight = editor.paint.fontMetricsInt.descent - editor.paint.fontMetricsInt.ascent
editor.setLineSpacing(max(0, desiredLineHeightPx - fontHeight).toFloat(), 1f)
}
private fun currentSelectionPayload(): Map<String, Int> =
mapOf(
"start" to editor.selectionStart.coerceAtLeast(0),
"end" to editor.selectionEnd.coerceAtLeast(0),
)
private fun emitSelectionChange(start: Int, end: Int) {
onComposerSelectionChange(
mapOf(
"value" to editor.text.toString(),
"selection" to mapOf("start" to start, "end" to end),
"eventCount" to nativeEventCount,
),
)
}
private fun emitContentSizeIfNeeded() {
val height = editor.layout?.height ?: editor.measuredHeight
val contentHeight = height + contentInsetVertical * 2
if (contentHeight == lastContentHeight) return
lastContentHeight = contentHeight
onComposerContentSizeChange(
mapOf("height" to contentHeight / resources.displayMetrics.density),
)
}
private fun applyTokenSpans() {
val editable = editor.text ?: return
editable.getSpans(
0,
editable.length,
ComposerChipSpan::class.java
).forEach(editable::removeSpan)
tokens.forEach { token ->
if (token.start < 0 || token.end <= token.start || token.end > editable.length) return@forEach
val expectedSource = editable.substring(token.start, token.end)
if (expectedSource != token.source) return@forEach
editable.setSpan(
ComposerChipSpan(
token.label,
token.type == "skill",
chipTheme,
resources.displayMetrics.density
),
token.start,
token.end,
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE,
)
}
editor.invalidate()
}
private fun parseColor(value: String, fallback: Int): Int =
try {
Color.parseColor(value)
} catch (_: Exception) {
fallback
}
}
private data class ComposerToken(
val type: String,
val source: String,
val label: String,
val start: Int,
val end: Int
)
private data class ComposerChipTheme(
val chipBackground: Int,
val chipBorder: Int,
val chipText: Int,
val skillBackground: Int,
val skillBorder: Int,
val skillText: Int
) {
companion object {
fun default() = ComposerChipTheme(
chipBackground = Color.rgb(238, 240, 243),
chipBorder = Color.rgb(210, 214, 220),
chipText = Color.rgb(35, 39, 45),
skillBackground = Color.rgb(233, 239, 255),
skillBorder = Color.rgb(185, 200, 245),
skillText = Color.rgb(45, 72, 155),
)
}
}
private class ComposerChipSpan(
private val label: String,
private val skill: Boolean,
private val theme: ComposerChipTheme,
density: Float
) : ReplacementSpan() {
private val horizontalPadding = 7f * density
private val verticalPadding = 2f * density
private val cornerRadius = 6f * density
private val borderWidth = density
override fun getSize(
paint: Paint,
text: CharSequence,
start: Int,
end: Int,
fontMetrics: Paint.FontMetricsInt?
): Int {
fontMetrics?.let {
val extra = verticalPadding.toInt()
val base = paint.fontMetricsInt
it.top = base.top - extra
it.ascent = base.ascent - extra
it.descent = base.descent + extra
it.bottom = base.bottom + extra
}
return (paint.measureText(label) + horizontalPadding * 2).toInt()
}
override fun draw(
canvas: Canvas,
text: CharSequence,
start: Int,
end: Int,
x: Float,
top: Int,
y: Int,
bottom: Int,
paint: Paint
) {
val width = paint.measureText(label) + horizontalPadding * 2
val metrics = paint.fontMetrics
val rect = RectF(
x,
y + metrics.ascent - verticalPadding,
x + width,
y + metrics.descent + verticalPadding,
)
val originalColor = paint.color
val originalStyle = paint.style
val originalStrokeWidth = paint.strokeWidth
paint.color = if (skill) theme.skillBackground else theme.chipBackground
paint.style = Paint.Style.FILL
canvas.drawRoundRect(rect, cornerRadius, cornerRadius, paint)
paint.color = if (skill) theme.skillBorder else theme.chipBorder
paint.style = Paint.Style.STROKE
paint.strokeWidth = borderWidth
canvas.drawRoundRect(rect, cornerRadius, cornerRadius, paint)
paint.color = if (skill) theme.skillText else theme.chipText
paint.style = Paint.Style.FILL
canvas.drawText(label, x + horizontalPadding, y.toFloat(), paint)
paint.color = originalColor
paint.style = originalStyle
paint.strokeWidth = originalStrokeWidth
}
}
private fun parseTokens(value: String): List<ComposerToken> = try {
val array = org.json.JSONArray(value)
List(array.length()) { index ->
val token = array.getJSONObject(index)
ComposerToken(
type = token.optString("type"),
source = token.optString("source"),
label = token.optString("label"),
start = token.optInt("start"),
end = token.optInt("end"),
)
}
} catch (_: Exception) {
emptyList()
}
private class SelectionAwareEditText(context: Context) : EditText(context) {
var selectionListener: ((Int, Int) -> Unit)? = null
var pasteImagesListener: ((List<String>) -> Unit)? = null
override fun onSelectionChanged(selStart: Int, selEnd: Int) {
super.onSelectionChanged(selStart, selEnd)
selectionListener?.invoke(selStart, selEnd)
}
override fun onTextContextMenuItem(id: Int): Boolean {
if (id == android.R.id.paste || id == android.R.id.pasteAsPlainText) {
val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as? ClipboardManager
val clip = clipboard?.primaryClip
val imageUris = buildList {
if (clip != null) {
for (index in 0 until clip.itemCount) {
clip.getItemAt(index).uri?.let { uri ->
val mimeType = context.contentResolver.getType(uri)
if (mimeType?.startsWith("image/") == true) add(uri.toString())
}
}
}
}
if (imageUris.isNotEmpty()) {
pasteImagesListener?.invoke(imageUris)
return true
}
}
return super.onTextContextMenuItem(id)
}
}
@@ -1,6 +1,9 @@
{
"platforms": ["apple"],
"platforms": ["apple", "android"],
"apple": {
"modules": ["T3ComposerEditorModule"]
},
"android": {
"modules": ["expo.modules.t3composereditor.T3ComposerEditorModule"]
}
}
@@ -300,7 +300,7 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate {
skillText: "#a21caf",
fileTint: "#737373"
)
private var fontFamily = "DMSans_400Regular"
private var fontFamily = "DMSans-Regular"
private var fontSize: CGFloat = 14
private var lineHeight: CGFloat = 20
private var contentInsetVertical: CGFloat = 0
@@ -608,7 +608,7 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate {
iconImage: UIImage?,
style: ComposerChipStyle
) -> UIImage {
let font = UIFont(name: "DMSans_500Medium", size: max(12, fontSize - 2))
let font = UIFont(name: "DMSans-Medium", size: max(12, fontSize - 2))
?? UIFont.systemFont(ofSize: max(12, fontSize - 2), weight: .medium)
let fallbackIcon = UIImage(
systemName: iconName,
@@ -0,0 +1,19 @@
apply plugin: 'com.android.library'
apply plugin: 'org.jetbrains.kotlin.android'
group = 'com.t3tools.nativecontrols'
version = '0.0.0'
android {
namespace 'expo.modules.t3nativecontrols'
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,97 @@
package expo.modules.t3nativecontrols
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.view.View
import expo.modules.kotlin.AppContext
import expo.modules.kotlin.viewevent.EventDispatcher
import expo.modules.kotlin.views.ExpoView
class T3HeaderButtonView(context: Context, appContext: AppContext) : ExpoView(context, appContext) {
private val iconView = HeaderIconView(context)
private val onTriggered by EventDispatcher()
init {
isClickable = true
isFocusable = true
setOnClickListener {
onTriggered(emptyMap<String, Any>())
}
addView(iconView, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT))
}
fun setLabel(label: String) {
contentDescription = label
}
fun setSystemImage(systemImage: String) {
iconView.systemImage = systemImage
}
}
private class HeaderIconView(context: Context) : View(context) {
private val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
color = Color.parseColor("#6B7280")
strokeCap = Paint.Cap.ROUND
strokeJoin = Paint.Join.ROUND
strokeWidth = 3f * resources.displayMetrics.density
style = Paint.Style.STROKE
}
var systemImage: String = "gearshape"
set(value) {
field = value
invalidate()
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
val cx = width / 2f
val cy = height / 2f
val size = minOf(width, height).toFloat()
if (systemImage == "square.and.pencil") {
drawNewTask(canvas, cx, cy, size)
} else {
drawSettings(canvas, cx, cy, size)
}
}
private fun drawSettings(canvas: Canvas, cx: Float, cy: Float, size: Float) {
val radius = size * 0.12f
canvas.drawCircle(cx, cy, radius, paint)
for (index in 0 until 8) {
val angle = Math.PI * index / 4.0
val inner = size * 0.19f
val outer = size * 0.27f
val sx = cx + kotlin.math.cos(angle).toFloat() * inner
val sy = cy + kotlin.math.sin(angle).toFloat() * inner
val ex = cx + kotlin.math.cos(angle).toFloat() * outer
val ey = cy + kotlin.math.sin(angle).toFloat() * outer
canvas.drawLine(sx, sy, ex, ey, paint)
}
}
private fun drawNewTask(canvas: Canvas, cx: Float, cy: Float, size: Float) {
val left = cx - size * 0.2f
val top = cy - size * 0.16f
val right = cx + size * 0.14f
val bottom = cy + size * 0.2f
canvas.drawRoundRect(left, top, right, bottom, size * 0.04f, size * 0.04f, paint)
canvas.drawLine(
cx - size * 0.02f,
cy + size * 0.13f,
cx + size * 0.24f,
cy - size * 0.13f,
paint
)
canvas.drawLine(
cx + size * 0.17f,
cy - size * 0.2f,
cx + size * 0.24f,
cy - size * 0.13f,
paint
)
}
}
@@ -0,0 +1,21 @@
package expo.modules.t3nativecontrols
import expo.modules.kotlin.modules.Module
import expo.modules.kotlin.modules.ModuleDefinition
class T3NativeControlsModule : Module() {
override fun definition() = ModuleDefinition {
Name("T3NativeControls")
View(T3HeaderButtonView::class) {
Prop("label") { view: T3HeaderButtonView, label: String ->
view.setLabel(label)
}
Prop("systemImage") { view: T3HeaderButtonView, systemImage: String ->
view.setSystemImage(systemImage)
}
Events("onTriggered")
}
}
}
@@ -1,6 +1,9 @@
{
"platforms": ["apple"],
"platforms": ["apple", "android"],
"apple": {
"modules": ["T3NativeControlsModule", "T3KeyboardCommandsModule"]
},
"android": {
"modules": ["expo.modules.t3nativecontrols.T3NativeControlsModule"]
}
}
@@ -0,0 +1,19 @@
apply plugin: 'com.android.library'
apply plugin: 'org.jetbrains.kotlin.android'
group = 'com.t3tools.reviewdiff'
version = '0.0.0'
android {
namespace 'expo.modules.t3reviewdiff'
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,315 @@
package expo.modules.t3reviewdiff
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.LinearGradient
import android.graphics.Paint
import android.graphics.Path
import android.graphics.RectF
import android.graphics.Shader
import android.graphics.Typeface
import kotlin.math.max
import kotlin.math.min
internal class ReviewDiffCanvasDrawing(context: Context) {
private val density = context.resources.displayMetrics.density
var theme: DiffTheme = DiffTheme.fallback("light")
val backgroundPaint = Paint()
val borderPaint = Paint(Paint.ANTI_ALIAS_FLAG)
val textPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
hinting = Paint.HINTING_ON
isSubpixelText = false
clearShadowLayer()
}
val uiPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
hinting = Paint.HINTING_ON
isSubpixelText = false
clearShadowLayer()
}
private val italicCodeTypeface by lazy {
Typeface.create(ReviewDiffTypefaces.regular, Typeface.ITALIC)
}
private val boldItalicCodeTypeface by lazy {
Typeface.create(ReviewDiffTypefaces.bold, Typeface.ITALIC)
}
init {
textPaint.typeface = ReviewDiffTypefaces.regular
uiPaint.typeface = Typeface.DEFAULT_BOLD
}
fun fileHeaderChevronRect(top: Int, bottom: Int, style: DiffStyle): RectF {
val centerY = (top + bottom) / 2f
val left = style.fileHeaderHorizontalPaddingPx
return RectF(left, centerY - 10f * density, left + 20f * density, centerY + 10f * density)
}
fun fileHeaderIconRect(top: Int, bottom: Int, style: DiffStyle): RectF {
val chevron = fileHeaderChevronRect(top, bottom, style)
return RectF(
chevron.right + 8f * density,
chevron.top,
chevron.right + 28f * density,
chevron.bottom,
)
}
fun fileHeaderCheckboxRect(top: Int, bottom: Int, width: Int, style: DiffStyle): RectF {
val centerY = (top + bottom) / 2f
val right = width - style.fileHeaderHorizontalPaddingPx
return RectF(
right - 20f * density,
centerY - 10f * density,
right,
centerY + 10f * density,
)
}
fun drawDisclosureChevron(
canvas: Canvas,
rect: RectF,
color: Int,
collapsed: Boolean
) {
borderPaint.style = Paint.Style.STROKE
borderPaint.color = color
borderPaint.strokeWidth = 2f * density
borderPaint.strokeCap = Paint.Cap.ROUND
borderPaint.strokeJoin = Paint.Join.ROUND
val path = Path()
if (collapsed) {
path.moveTo(rect.left + rect.width() * 0.4f, rect.top + rect.height() * 0.28f)
path.lineTo(rect.left + rect.width() * 0.6f, rect.centerY())
path.lineTo(rect.left + rect.width() * 0.4f, rect.bottom - rect.height() * 0.28f)
} else {
path.moveTo(rect.left + rect.width() * 0.28f, rect.top + rect.height() * 0.42f)
path.lineTo(rect.centerX(), rect.top + rect.height() * 0.62f)
path.lineTo(rect.right - rect.width() * 0.28f, rect.top + rect.height() * 0.42f)
}
canvas.drawPath(path, borderPaint)
borderPaint.style = Paint.Style.FILL
}
fun drawFileIcon(canvas: Canvas, rect: RectF, changeType: String) {
val color = when (changeType) {
"new" -> theme.addText
"deleted" -> theme.deleteText
else -> theme.hunkText
}
borderPaint.style = Paint.Style.STROKE
borderPaint.color = color
borderPaint.strokeWidth = 2f * density
canvas.drawRoundRect(rect, 6f * density, 6f * density, borderPaint)
if (changeType == "rename-pure" || changeType == "rename-changed" || changeType == "renamed") {
drawRenameChevronIcon(canvas, rect, color)
} else {
backgroundPaint.color = color
canvas.drawCircle(rect.centerX(), rect.centerY(), 3f * density, backgroundPaint)
}
borderPaint.style = Paint.Style.FILL
}
fun drawViewedCheckbox(canvas: Canvas, rect: RectF, checked: Boolean) {
if (checked) {
backgroundPaint.color = theme.hunkText
canvas.drawRoundRect(rect, 6f * density, 6f * density, backgroundPaint)
}
borderPaint.style = Paint.Style.STROKE
borderPaint.color = if (checked) theme.hunkText else theme.mutedText
borderPaint.strokeWidth = 1.8f * density
canvas.drawRoundRect(rect, 6f * density, 6f * density, borderPaint)
if (checked) {
borderPaint.color = theme.background
borderPaint.strokeWidth = 2f * density
borderPaint.strokeCap = Paint.Cap.ROUND
borderPaint.strokeJoin = Paint.Join.ROUND
val path = Path().apply {
moveTo(rect.left + rect.width() * 0.28f, rect.centerY())
lineTo(rect.left + rect.width() * 0.44f, rect.bottom - rect.height() * 0.3f)
lineTo(rect.right - rect.width() * 0.25f, rect.top + rect.height() * 0.3f)
}
canvas.drawPath(path, borderPaint)
}
borderPaint.style = Paint.Style.FILL
}
fun drawNoticeIcon(canvas: Canvas, rect: RectF, color: Int) {
borderPaint.style = Paint.Style.STROKE
borderPaint.color = color
borderPaint.strokeWidth = 1.7f * density
borderPaint.strokeCap = Paint.Cap.ROUND
canvas.drawOval(rect, borderPaint)
canvas.drawLine(
rect.centerX(),
rect.top + rect.height() * 0.3f,
rect.centerX(),
rect.top + rect.height() * 0.58f,
borderPaint,
)
borderPaint.style = Paint.Style.FILL
canvas.drawCircle(rect.centerX(), rect.bottom - rect.height() * 0.24f, density, borderPaint)
}
fun configureUiPaint(paint: Paint, color: Int, size: Float, weight: String) {
paint.typeface = if (isBoldFontWeight(weight)) Typeface.DEFAULT_BOLD else Typeface.DEFAULT
configureTextPaint(paint, color, size)
}
fun configureMonospacePaint(color: Int, size: Float, weight: String) {
textPaint.typeface = ReviewDiffTypefaces.forWeight(weight)
configureTextPaint(textPaint, color, size)
}
fun configureCodePaint(color: Int, fontStyle: Int, style: DiffStyle) {
val tokenBold = fontStyle and 2 != 0
val italic = fontStyle and 1 != 0
textPaint.typeface = when {
tokenBold && italic -> boldItalicCodeTypeface
tokenBold -> ReviewDiffTypefaces.bold
italic -> italicCodeTypeface
else -> ReviewDiffTypefaces.forWeight(style.codeFontWeight)
}
configureTextPaint(textPaint, color, style.codeFontSizePx)
textPaint.isUnderlineText = fontStyle and 4 != 0
}
fun lineNumberColor(change: String): Int = when (change) {
"add" -> theme.addText
"delete" -> theme.deleteText
else -> theme.mutedText
}
fun drawDeleteStripes(
canvas: Canvas,
top: Int,
bottom: Int,
width: Float,
color: Int
) {
backgroundPaint.color = color
var y = top.toFloat()
while (y < bottom) {
canvas.drawRect(0f, y, width, min(bottom.toFloat(), y + density), backgroundPaint)
y += 2f * density
}
}
fun drawWordDiffRanges(
canvas: Canvas,
row: DiffRow,
codeX: Float,
top: Int,
bottom: Int
) {
if (row.wordDiffRanges.isEmpty() || (row.change != "add" && row.change != "delete")) return
val color = if (row.change == "add") theme.addBar else theme.deleteBar
backgroundPaint.color = withAlpha(color, 71)
val characterWidth = textPaint.measureText("M")
val fontHeight = textPaint.fontMetrics.run { descent - ascent }
val highlightHeight = max(4f * density, min(bottom - top - 4f * density, fontHeight))
val highlightTop = (top + bottom - highlightHeight) / 2f
row.wordDiffRanges.forEach { range ->
val left = codeX + range.start * characterWidth
val right = max(left + 2f * density, codeX + range.end * characterWidth)
canvas.drawRoundRect(
RectF(left, highlightTop, right, highlightTop + highlightHeight),
3f * density,
3f * density,
backgroundPaint,
)
}
}
fun drawFileHeaderPathScrollFades(
canvas: Canvas,
pathRect: RectF,
horizontalOffset: Int,
maxOffset: Int
) {
if (maxOffset <= 0 || pathRect.width() <= 0f) return
val fadeWidth = min(28f * density, pathRect.width() / 3f)
if (horizontalOffset > 0) {
drawHorizontalFade(
canvas,
RectF(pathRect.left, pathRect.top, pathRect.left + fadeWidth, pathRect.bottom),
fadesToRight = false,
)
}
if (horizontalOffset < maxOffset) {
drawHorizontalFade(
canvas,
RectF(pathRect.right - fadeWidth, pathRect.top, pathRect.right, pathRect.bottom),
fadesToRight = true,
)
}
}
private fun drawRenameChevronIcon(canvas: Canvas, rect: RectF, color: Int) {
borderPaint.style = Paint.Style.STROKE
borderPaint.color = color
borderPaint.strokeWidth = 1.8f * density
borderPaint.strokeCap = Paint.Cap.ROUND
borderPaint.strokeJoin = Paint.Join.ROUND
val chevronWidth = 3.6f * density
val chevronHeight = 8f * density
val gap = 2.4f * density
val startX = rect.centerX() - (chevronWidth * 2f + gap) / 2f
val path = Path()
for (x in listOf(startX, startX + chevronWidth + gap)) {
path.moveTo(x, rect.centerY() - chevronHeight / 2f)
path.lineTo(x + chevronWidth, rect.centerY())
path.lineTo(x, rect.centerY() + chevronHeight / 2f)
}
canvas.drawPath(path, borderPaint)
}
private fun configureTextPaint(paint: Paint, color: Int, size: Float) {
paint.textSize = size
paint.color = color
paint.style = Paint.Style.FILL
paint.textAlign = Paint.Align.LEFT
paint.isUnderlineText = false
paint.isFakeBoldText = false
paint.clearShadowLayer()
}
private fun drawHorizontalFade(canvas: Canvas, rect: RectF, fadesToRight: Boolean) {
val opaque = theme.headerBackground
val transparent = Color.argb(0, Color.red(opaque), Color.green(opaque), Color.blue(opaque))
backgroundPaint.shader = LinearGradient(
rect.left,
rect.centerY(),
rect.right,
rect.centerY(),
if (fadesToRight) transparent else opaque,
if (fadesToRight) opaque else transparent,
Shader.TileMode.CLAMP,
)
canvas.drawRect(rect, backgroundPaint)
backgroundPaint.shader = null
}
private fun isBoldFontWeight(weight: String): Boolean = when (weight.lowercase()) {
"medium", "semibold", "semi-bold", "bold", "heavy", "black" -> true
else -> false
}
private fun withAlpha(color: Int, alpha: Int): Int =
Color.argb(alpha, Color.red(color), Color.green(color), Color.blue(color))
}
private object ReviewDiffTypefaces {
val regular: Typeface = Typeface.create("monospace", Typeface.NORMAL)
private val medium: Typeface = Typeface.create("monospace-medium", Typeface.NORMAL)
val bold: Typeface = Typeface.create("monospace", Typeface.BOLD)
fun forWeight(weight: String): Typeface = when (weight.lowercase()) {
"medium", "semibold", "semi-bold" -> medium
"bold", "heavy", "black" -> bold
else -> regular
}
}
@@ -0,0 +1,78 @@
package expo.modules.t3reviewdiff
import expo.modules.kotlin.modules.Module
import expo.modules.kotlin.modules.ModuleDefinition
class T3ReviewDiffModule : Module() {
override fun definition() = ModuleDefinition {
Name("T3ReviewDiffSurface")
View(T3ReviewDiffView::class) {
Prop("tokensResetKey") { view: T3ReviewDiffView, tokensResetKey: String ->
view.setTokensResetKey(tokensResetKey)
}
Prop("contentResetKey") { view: T3ReviewDiffView, contentResetKey: String ->
view.setContentResetKey(contentResetKey)
}
Prop("collapsedFileIdsJson") { view: T3ReviewDiffView, collapsedFileIdsJson: String ->
view.setCollapsedFileIdsJson(collapsedFileIdsJson)
}
Prop("viewedFileIdsJson") { view: T3ReviewDiffView, viewedFileIdsJson: String ->
view.setViewedFileIdsJson(viewedFileIdsJson)
}
Prop("selectedRowIdsJson") { view: T3ReviewDiffView, selectedRowIdsJson: String ->
view.setSelectedRowIdsJson(selectedRowIdsJson)
}
Prop("collapsedCommentIdsJson") { view: T3ReviewDiffView, collapsedCommentIdsJson: String ->
view.setCollapsedCommentIdsJson(collapsedCommentIdsJson)
}
Prop("appearanceScheme") { view: T3ReviewDiffView, appearanceScheme: String ->
view.setAppearanceScheme(appearanceScheme)
}
Prop("themeJson") { view: T3ReviewDiffView, themeJson: String ->
view.setThemeJson(themeJson)
}
Prop("styleJson") { view: T3ReviewDiffView, styleJson: String ->
view.setStyleJson(styleJson)
}
Prop("rowHeight") { view: T3ReviewDiffView, rowHeight: Double ->
view.setRowHeight(rowHeight.toFloat())
}
Prop("contentWidth") { view: T3ReviewDiffView, contentWidth: Double ->
view.setContentWidth(contentWidth.toFloat())
}
Prop("initialRowIndex") { view: T3ReviewDiffView, initialRowIndex: Double ->
view.setInitialRowIndex(initialRowIndex)
}
Events(
"onDebug",
"onVisibleFileChange",
"onToggleFile",
"onToggleViewedFile",
"onPressLine",
"onToggleComment",
)
AsyncFunction("scrollToFile") { view: T3ReviewDiffView, fileId: String, animated: Boolean ->
view.scrollToFile(fileId, animated)
}
AsyncFunction("scrollToTop") { view: T3ReviewDiffView, animated: Boolean ->
view.scrollToTop(animated)
}
AsyncFunction("setRowsJson") { view: T3ReviewDiffView, rowsJson: String ->
view.setRowsJson(rowsJson)
}
AsyncFunction("setTokensJson") { view: T3ReviewDiffView, tokensJson: String ->
view.setTokensJson(tokensJson)
}
AsyncFunction("setTokensPatchJson") { view: T3ReviewDiffView, tokensPatchJson: String ->
view.setTokensPatchJson(tokensPatchJson)
}
OnViewDestroys { view: T3ReviewDiffView ->
view.cleanup()
}
}
}
}
@@ -1,7 +1,10 @@
{
"platforms": ["apple"],
"platforms": ["apple", "android"],
"apple": {
"modules": ["T3ReviewDiffModule"],
"podspecPath": "T3ReviewDiffNative.podspec"
},
"android": {
"modules": ["expo.modules.t3reviewdiff.T3ReviewDiffModule"]
}
}
@@ -7,6 +7,11 @@
"modules": [
"T3ReviewDiffModule"
]
},
"android": {
"modules": [
"expo.modules.t3reviewdiff.T3ReviewDiffModule"
]
}
}
}
+15 -3
View File
@@ -18,9 +18,9 @@ uses that callback I/O model:
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.
Android implements the same view contract with upstream `libghostty-vt` for terminal state, parsing,
reflow, and scrollback. An Android Canvas view renders compact snapshots produced by the JNI bridge,
so the React Native screen and RPC code stay platform-neutral.
Vendored Ghostty revision and license details are in `THIRD_PARTY_NOTICES.md`.
@@ -36,3 +36,15 @@ 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`.
## Rebuilding libghostty-vt for Android
The checked-in Android shared libraries and headers are pinned to the revision recorded in
`Vendor/libghostty-vt/VERSION`. Set `ANDROID_NDK_HOME` and run:
```bash
apps/mobile/modules/t3-terminal/scripts/build-libghostty-android.sh
```
The script downloads Zig 0.15.2 when needed, checks out the pinned upstream Ghostty revision, and
rebuilds all four Android ABIs with 16 KB page-size support.
@@ -14,3 +14,21 @@ iOS 16 support fork. That fork was created from VVTerm's custom-I/O Ghostty fork
Ghostty's MIT license applies to the vendored framework. Keep this notice in sync when updating
`Vendor/libghostty`.
## Ghostty / libghostty-vt
The Android terminal renderer vendors upstream `libghostty-vt` shared libraries and C headers.
- Upstream project: https://github.com/ghostty-org/ghostty
- Vendored revision: `9f62873bf195e4d8a762d768a1405a5f2f7b1697`
- License: MIT
Ghostty's MIT license applies to the vendored Android libraries. Keep this notice in sync when
updating `Vendor/libghostty-vt`.
## MesloLGS NF (Android terminal font)
- Files: `android/src/main/assets/fonts/MesloLGS-NF-{Regular,Bold}.ttf`
- Source: https://github.com/romkatv/powerlevel10k-media (Meslo LG patched with Nerd Fonts glyphs)
- Upstream: Meslo LG by André Berg (customization of Apple's Menlo), Nerd Fonts patcher
- License: Apache License 2.0
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2024 Mitchell Hashimoto, Ghostty contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
@@ -0,0 +1 @@
9f62873bf195e4d8a762d768a1405a5f2f7b1697
@@ -0,0 +1,154 @@
/**
* @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 terminal "Terminal" - Complete terminal emulator state and rendering
* - @ref render "Render State" - Incremental render state updates for custom renderers
* - @ref formatter "Formatter" - Format terminal content as plain text, VT sequences, or HTML
* - @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 build_info "Build Info" - Query compile-time build configuration
* - @ref allocator "Memory Management" - Memory management and custom allocators
* - @ref wasm "WebAssembly Utilities" - WebAssembly convenience functions
*
* Encoding related APIs:
* - @ref focus "Focus Encoding" - Encode focus in/out events into terminal sequences
* - @ref key "Key Encoding" - Encode key events into terminal sequences
* - @ref mouse "Mouse Encoding" - Encode mouse events into terminal sequences
*
* @section examples_sec Examples
*
* Complete working examples:
* - @ref c-vt-build-info/src/main.c - Build info query example
* - @ref c-vt/src/main.c - OSC parser example
* - @ref c-vt-encode-key/src/main.c - Key encoding example
* - @ref c-vt-encode-mouse/src/main.c - Mouse encoding example
* - @ref c-vt-paste/src/main.c - Paste safety check example
* - @ref c-vt-sgr/src/main.c - SGR parser example
* - @ref c-vt-formatter/src/main.c - Terminal formatter example
* - @ref c-vt-grid-traverse/src/main.c - Grid traversal example using grid refs
* - @ref c-vt-grid-ref-tracked/src/main.c - Tracked grid ref example
*
*/
/** @example c-vt-build-info/src/main.c
* This example demonstrates how to query compile-time build configuration
* such as SIMD support, Kitty graphics, and tmux control mode availability.
*/
/** @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-encode-key/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-encode-mouse/src/main.c
* This example demonstrates how to use the mouse encoder to convert mouse events
* into terminal escape sequences using the SGR mouse format.
*/
/** @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.
*/
/** @example c-vt-formatter/src/main.c
* This example demonstrates how to use the terminal and formatter APIs to
* create a terminal, write VT-encoded content into it, and format the screen
* contents as plain text.
*/
/** @example c-vt-grid-traverse/src/main.c
* This example demonstrates how to traverse the entire terminal grid using
* grid refs to inspect cell codepoints, row wrap state, and cell styles.
*/
/** @example c-vt-grid-ref-tracked/src/main.c
* This example demonstrates how to track a grid ref as the terminal scrolls,
* detect when it loses its value, and move it to a new point.
*/
/** @example c-vt-selection-gesture/src/main.c
* This example demonstrates how to use synthetic selection gesture events to
* derive drag and deep-press selection snapshots.
*/
/** @example c-vt-kitty-graphics/src/main.c
* This example demonstrates how to use the system interface to install a
* PNG decoder callback and send a Kitty Graphics Protocol image.
*/
#ifndef GHOSTTY_VT_H
#define GHOSTTY_VT_H
#ifdef __cplusplus
extern "C" {
#endif
#include <ghostty/vt/types.h>
#include <ghostty/vt/allocator.h>
#include <ghostty/vt/build_info.h>
#include <ghostty/vt/color.h>
#include <ghostty/vt/device.h>
#include <ghostty/vt/focus.h>
#include <ghostty/vt/formatter.h>
#include <ghostty/vt/render.h>
#include <ghostty/vt/terminal.h>
#include <ghostty/vt/grid_ref.h>
#include <ghostty/vt/grid_ref_tracked.h>
#include <ghostty/vt/osc.h>
#include <ghostty/vt/sgr.h>
#include <ghostty/vt/style.h>
#include <ghostty/vt/sys.h>
#include <ghostty/vt/key.h>
#include <ghostty/vt/kitty_graphics.h>
#include <ghostty/vt/modes.h>
#include <ghostty/vt/mouse.h>
#include <ghostty/vt/paste.h>
#include <ghostty/vt/point.h>
#include <ghostty/vt/screen.h>
#include <ghostty/vt/selection.h>
#include <ghostty/vt/size_report.h>
#include <ghostty/vt/wasm.h>
#ifdef __cplusplus
}
#endif
#endif /* GHOSTTY_VT_H */
@@ -0,0 +1,255 @@
/**
* @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>
#include <ghostty/vt/types.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
*
* ## Alloc/Free Helpers
*
* ghostty_alloc() and ghostty_free() provide a simple malloc/free-style
* interface for allocating and freeing byte buffers through the library's
* allocator. These are useful when:
*
* - You need to allocate a buffer to pass into a libghostty-vt function
* (e.g. preparing input data for ghostty_terminal_vt_write()).
* - You need to free a buffer returned by a libghostty-vt function
* (e.g. the output of ghostty_formatter_format_alloc()).
* - You are on a platform where the library's internal allocator differs
* from the consumer's C runtime (e.g. Windows, where Zig's libc and
* MSVC's CRT maintain separate heaps), so calling the standard C
* free() on library-allocated memory would be undefined behavior.
*
* Always use the same allocator (or NULL) for both the allocation and
* the corresponding free.
*
* @{
*/
/**
* 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;
/**
* Allocate a buffer of `len` bytes.
*
* Uses the provided allocator, or the default allocator if NULL is passed.
* The returned buffer must be freed with ghostty_free() using the same
* allocator.
*
* @param allocator Pointer to the allocator to use, or NULL for the default
* @param len Number of bytes to allocate
* @return Pointer to the allocated buffer, or NULL if allocation failed
*
* @ingroup allocator
*/
GHOSTTY_API uint8_t* ghostty_alloc(const GhosttyAllocator* allocator, size_t len);
/**
* Free memory that was allocated by a libghostty-vt function.
*
* Use this to free buffers returned by functions such as
* ghostty_formatter_format_alloc(). Pass the same allocator that was
* used for the allocation, or NULL if the default allocator was used.
*
* On platforms where the library's internal allocator differs from the
* consumer's C runtime (e.g. Windows, where Zig's libc and MSVC's CRT
* maintain separate heaps), calling the standard C free() on memory
* allocated by the library causes undefined behavior. This function
* guarantees the correct allocator is used regardless of platform.
*
* It is safe to pass a NULL pointer; the call is a no-op in that case.
*
* @param allocator Pointer to the allocator that was used to allocate the
* memory, or NULL if the default allocator was used
* @param ptr Pointer to the memory to free (may be NULL)
* @param len Length of the allocation in bytes (must match the original
* allocation size)
*
* @ingroup allocator
*/
GHOSTTY_API void ghostty_free(const GhosttyAllocator* allocator, uint8_t* ptr, size_t len);
/** @} */
#endif /* GHOSTTY_VT_ALLOCATOR_H */
@@ -0,0 +1,150 @@
/**
* @file build_info.h
*
* Build info - query compile-time build configuration of libghostty-vt.
*/
#ifndef GHOSTTY_VT_BUILD_INFO_H
#define GHOSTTY_VT_BUILD_INFO_H
/** @defgroup build_info Build Info
*
* Query compile-time build configuration of libghostty-vt.
*
* These values reflect the options the library was built with and are
* constant for the lifetime of the process.
*
* ## Basic Usage
*
* Use ghostty_build_info() to query individual build options:
*
* @snippet c-vt-build-info/src/main.c build-info-query
*
* @{
*/
#include <stddef.h>
#include <stdbool.h>
#include <ghostty/vt/types.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* Build optimization mode.
*/
typedef enum GHOSTTY_ENUM_TYPED {
GHOSTTY_OPTIMIZE_DEBUG = 0,
GHOSTTY_OPTIMIZE_RELEASE_SAFE = 1,
GHOSTTY_OPTIMIZE_RELEASE_SMALL = 2,
GHOSTTY_OPTIMIZE_RELEASE_FAST = 3,
GHOSTTY_OPTIMIZE_MODE_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
} GhosttyOptimizeMode;
/**
* Build info data types that can be queried.
*
* Each variant documents the expected output pointer type.
*/
typedef enum GHOSTTY_ENUM_TYPED {
/** Invalid data type. Never results in any data extraction. */
GHOSTTY_BUILD_INFO_INVALID = 0,
/**
* Whether SIMD-accelerated code paths are enabled.
*
* Output type: bool *
*/
GHOSTTY_BUILD_INFO_SIMD = 1,
/**
* Whether Kitty graphics protocol support is available.
*
* Output type: bool *
*/
GHOSTTY_BUILD_INFO_KITTY_GRAPHICS = 2,
/**
* Whether tmux control mode support is available.
*
* Output type: bool *
*/
GHOSTTY_BUILD_INFO_TMUX_CONTROL_MODE = 3,
/**
* The optimization mode the library was built with.
*
* Output type: GhosttyOptimizeMode *
*/
GHOSTTY_BUILD_INFO_OPTIMIZE = 4,
/**
* The full version string (e.g. "1.2.3" or "1.2.3-dev+abcdef").
*
* Output type: GhosttyString *
*/
GHOSTTY_BUILD_INFO_VERSION_STRING = 5,
/**
* The major version number.
*
* Output type: size_t *
*/
GHOSTTY_BUILD_INFO_VERSION_MAJOR = 6,
/**
* The minor version number.
*
* Output type: size_t *
*/
GHOSTTY_BUILD_INFO_VERSION_MINOR = 7,
/**
* The patch version number.
*
* Output type: size_t *
*/
GHOSTTY_BUILD_INFO_VERSION_PATCH = 8,
/**
* The pre metadata string (e.g. "alpha", "beta", "dev"). Has zero length if
* no pre metadata is present.
*
* Output type: GhosttyString *
*/
GHOSTTY_BUILD_INFO_VERSION_PRE = 9,
/**
* The build metadata string (e.g. commit hash). Has zero length if
* no build metadata is present.
*
* Output type: GhosttyString *
*/
GHOSTTY_BUILD_INFO_VERSION_BUILD = 10,
GHOSTTY_BUILD_INFO_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
} GhosttyBuildInfo;
/**
* Query a compile-time build configuration value.
*
* The caller must pass a pointer to the correct output type for the
* requested data (see GhosttyBuildInfo variants for types).
*
* @param data The build info field to query
* @param out Pointer to store the result (type depends on data parameter)
* @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if the
* data type is invalid
*
* @ingroup build_info
*/
GHOSTTY_API GhosttyResult ghostty_build_info(GhosttyBuildInfo data, void *out);
#ifdef __cplusplus
}
#endif
/** @} */
#endif /* GHOSTTY_VT_BUILD_INFO_H */
@@ -0,0 +1,97 @@
/**
* @file color.h
*
* Color types and utilities.
*/
#ifndef GHOSTTY_VT_COLOR_H
#define GHOSTTY_VT_COLOR_H
#include <stdint.h>
#include <ghostty/vt/types.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
*/
GHOSTTY_API 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,151 @@
/**
* @file device.h
*
* Device types used by the terminal for device status and device attribute
* queries.
*/
#ifndef GHOSTTY_VT_DEVICE_H
#define GHOSTTY_VT_DEVICE_H
#include <stddef.h>
#include <stdint.h>
/* DA1 conformance levels (Pp parameter). */
#define GHOSTTY_DA_CONFORMANCE_VT100 1
#define GHOSTTY_DA_CONFORMANCE_VT101 1
#define GHOSTTY_DA_CONFORMANCE_VT102 6
#define GHOSTTY_DA_CONFORMANCE_VT125 12
#define GHOSTTY_DA_CONFORMANCE_VT131 7
#define GHOSTTY_DA_CONFORMANCE_VT132 4
#define GHOSTTY_DA_CONFORMANCE_VT220 62
#define GHOSTTY_DA_CONFORMANCE_VT240 62
#define GHOSTTY_DA_CONFORMANCE_VT320 63
#define GHOSTTY_DA_CONFORMANCE_VT340 63
#define GHOSTTY_DA_CONFORMANCE_VT420 64
#define GHOSTTY_DA_CONFORMANCE_VT510 65
#define GHOSTTY_DA_CONFORMANCE_VT520 65
#define GHOSTTY_DA_CONFORMANCE_VT525 65
#define GHOSTTY_DA_CONFORMANCE_LEVEL_2 62
#define GHOSTTY_DA_CONFORMANCE_LEVEL_3 63
#define GHOSTTY_DA_CONFORMANCE_LEVEL_4 64
#define GHOSTTY_DA_CONFORMANCE_LEVEL_5 65
/* DA1 feature codes (Ps parameters). */
#define GHOSTTY_DA_FEATURE_COLUMNS_132 1
#define GHOSTTY_DA_FEATURE_PRINTER 2
#define GHOSTTY_DA_FEATURE_REGIS 3
#define GHOSTTY_DA_FEATURE_SIXEL 4
#define GHOSTTY_DA_FEATURE_SELECTIVE_ERASE 6
#define GHOSTTY_DA_FEATURE_USER_DEFINED_KEYS 8
#define GHOSTTY_DA_FEATURE_NATIONAL_REPLACEMENT 9
#define GHOSTTY_DA_FEATURE_TECHNICAL_CHARACTERS 15
#define GHOSTTY_DA_FEATURE_LOCATOR 16
#define GHOSTTY_DA_FEATURE_TERMINAL_STATE 17
#define GHOSTTY_DA_FEATURE_WINDOWING 18
#define GHOSTTY_DA_FEATURE_HORIZONTAL_SCROLLING 21
#define GHOSTTY_DA_FEATURE_ANSI_COLOR 22
#define GHOSTTY_DA_FEATURE_RECTANGULAR_EDITING 28
#define GHOSTTY_DA_FEATURE_ANSI_TEXT_LOCATOR 29
#define GHOSTTY_DA_FEATURE_CLIPBOARD 52
/* DA2 device type identifiers (Pp parameter). */
#define GHOSTTY_DA_DEVICE_TYPE_VT100 0
#define GHOSTTY_DA_DEVICE_TYPE_VT220 1
#define GHOSTTY_DA_DEVICE_TYPE_VT240 2
#define GHOSTTY_DA_DEVICE_TYPE_VT330 18
#define GHOSTTY_DA_DEVICE_TYPE_VT340 19
#define GHOSTTY_DA_DEVICE_TYPE_VT320 24
#define GHOSTTY_DA_DEVICE_TYPE_VT382 32
#define GHOSTTY_DA_DEVICE_TYPE_VT420 41
#define GHOSTTY_DA_DEVICE_TYPE_VT510 61
#define GHOSTTY_DA_DEVICE_TYPE_VT520 64
#define GHOSTTY_DA_DEVICE_TYPE_VT525 65
#ifdef __cplusplus
extern "C" {
#endif
/**
* Color scheme reported in response to a CSI ? 996 n query.
*
* @ingroup terminal
*/
typedef enum GHOSTTY_ENUM_TYPED {
GHOSTTY_COLOR_SCHEME_LIGHT = 0,
GHOSTTY_COLOR_SCHEME_DARK = 1,
GHOSTTY_COLOR_SCHEME_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
} GhosttyColorScheme;
/**
* Primary device attributes (DA1) response data.
*
* Returned as part of GhosttyDeviceAttributes in response to a CSI c query.
* The conformance_level is the Pp parameter and features contains the Ps
* feature codes.
*
* @ingroup terminal
*/
typedef struct {
/** Conformance level (Pp parameter). E.g. 62 for VT220. */
uint16_t conformance_level;
/** DA1 feature codes. Only the first num_features entries are valid. */
uint16_t features[64];
/** Number of valid entries in the features array. */
size_t num_features;
} GhosttyDeviceAttributesPrimary;
/**
* Secondary device attributes (DA2) response data.
*
* Returned as part of GhosttyDeviceAttributes in response to a CSI > c query.
* Response format: CSI > Pp ; Pv ; Pc c
*
* @ingroup terminal
*/
typedef struct {
/** Terminal type identifier (Pp). E.g. 1 for VT220. */
uint16_t device_type;
/** Firmware/patch version number (Pv). */
uint16_t firmware_version;
/** ROM cartridge registration number (Pc). Always 0 for emulators. */
uint16_t rom_cartridge;
} GhosttyDeviceAttributesSecondary;
/**
* Tertiary device attributes (DA3) response data.
*
* Returned as part of GhosttyDeviceAttributes in response to a CSI = c query.
* Response format: DCS ! | D...D ST (DECRPTUI).
*
* @ingroup terminal
*/
typedef struct {
/** Unit ID encoded as 8 uppercase hex digits in the response. */
uint32_t unit_id;
} GhosttyDeviceAttributesTertiary;
/**
* Device attributes response data for all three DA levels.
*
* Filled by the device_attributes callback in response to CSI c,
* CSI > c, or CSI = c queries. The terminal uses whichever sub-struct
* matches the request type.
*
* @ingroup terminal
*/
typedef struct {
GhosttyDeviceAttributesPrimary primary;
GhosttyDeviceAttributesSecondary secondary;
GhosttyDeviceAttributesTertiary tertiary;
} GhosttyDeviceAttributes;
#ifdef __cplusplus
}
#endif
#endif /* GHOSTTY_VT_DEVICE_H */
@@ -0,0 +1,76 @@
/**
* @file focus.h
*
* Focus encoding - encode focus in/out events into terminal escape sequences.
*/
#ifndef GHOSTTY_VT_FOCUS_H
#define GHOSTTY_VT_FOCUS_H
/** @defgroup focus Focus Encoding
*
* Utilities for encoding focus gained/lost events into terminal escape
* sequences (CSI I / CSI O) for focus reporting mode (mode 1004).
*
* ## Basic Usage
*
* Use ghostty_focus_encode() to encode a focus event into a caller-provided
* buffer. If the buffer is too small, the function returns
* GHOSTTY_OUT_OF_SPACE and sets the required size in the output parameter.
*
* ## Example
*
* @snippet c-vt-encode-focus/src/main.c focus-encode
*
* @{
*/
#include <stddef.h>
#include <ghostty/vt/types.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* Focus event types for focus reporting mode (mode 1004).
*/
typedef enum GHOSTTY_ENUM_TYPED {
/** Terminal window gained focus */
GHOSTTY_FOCUS_GAINED = 0,
/** Terminal window lost focus */
GHOSTTY_FOCUS_LOST = 1,
GHOSTTY_FOCUS_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
} GhosttyFocusEvent;
/**
* Encode a focus event into a terminal escape sequence.
*
* Encodes a focus gained (CSI I) or focus lost (CSI O) report into the
* provided buffer.
*
* If the buffer is too small, the function returns GHOSTTY_OUT_OF_SPACE
* and writes the required buffer size to @p out_written. The caller can
* then retry with a sufficiently sized buffer.
*
* @param event The focus event to encode
* @param buf Output buffer to write the encoded sequence into (may be NULL)
* @param buf_len Size of the output buffer in bytes
* @param[out] out_written On success, the number of bytes written. On
* GHOSTTY_OUT_OF_SPACE, the required buffer size.
* @return GHOSTTY_SUCCESS on success, GHOSTTY_OUT_OF_SPACE if the buffer
* is too small
*/
GHOSTTY_API GhosttyResult ghostty_focus_encode(
GhosttyFocusEvent event,
char* buf,
size_t buf_len,
size_t* out_written);
#ifdef __cplusplus
}
#endif
/** @} */
#endif /* GHOSTTY_VT_FOCUS_H */
@@ -0,0 +1,207 @@
/**
* @file formatter.h
*
* Format terminal content as plain text, VT sequences, or HTML.
*/
#ifndef GHOSTTY_VT_FORMATTER_H
#define GHOSTTY_VT_FORMATTER_H
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <ghostty/vt/allocator.h>
#include <ghostty/vt/selection.h>
#include <ghostty/vt/types.h>
#include <ghostty/vt/terminal.h>
#ifdef __cplusplus
extern "C" {
#endif
/** @defgroup formatter Formatter
*
* Format terminal content as plain text, VT sequences, or HTML.
*
* A formatter captures a reference to a terminal and formatting options.
* It can be used repeatedly to produce output that reflects the current
* terminal state at the time of each format call.
*
* The terminal must outlive the formatter.
*
* @{
*/
/**
* Extra screen state to include in styled output.
*
* @ingroup formatter
*/
typedef struct {
/** Size of this struct in bytes. Must be set to sizeof(GhosttyFormatterScreenExtra). */
size_t size;
/** Emit cursor position using CUP (CSI H). */
bool cursor;
/** Emit current SGR style state based on the cursor's active style_id. */
bool style;
/** Emit current hyperlink state using OSC 8 sequences. */
bool hyperlink;
/** Emit character protection mode using DECSCA. */
bool protection;
/** Emit Kitty keyboard protocol state using CSI > u and CSI = sequences. */
bool kitty_keyboard;
/** Emit character set designations and invocations. */
bool charsets;
} GhosttyFormatterScreenExtra;
/**
* Extra terminal state to include in styled output.
*
* @ingroup formatter
*/
typedef struct {
/** Size of this struct in bytes. Must be set to sizeof(GhosttyFormatterTerminalExtra). */
size_t size;
/** Emit the palette using OSC 4 sequences. */
bool palette;
/** Emit terminal modes that differ from their defaults using CSI h/l. */
bool modes;
/** Emit scrolling region state using DECSTBM and DECSLRM sequences. */
bool scrolling_region;
/** Emit tabstop positions by clearing all tabs and setting each one. */
bool tabstops;
/** Emit the present working directory using OSC 7. */
bool pwd;
/** Emit keyboard modes such as ModifyOtherKeys. */
bool keyboard;
/** Screen-level extras. */
GhosttyFormatterScreenExtra screen;
} GhosttyFormatterTerminalExtra;
/**
* Options for creating a terminal formatter.
*
* @ingroup formatter
*/
typedef struct {
/** Size of this struct in bytes. Must be set to sizeof(GhosttyFormatterTerminalOptions). */
size_t size;
/** Output format to emit. */
GhosttyFormatterFormat emit;
/** Whether to unwrap soft-wrapped lines. */
bool unwrap;
/** Whether to trim trailing whitespace on non-blank lines. */
bool trim;
/** Extra terminal state to include in styled output. */
GhosttyFormatterTerminalExtra extra;
/** Optional selection to restrict output to a range.
* If NULL, the entire screen is formatted. */
const GhosttySelection *selection;
} GhosttyFormatterTerminalOptions;
/**
* Create a formatter for a terminal's active screen.
*
* The terminal must outlive the formatter. The formatter stores a borrowed
* reference to the terminal and reads its current state on each format call.
*
* @param allocator Pointer to allocator, or NULL to use the default allocator
* @param formatter Pointer to store the created formatter handle
* @param terminal The terminal to format (must not be NULL)
* @param options Formatting options
* @return GHOSTTY_SUCCESS on success, or an error code on failure
*
* @ingroup formatter
*/
GHOSTTY_API GhosttyResult ghostty_formatter_terminal_new(
const GhosttyAllocator* allocator,
GhosttyFormatter* formatter,
GhosttyTerminal terminal,
GhosttyFormatterTerminalOptions options);
/**
* Run the formatter and produce output into the caller-provided buffer.
*
* Each call formats the current terminal state. Pass NULL for buf to
* query the required buffer size without writing any output; in that case
* out_written receives the required size and the return value is
* GHOSTTY_OUT_OF_SPACE.
*
* If the buffer is too small, returns GHOSTTY_OUT_OF_SPACE and sets
* out_written to the required size. The caller can then retry with a
* larger buffer.
*
* @param formatter The formatter handle (must not be NULL)
* @param buf Pointer to the output buffer, or NULL to query size
* @param buf_len Length of the output buffer in bytes
* @param out_written Pointer to receive the number of bytes written,
* or the required size on failure
* @return GHOSTTY_SUCCESS on success, or an error code on failure
*
* @ingroup formatter
*/
GHOSTTY_API GhosttyResult ghostty_formatter_format_buf(GhosttyFormatter formatter,
uint8_t* buf,
size_t buf_len,
size_t* out_written);
/**
* Run the formatter and return an allocated buffer with the output.
*
* Each call formats the current terminal state. The buffer is allocated
* using the provided allocator (or the default allocator if NULL).
* The caller is responsible for freeing the returned buffer with
* ghostty_free(), passing the same allocator (or NULL for the default)
* that was used for the allocation.
*
* @param formatter The formatter handle (must not be NULL)
* @param allocator Pointer to allocator, or NULL to use the default allocator
* @param out_ptr Pointer to receive the allocated buffer
* @param out_len Pointer to receive the length of the output in bytes
* @return GHOSTTY_SUCCESS on success, GHOSTTY_OUT_OF_MEMORY on allocation
* failure
*
* @ingroup formatter
*/
GHOSTTY_API GhosttyResult ghostty_formatter_format_alloc(GhosttyFormatter formatter,
const GhosttyAllocator* allocator,
uint8_t** out_ptr,
size_t* out_len);
/**
* Free a formatter instance.
*
* Releases all resources associated with the formatter. After this call,
* the formatter handle becomes invalid.
*
* @param formatter The formatter handle to free (may be NULL)
*
* @ingroup formatter
*/
GHOSTTY_API void ghostty_formatter_free(GhosttyFormatter formatter);
/** @} */
#ifdef __cplusplus
}
#endif
#endif /* GHOSTTY_VT_FORMATTER_H */
@@ -0,0 +1,212 @@
/**
* @file grid_ref.h
*
* Terminal grid reference type for referencing a resolved position in the
* terminal grid.
*/
#ifndef GHOSTTY_VT_GRID_REF_H
#define GHOSTTY_VT_GRID_REF_H
#include <stddef.h>
#include <stdint.h>
#include <ghostty/vt/types.h>
#include <ghostty/vt/screen.h>
#include <ghostty/vt/style.h>
#ifdef __cplusplus
extern "C" {
#endif
/** @defgroup grid_ref Grid Reference
*
* A grid reference is a reference to a specific cell position in the
* terminal. Obtain a grid reference from `ghostty_terminal_grid_ref`
* for untracked or `ghostty_terminal_grid_ref_track` for tracked. Untracked
* vs tracked is explained next.
*
* Important: The grid reference APIs are not meant to be used as the core of a render
* loop. They are not built to sustain the framerates needed for rendering large
* screens. Use the render state API for that.
*
* ## Untracked vs Tracked References
*
* ### Untracked Reference
*
* An untracked grid reference is a value type that snapshots a specific
* cell. It is only valid until the next update to the terminal instance.
* There is no guarantee that it will remain valid after any operation,
* even if a seemingly unrelated part of the grid is changed. These are meant
* to be read and have their values cached immediately after obtaining it.
*
* An untracked grid reference has a performance cost in its initial lookup,
* but doesn't affect the ongoing performance of the terminal in any way,
* since it is a one-time snapshot.
*
* ### Tracked Reference
*
* A tracked grid reference follows its cell across normal screen operations.
* For example scrolling, scrollback pruning, resize/reflow, and other
* terminal mutations update the tracked reference automatically.
*
* A tracked reference can still lose its original semantic location. This can
* happen when the underlying grid is reset, pruned, or otherwise discarded in a
* way that cannot be mapped to a meaningful new cell. In that state,
* ghostty_tracked_grid_ref_has_value() returns false and
* ghostty_tracked_grid_ref_snapshot() / ghostty_tracked_grid_ref_point() return
* GHOSTTY_NO_VALUE. The handle remains valid, and callers may move it to a new
* point with ghostty_tracked_grid_ref_set().
*
* To read cell data from a tracked reference, first snapshot it with
* ghostty_tracked_grid_ref_snapshot(). The returned `GhosttyGridRef` is again
* an untracked reference and follows the same short lifetime rules as any other
* untracked grid reference.
*
* A tracked reference belongs to the terminal screen/page-list that was active
* when it was created or last set. Converting it to a point uses that owning
* screen/page-list, even if the terminal has since switched between primary and
* alternate screens. Calling ghostty_tracked_grid_ref_set() resolves the new
* point against the terminal's currently active screen/page-list and may move
* the tracked reference between screens.
*
* Tracked references are owned by the caller and must be freed with
* ghostty_tracked_grid_ref_free(). If the terminal that created a tracked
* reference is freed first, the handle remains valid only for tracked-grid-ref
* APIs: it reports no value and can still be freed.
*
* Each tracked reference adds bookkeeping to terminal mutations. Use them
* sparingly for long-lived anchors such as selections, search state, marks,
* or application-side bookmarks.
*
* ## Lifetime
*
* An untracked reference is a snapshot. It doesn't need to be freed.
* The safety of accessing the value is documented explicitly above: it
* is only safe to access any data until the next terminal mutating
* operation (including free).
*
* A tracked reference is allocated and must be freed when it is no
* longer needed. A tracked reference may outlive the terminal that created it;
* after terminal free, it reports no value and can still be freed.
*
* ## Examples
*
* @snippet c-vt-grid-traverse/src/main.c grid-ref-traverse
* @snippet c-vt-grid-ref-tracked/src/main.c grid-ref-tracked
*
* @{
*/
/**
* A resolved reference to a terminal cell position.
*
* This is a sized struct. Use GHOSTTY_INIT_SIZED() to initialize it.
*
* @ingroup grid_ref
*/
typedef struct {
size_t size;
void *node;
uint16_t x;
uint16_t y;
} GhosttyGridRef;
/**
* Get the cell from a grid reference.
*
* @param ref Pointer to the grid reference
* @param[out] out_cell On success, set to the cell at the ref's position (may be NULL)
* @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if the ref's
* node is NULL
*
* @ingroup grid_ref
*/
GHOSTTY_API GhosttyResult ghostty_grid_ref_cell(const GhosttyGridRef *ref,
GhosttyCell *out_cell);
/**
* Get the row from a grid reference.
*
* @param ref Pointer to the grid reference
* @param[out] out_row On success, set to the row at the ref's position (may be NULL)
* @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if the ref's
* node is NULL
*
* @ingroup grid_ref
*/
GHOSTTY_API GhosttyResult ghostty_grid_ref_row(const GhosttyGridRef *ref,
GhosttyRow *out_row);
/**
* Get the grapheme cluster codepoints for the cell at the grid reference's
* position.
*
* Writes the full grapheme cluster (the cell's primary codepoint followed by
* any combining codepoints) into the provided buffer. If the cell has no text,
* out_len is set to 0 and GHOSTTY_SUCCESS is returned.
*
* If the buffer is too small (or NULL), the function returns
* GHOSTTY_OUT_OF_SPACE and writes the required number of codepoints to
* out_len. The caller can then retry with a sufficiently sized buffer.
*
* @param ref Pointer to the grid reference
* @param buf Output buffer of uint32_t codepoints (may be NULL)
* @param buf_len Number of uint32_t elements in the buffer
* @param[out] out_len On success, the number of codepoints written. On
* GHOSTTY_OUT_OF_SPACE, the required buffer size in codepoints.
* @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if the ref's
* node is NULL, GHOSTTY_OUT_OF_SPACE if the buffer is too small
*
* @ingroup grid_ref
*/
GHOSTTY_API GhosttyResult ghostty_grid_ref_graphemes(const GhosttyGridRef *ref,
uint32_t *buf,
size_t buf_len,
size_t *out_len);
/**
* Get the hyperlink URI for the cell at the grid reference's position.
*
* Writes the URI bytes into the provided buffer. If the cell has no
* hyperlink, out_len is set to 0 and GHOSTTY_SUCCESS is returned.
*
* If the buffer is too small (or NULL), the function returns
* GHOSTTY_OUT_OF_SPACE and writes the required number of bytes to
* out_len. The caller can then retry with a sufficiently sized buffer.
*
* @param ref Pointer to the grid reference
* @param buf Output buffer for the URI bytes (may be NULL)
* @param buf_len Size of the output buffer in bytes
* @param[out] out_len On success, the number of bytes written. On
* GHOSTTY_OUT_OF_SPACE, the required buffer size in bytes.
* @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if the ref's
* node is NULL, GHOSTTY_OUT_OF_SPACE if the buffer is too small
*
* @ingroup grid_ref
*/
GHOSTTY_API GhosttyResult ghostty_grid_ref_hyperlink_uri(
const GhosttyGridRef *ref,
uint8_t *buf,
size_t buf_len,
size_t *out_len);
/**
* Get the style of the cell at the grid reference's position.
*
* @param ref Pointer to the grid reference
* @param[out] out_style On success, set to the cell's style (may be NULL)
* @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if the ref's
* node is NULL
*
* @ingroup grid_ref
*/
GHOSTTY_API GhosttyResult ghostty_grid_ref_style(const GhosttyGridRef *ref,
GhosttyStyle *out_style);
/** @} */
#ifdef __cplusplus
}
#endif
#endif /* GHOSTTY_VT_GRID_REF_H */
@@ -0,0 +1,139 @@
/**
* @file grid_ref_tracked.h
*
* Tracked terminal grid references.
*/
#ifndef GHOSTTY_VT_GRID_REF_TRACKED_H
#define GHOSTTY_VT_GRID_REF_TRACKED_H
#include <stdbool.h>
#include <ghostty/vt/types.h>
#include <ghostty/vt/grid_ref.h>
#include <ghostty/vt/point.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* Tracked grid references are owned grid references that move with the
* terminal. See @ref grid_ref for the full overview of tracked and untracked
* grid reference behavior.
*
* @ingroup grid_ref
*/
/**
* Free a tracked grid reference.
*
* Passing NULL is allowed and has no effect. A tracked reference may be freed
* after the terminal that created it is freed.
*
* @param ref Tracked grid reference to free.
*
* @ingroup grid_ref
*/
GHOSTTY_API void ghostty_tracked_grid_ref_free(GhosttyTrackedGridRef ref);
/**
* Return whether a tracked grid reference currently has a meaningful value.
*
* If the terminal that created the tracked reference has been freed, this
* returns false.
*
* @param ref Tracked grid reference.
* @return true if the reference currently has a meaningful value.
*
* @ingroup grid_ref
*/
GHOSTTY_API bool ghostty_tracked_grid_ref_has_value(
GhosttyTrackedGridRef ref);
/**
* Convert a tracked grid reference to a point in the requested coordinate
* space.
*
* This is the tracked equivalent of ghostty_terminal_point_from_grid_ref().
* Unlike snapshotting, this does not expose an intermediate untracked
* GhosttyGridRef.
*
* A tracked reference is resolved against the terminal screen/page-list that
* currently owns the reference. If the terminal has switched between primary
* and alternate screens since the reference was created or last set, this may
* be different from the terminal's currently active screen.
*
* If the tracked reference no longer has a meaningful value, this returns
* GHOSTTY_NO_VALUE. GHOSTTY_NO_VALUE is also returned when the reference cannot
* be represented in the requested coordinate space, including after the
* terminal that created the tracked reference has been freed.
*
* @param ref Tracked grid reference.
* @param tag Coordinate space to convert into.
* @param[out] out_point On success, receives the coordinate. May be NULL.
* @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if ref is invalid,
* or GHOSTTY_NO_VALUE if there is no representable value.
*
* @ingroup grid_ref
*/
GHOSTTY_API GhosttyResult ghostty_tracked_grid_ref_point(
GhosttyTrackedGridRef ref,
GhosttyPointTag tag,
GhosttyPointCoordinate *out_point);
/**
* Move an existing tracked grid reference to a new terminal point.
*
* On success, the tracked reference begins tracking the new point and any prior
* "no value" state is cleared. On GHOSTTY_OUT_OF_MEMORY, the original tracked
* reference is left unchanged.
*
* The terminal must be the same terminal that created the tracked reference.
* The point is resolved against the terminal screen/page-list that is active at
* the time this function is called. If the terminal has switched between
* primary and alternate screens, this may move the tracked reference from one
* screen/page-list to the other.
*
* @param ref Tracked grid reference.
* @param terminal Terminal instance that owns the reference.
* @param point New point to track.
* @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if ref, terminal,
* or point is invalid, or GHOSTTY_OUT_OF_MEMORY if allocation fails.
*
* @ingroup grid_ref
*/
GHOSTTY_API GhosttyResult ghostty_tracked_grid_ref_set(
GhosttyTrackedGridRef ref,
GhosttyTerminal terminal,
GhosttyPoint point);
/**
* Snapshot a tracked grid reference into a regular GhosttyGridRef.
*
* The returned GhosttyGridRef is an untracked snapshot and has the same
* lifetime rules as ghostty_terminal_grid_ref(): it is only valid until the
* next terminal update. Snapshot immediately before calling
* ghostty_grid_ref_cell(), ghostty_grid_ref_row(),
* ghostty_grid_ref_graphemes(), ghostty_grid_ref_hyperlink_uri(), or
* ghostty_grid_ref_style().
*
* If the tracked reference no longer has a meaningful value, this returns
* GHOSTTY_NO_VALUE. This includes references whose owning terminal has been
* freed.
*
* @param ref Tracked grid reference.
* @param[out] out_ref On success, receives an untracked snapshot. May be NULL.
* @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if ref is invalid,
* or GHOSTTY_NO_VALUE if the tracked location was discarded.
*
* @ingroup grid_ref
*/
GHOSTTY_API GhosttyResult ghostty_tracked_grid_ref_snapshot(
GhosttyTrackedGridRef ref,
GhosttyGridRef *out_ref);
#ifdef __cplusplus
}
#endif
#endif /* GHOSTTY_VT_GRID_REF_TRACKED_H */
@@ -0,0 +1,73 @@
/**
* @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()
* or ghostty_key_encoder_setopt_from_terminal() if you have a
* GhosttyTerminal.
* 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
*
* For a complete working example, see example/c-vt-encode-key in the
* repository.
*
* ## Example
*
* @snippet c-vt-encode-key/src/main.c key-encode
*
* ## Example: Encoding with Terminal State
*
* When you have a GhosttyTerminal, you can sync its modes (cursor key
* application, Kitty flags, etc.) into the encoder automatically:
*
* @code{.c}
* // Create a terminal and feed it some VT data that changes modes
* GhosttyTerminal terminal;
* ghostty_terminal_new(NULL, &terminal,
* (GhosttyTerminalOptions){.cols = 80, .rows = 24, .max_scrollback = 0});
*
* // Application might write data that enables Kitty keyboard protocol, etc.
* ghostty_terminal_vt_write(terminal, vt_data, vt_len);
*
* // Create an encoder and sync its options from the terminal
* GhosttyKeyEncoder encoder;
* ghostty_key_encoder_new(NULL, &encoder);
* ghostty_key_encoder_setopt_from_terminal(encoder, terminal);
*
* // Encode a key event using the terminal-derived options
* char buf[128];
* size_t written = 0;
* ghostty_key_encoder_encode(encoder, event, buf, sizeof(buf), &written);
*
* ghostty_key_encoder_free(encoder);
* ghostty_terminal_free(terminal);
* @endcode
*
* @{
*/
#include <ghostty/vt/key/event.h>
#include <ghostty/vt/key/encoder.h>
/** @} */
#endif /* GHOSTTY_VT_KEY_H */
@@ -0,0 +1,255 @@
/**
* @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/types.h>
#include <ghostty/vt/allocator.h>
#include <ghostty/vt/terminal.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 GhosttyKeyEncoderImpl *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 GHOSTTY_ENUM_TYPED {
/** 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,
GHOSTTY_OPTION_AS_ALT_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
} 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 GHOSTTY_ENUM_TYPED {
/** 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,
/** Backarrow key mode (value: bool)
* See https://vt100.net/dec/ek-vt3xx-tp-002.pdf page 170
* If `false` (the default), `backspace` emits 0x7f
* If `true`, `backspace` emits 0x08
*/
GHOSTTY_KEY_ENCODER_OPT_BACKARROW_KEY_MODE = 7,
GHOSTTY_KEY_ENCODER_OPT_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
} 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
*/
GHOSTTY_API 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
*/
GHOSTTY_API 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).
*
* If you are using a terminal instance, you can set the key encoding
* options based on the active terminal state (e.g. legacy vs Kitty mode
* and associated flags) with ghostty_key_encoder_setopt_from_terminal().
*
* 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
*/
GHOSTTY_API void ghostty_key_encoder_setopt(GhosttyKeyEncoder encoder, GhosttyKeyEncoderOption option, const void *value);
/**
* Set encoder options from a terminal's current state.
*
* Reads the terminal's current modes and flags and applies them to the
* encoder's options. This sets cursor key application mode, keypad mode,
* alt escape prefix, modifyOtherKeys state, and Kitty keyboard protocol
* flags from the terminal state.
*
* Note that the `macos_option_as_alt` option cannot be determined from
* terminal state and is reset to `GHOSTTY_OPTION_AS_ALT_FALSE` by this
* call. Use ghostty_key_encoder_setopt() to set it afterward if needed.
*
* @param encoder The encoder handle, must not be NULL
* @param terminal The terminal handle, must not be NULL
*
* @ingroup key
*/
GHOSTTY_API void ghostty_key_encoder_setopt_from_terminal(GhosttyKeyEncoder encoder, GhosttyTerminal terminal);
/**
* 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_SPACE
* 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_SPACE 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_SPACE)
* size_t required = 0;
* GhosttyResult result = ghostty_key_encoder_encode(encoder, event, NULL, 0, &required);
* assert(result == GHOSTTY_OUT_OF_SPACE);
*
* // 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_SPACE) {
* // 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
*/
GHOSTTY_API 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,482 @@
/**
* @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/types.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 GhosttyKeyEventImpl *GhosttyKeyEvent;
/**
* Keyboard input event types.
*
* @ingroup key
*/
typedef enum GHOSTTY_ENUM_TYPED {
/** 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,
GHOSTTY_KEY_ACTION_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
} 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_ENUM_TYPED {
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,
GHOSTTY_KEY_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
} 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
*/
GHOSTTY_API 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
*/
GHOSTTY_API 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
*/
GHOSTTY_API 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
*/
GHOSTTY_API 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
*/
GHOSTTY_API 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
*/
GHOSTTY_API 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
*/
GHOSTTY_API 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
*/
GHOSTTY_API 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
*/
GHOSTTY_API 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
*/
GHOSTTY_API 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
*/
GHOSTTY_API 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
*/
GHOSTTY_API bool ghostty_key_event_get_composing(GhosttyKeyEvent event);
/**
* Set the UTF-8 text generated by the key for the current keyboard layout.
*
* Must contain the unmodified character before any Ctrl/Meta transformations.
* The encoder derives modifier sequences from the logical key and mods
* bitmask, not from this text. Do not pass C0 control characters
* (U+0000-U+001F, U+007F) or platform function key codes (e.g. macOS PUA
* U+F700-U+F8FF); pass NULL instead and let the encoder use the logical key.
*
* 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
*/
GHOSTTY_API 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
*/
GHOSTTY_API 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
*/
GHOSTTY_API 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
*/
GHOSTTY_API uint32_t ghostty_key_event_get_unshifted_codepoint(GhosttyKeyEvent event);
#endif /* GHOSTTY_VT_KEY_EVENT_H */
@@ -0,0 +1,775 @@
/**
* @file kitty_graphics.h
*
* Kitty graphics protocol
*
* See @ref kitty_graphics for a full usage guide.
*/
#ifndef GHOSTTY_VT_KITTY_GRAPHICS_H
#define GHOSTTY_VT_KITTY_GRAPHICS_H
#include <stdbool.h>
#include <stdint.h>
#include <ghostty/vt/allocator.h>
#include <ghostty/vt/selection.h>
#include <ghostty/vt/types.h>
#ifdef __cplusplus
extern "C" {
#endif
/** @defgroup kitty_graphics Kitty Graphics
*
* API for inspecting images and placements stored via the
* [Kitty graphics protocol](https://sw.kovidgoyal.net/kitty/graphics-protocol/).
*
* The central object is @ref GhosttyKittyGraphics, an opaque handle to
* the image storage associated with a terminal's active screen. From it
* you can iterate over placements and look up individual images.
*
* ## Obtaining a KittyGraphics Handle
*
* A @ref GhosttyKittyGraphics handle is obtained from a terminal via
* ghostty_terminal_get() with @ref GHOSTTY_TERMINAL_DATA_KITTY_GRAPHICS.
* The handle is borrowed from the terminal and remains valid until the
* next mutating terminal call (e.g. ghostty_terminal_vt_write() or
* ghostty_terminal_reset()).
*
* Before images can be stored, Kitty graphics must be enabled on the
* terminal by setting a non-zero storage limit with
* @ref GHOSTTY_TERMINAL_OPT_KITTY_IMAGE_STORAGE_LIMIT, and a PNG
* decoder callback must be installed via ghostty_sys_set() with
* @ref GHOSTTY_SYS_OPT_DECODE_PNG.
*
* @snippet c-vt-kitty-graphics/src/main.c kitty-graphics-decode-png
*
* ## Iterating Placements
*
* Placements are inspected through a @ref GhosttyKittyGraphicsPlacementIterator.
* The typical workflow is:
*
* 1. Create an iterator with ghostty_kitty_graphics_placement_iterator_new().
* 2. Populate it from the storage with ghostty_kitty_graphics_get() using
* @ref GHOSTTY_KITTY_GRAPHICS_DATA_PLACEMENT_ITERATOR.
* 3. Optionally filter by z-layer with
* ghostty_kitty_graphics_placement_iterator_set().
* 4. Advance with ghostty_kitty_graphics_placement_next() and read
* per-placement data with ghostty_kitty_graphics_placement_get().
* 5. For each placement, look up its image with
* ghostty_kitty_graphics_image() to access pixel data and dimensions.
* 6. Free the iterator with ghostty_kitty_graphics_placement_iterator_free().
*
* ## Looking Up Images
*
* Given an image ID (obtained from a placement via
* @ref GHOSTTY_KITTY_GRAPHICS_PLACEMENT_DATA_IMAGE_ID), call
* ghostty_kitty_graphics_image() to get a @ref GhosttyKittyGraphicsImage
* handle. From this handle, ghostty_kitty_graphics_image_get() provides
* the image dimensions, pixel format, compression, and a borrowed pointer
* to the raw pixel data.
*
* ## Rendering Helpers
*
* Several functions assist with rendering a placement:
*
* - ghostty_kitty_graphics_placement_pixel_size() — rendered pixel
* dimensions accounting for source rect and aspect ratio.
* - ghostty_kitty_graphics_placement_grid_size() — number of grid
* columns and rows the placement occupies.
* - ghostty_kitty_graphics_placement_viewport_pos() — viewport-relative
* grid position (may be negative for partially scrolled placements).
* - ghostty_kitty_graphics_placement_source_rect() — resolved source
* rectangle in pixels, clamped to image bounds.
* - ghostty_kitty_graphics_placement_rect() — bounding rectangle as a
* @ref GhosttySelection.
*
* ## Lifetime and Thread Safety
*
* All handles borrowed from the terminal (GhosttyKittyGraphics,
* GhosttyKittyGraphicsImage) are invalidated by any mutating terminal
* call. The placement iterator is independently owned and must be freed
* by the caller, but the data it yields is only valid while the
* underlying terminal is not mutated.
*
* ## Example
*
* The following example creates a terminal, sends a Kitty graphics
* image, then iterates placements and prints image metadata:
*
* @snippet c-vt-kitty-graphics/src/main.c kitty-graphics-main
*
* @{
*/
/**
* Queryable data kinds for ghostty_kitty_graphics_get().
*
* @ingroup kitty_graphics
*/
typedef enum GHOSTTY_ENUM_TYPED {
/** Invalid / sentinel value. */
GHOSTTY_KITTY_GRAPHICS_DATA_INVALID = 0,
/**
* Populate a pre-allocated placement iterator with placement data from
* the storage. Iterator data is only valid as long as the underlying
* terminal is not mutated.
*
* Output type: GhosttyKittyGraphicsPlacementIterator *
*/
GHOSTTY_KITTY_GRAPHICS_DATA_PLACEMENT_ITERATOR = 1,
GHOSTTY_KITTY_GRAPHICS_DATA_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
} GhosttyKittyGraphicsData;
/**
* Queryable data kinds for ghostty_kitty_graphics_placement_get().
*
* @ingroup kitty_graphics
*/
typedef enum GHOSTTY_ENUM_TYPED {
/** Invalid / sentinel value. */
GHOSTTY_KITTY_GRAPHICS_PLACEMENT_DATA_INVALID = 0,
/**
* The image ID this placement belongs to.
*
* Output type: uint32_t *
*/
GHOSTTY_KITTY_GRAPHICS_PLACEMENT_DATA_IMAGE_ID = 1,
/**
* The placement ID.
*
* Output type: uint32_t *
*/
GHOSTTY_KITTY_GRAPHICS_PLACEMENT_DATA_PLACEMENT_ID = 2,
/**
* Whether this is a virtual placement (unicode placeholder).
*
* Output type: bool *
*/
GHOSTTY_KITTY_GRAPHICS_PLACEMENT_DATA_IS_VIRTUAL = 3,
/**
* Pixel offset from the left edge of the cell.
*
* Output type: uint32_t *
*/
GHOSTTY_KITTY_GRAPHICS_PLACEMENT_DATA_X_OFFSET = 4,
/**
* Pixel offset from the top edge of the cell.
*
* Output type: uint32_t *
*/
GHOSTTY_KITTY_GRAPHICS_PLACEMENT_DATA_Y_OFFSET = 5,
/**
* Source rectangle x origin in pixels.
*
* Output type: uint32_t *
*/
GHOSTTY_KITTY_GRAPHICS_PLACEMENT_DATA_SOURCE_X = 6,
/**
* Source rectangle y origin in pixels.
*
* Output type: uint32_t *
*/
GHOSTTY_KITTY_GRAPHICS_PLACEMENT_DATA_SOURCE_Y = 7,
/**
* Source rectangle width in pixels (0 = full image width).
*
* Output type: uint32_t *
*/
GHOSTTY_KITTY_GRAPHICS_PLACEMENT_DATA_SOURCE_WIDTH = 8,
/**
* Source rectangle height in pixels (0 = full image height).
*
* Output type: uint32_t *
*/
GHOSTTY_KITTY_GRAPHICS_PLACEMENT_DATA_SOURCE_HEIGHT = 9,
/**
* Number of columns this placement occupies.
*
* Output type: uint32_t *
*/
GHOSTTY_KITTY_GRAPHICS_PLACEMENT_DATA_COLUMNS = 10,
/**
* Number of rows this placement occupies.
*
* Output type: uint32_t *
*/
GHOSTTY_KITTY_GRAPHICS_PLACEMENT_DATA_ROWS = 11,
/**
* Z-index for this placement.
*
* Output type: int32_t *
*/
GHOSTTY_KITTY_GRAPHICS_PLACEMENT_DATA_Z = 12,
GHOSTTY_KITTY_GRAPHICS_PLACEMENT_DATA_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
} GhosttyKittyGraphicsPlacementData;
/**
* Z-layer classification for kitty graphics placements.
*
* Based on the kitty protocol z-index conventions:
* - BELOW_BG: z < INT32_MIN/2 (drawn below cell background)
* - BELOW_TEXT: INT32_MIN/2 <= z < 0 (above background, below text)
* - ABOVE_TEXT: z >= 0 (above text)
* - ALL: no filtering (current behavior)
*
* @ingroup kitty_graphics
*/
typedef enum GHOSTTY_ENUM_TYPED {
GHOSTTY_KITTY_PLACEMENT_LAYER_ALL = 0,
GHOSTTY_KITTY_PLACEMENT_LAYER_BELOW_BG = 1,
GHOSTTY_KITTY_PLACEMENT_LAYER_BELOW_TEXT = 2,
GHOSTTY_KITTY_PLACEMENT_LAYER_ABOVE_TEXT = 3,
GHOSTTY_KITTY_PLACEMENT_LAYER_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
} GhosttyKittyPlacementLayer;
/**
* Settable options for ghostty_kitty_graphics_placement_iterator_set().
*
* @ingroup kitty_graphics
*/
typedef enum GHOSTTY_ENUM_TYPED {
/**
* Set the z-layer filter for the iterator.
*
* Input type: GhosttyKittyPlacementLayer *
*/
GHOSTTY_KITTY_GRAPHICS_PLACEMENT_ITERATOR_OPTION_LAYER = 0,
GHOSTTY_KITTY_GRAPHICS_PLACEMENT_ITERATOR_OPTION_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
} GhosttyKittyGraphicsPlacementIteratorOption;
/**
* Pixel format of a Kitty graphics image.
*
* @ingroup kitty_graphics
*/
typedef enum GHOSTTY_ENUM_TYPED {
GHOSTTY_KITTY_IMAGE_FORMAT_RGB = 0,
GHOSTTY_KITTY_IMAGE_FORMAT_RGBA = 1,
GHOSTTY_KITTY_IMAGE_FORMAT_PNG = 2,
GHOSTTY_KITTY_IMAGE_FORMAT_GRAY_ALPHA = 3,
GHOSTTY_KITTY_IMAGE_FORMAT_GRAY = 4,
GHOSTTY_KITTY_IMAGE_FORMAT_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
} GhosttyKittyImageFormat;
/**
* Compression of a Kitty graphics image.
*
* @ingroup kitty_graphics
*/
typedef enum GHOSTTY_ENUM_TYPED {
GHOSTTY_KITTY_IMAGE_COMPRESSION_NONE = 0,
GHOSTTY_KITTY_IMAGE_COMPRESSION_ZLIB_DEFLATE = 1,
GHOSTTY_KITTY_IMAGE_COMPRESSION_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
} GhosttyKittyImageCompression;
/**
* Queryable data kinds for ghostty_kitty_graphics_image_get().
*
* @ingroup kitty_graphics
*/
typedef enum GHOSTTY_ENUM_TYPED {
/** Invalid / sentinel value. */
GHOSTTY_KITTY_IMAGE_DATA_INVALID = 0,
/**
* The image ID.
*
* Output type: uint32_t *
*/
GHOSTTY_KITTY_IMAGE_DATA_ID = 1,
/**
* The image number.
*
* Output type: uint32_t *
*/
GHOSTTY_KITTY_IMAGE_DATA_NUMBER = 2,
/**
* Image width in pixels.
*
* Output type: uint32_t *
*/
GHOSTTY_KITTY_IMAGE_DATA_WIDTH = 3,
/**
* Image height in pixels.
*
* Output type: uint32_t *
*/
GHOSTTY_KITTY_IMAGE_DATA_HEIGHT = 4,
/**
* Pixel format of the image.
*
* Output type: GhosttyKittyImageFormat *
*/
GHOSTTY_KITTY_IMAGE_DATA_FORMAT = 5,
/**
* Compression of the image.
*
* Output type: GhosttyKittyImageCompression *
*/
GHOSTTY_KITTY_IMAGE_DATA_COMPRESSION = 6,
/**
* Borrowed pointer to the raw pixel data. Valid as long as the
* underlying terminal is not mutated.
*
* Output type: const uint8_t **
*/
GHOSTTY_KITTY_IMAGE_DATA_DATA_PTR = 7,
/**
* Length of the raw pixel data in bytes.
*
* Output type: size_t *
*/
GHOSTTY_KITTY_IMAGE_DATA_DATA_LEN = 8,
GHOSTTY_KITTY_IMAGE_DATA_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
} GhosttyKittyGraphicsImageData;
/**
* Combined rendering geometry for a placement in a single sized struct.
*
* Combines the results of ghostty_kitty_graphics_placement_pixel_size(),
* ghostty_kitty_graphics_placement_grid_size(),
* ghostty_kitty_graphics_placement_viewport_pos(), and
* ghostty_kitty_graphics_placement_source_rect() into one call. This is
* an optimization over calling those four functions individually,
* particularly useful in environments with high per-call overhead such
* as FFI or Cgo.
*
* This struct uses the sized-struct ABI pattern. Initialize with
* GHOSTTY_INIT_SIZED(GhosttyKittyGraphicsPlacementRenderInfo) before calling
* ghostty_kitty_graphics_placement_render_info().
*
* @ingroup kitty_graphics
*/
typedef struct {
/** Size of this struct in bytes. Must be set to sizeof(GhosttyKittyGraphicsPlacementRenderInfo). */
size_t size;
/** Rendered width in pixels. */
uint32_t pixel_width;
/** Rendered height in pixels. */
uint32_t pixel_height;
/** Number of grid columns the placement occupies. */
uint32_t grid_cols;
/** Number of grid rows the placement occupies. */
uint32_t grid_rows;
/** Viewport-relative column (may be negative for partially visible placements). */
int32_t viewport_col;
/** Viewport-relative row (may be negative for partially visible placements). */
int32_t viewport_row;
/** False when the placement is fully off-screen or virtual. */
bool viewport_visible;
/** Resolved source rectangle x origin in pixels. */
uint32_t source_x;
/** Resolved source rectangle y origin in pixels. */
uint32_t source_y;
/** Resolved source rectangle width in pixels. */
uint32_t source_width;
/** Resolved source rectangle height in pixels. */
uint32_t source_height;
} GhosttyKittyGraphicsPlacementRenderInfo;
/**
* Get data from a kitty graphics storage instance.
*
* The output pointer must be of the appropriate type for the requested
* data kind.
*
* Returns GHOSTTY_NO_VALUE when Kitty graphics are disabled at build time.
*
* @param graphics The kitty graphics handle
* @param data The type of data to extract
* @param[out] out Pointer to store the extracted data
* @return GHOSTTY_SUCCESS on success
*
* @ingroup kitty_graphics
*/
GHOSTTY_API GhosttyResult ghostty_kitty_graphics_get(
GhosttyKittyGraphics graphics,
GhosttyKittyGraphicsData data,
void* out);
/**
* Look up a Kitty graphics image by its image ID.
*
* Returns NULL if no image with the given ID exists or if Kitty graphics
* are disabled at build time.
*
* @param graphics The kitty graphics handle
* @param image_id The image ID to look up
* @return An opaque image handle, or NULL if not found
*
* @ingroup kitty_graphics
*/
GHOSTTY_API GhosttyKittyGraphicsImage ghostty_kitty_graphics_image(
GhosttyKittyGraphics graphics,
uint32_t image_id);
/**
* Get data from a Kitty graphics image.
*
* The output pointer must be of the appropriate type for the requested
* data kind.
*
* @param image The image handle (NULL returns GHOSTTY_INVALID_VALUE)
* @param data The data kind to query
* @param[out] out Pointer to receive the queried value
* @return GHOSTTY_SUCCESS on success
*
* @ingroup kitty_graphics
*/
GHOSTTY_API GhosttyResult ghostty_kitty_graphics_image_get(
GhosttyKittyGraphicsImage image,
GhosttyKittyGraphicsImageData data,
void* out);
/**
* Get multiple data fields from a Kitty graphics image in a single call.
*
* This is an optimization over calling ghostty_kitty_graphics_image_get()
* repeatedly, particularly useful in environments with high per-call
* overhead such as FFI or Cgo.
*
* Each element in the keys array specifies a data kind, and the
* corresponding element in the values array receives the result.
* The type of each values[i] pointer must match the output type
* documented for keys[i].
*
* Processing stops at the first error; on success out_written
* is set to count, on error it is set to the index of the
* failing key (i.e. the number of values successfully written).
*
* @param image The image handle (NULL returns GHOSTTY_INVALID_VALUE)
* @param count Number of key/value pairs
* @param keys Array of data kinds to query
* @param values Array of output pointers (types must match each key's
* documented output type)
* @param[out] out_written On return, receives the number of values
* successfully written (may be NULL)
* @return GHOSTTY_SUCCESS if all queries succeed
*
* @ingroup kitty_graphics
*/
GHOSTTY_API GhosttyResult ghostty_kitty_graphics_image_get_multi(
GhosttyKittyGraphicsImage image,
size_t count,
const GhosttyKittyGraphicsImageData* keys,
void** values,
size_t* out_written);
/**
* Create a new placement iterator instance.
*
* All fields except the allocator are left undefined until populated
* via ghostty_kitty_graphics_get() with
* GHOSTTY_KITTY_GRAPHICS_DATA_PLACEMENT_ITERATOR.
*
* @param allocator Pointer to allocator, or NULL to use the default allocator
* @param[out] out_iterator On success, receives the created iterator handle
* @return GHOSTTY_SUCCESS on success, GHOSTTY_OUT_OF_MEMORY on allocation
* failure
*
* @ingroup kitty_graphics
*/
GHOSTTY_API GhosttyResult ghostty_kitty_graphics_placement_iterator_new(
const GhosttyAllocator* allocator,
GhosttyKittyGraphicsPlacementIterator* out_iterator);
/**
* Free a placement iterator.
*
* @param iterator The iterator handle to free (may be NULL)
*
* @ingroup kitty_graphics
*/
GHOSTTY_API void ghostty_kitty_graphics_placement_iterator_free(
GhosttyKittyGraphicsPlacementIterator iterator);
/**
* Set an option on a placement iterator.
*
* Use GHOSTTY_KITTY_GRAPHICS_PLACEMENT_ITERATOR_OPTION_LAYER with a
* GhosttyKittyPlacementLayer value to filter placements by z-layer.
* The filter is applied during iteration: ghostty_kitty_graphics_placement_next()
* will skip placements that do not match the configured layer.
*
* The default layer is GHOSTTY_KITTY_PLACEMENT_LAYER_ALL (no filtering).
*
* @param iterator The iterator handle (NULL returns GHOSTTY_INVALID_VALUE)
* @param option The option to set
* @param value Pointer to the value (type depends on option; NULL returns
* GHOSTTY_INVALID_VALUE)
* @return GHOSTTY_SUCCESS on success
*
* @ingroup kitty_graphics
*/
GHOSTTY_API GhosttyResult ghostty_kitty_graphics_placement_iterator_set(
GhosttyKittyGraphicsPlacementIterator iterator,
GhosttyKittyGraphicsPlacementIteratorOption option,
const void* value);
/**
* Advance the placement iterator to the next placement.
*
* If a layer filter has been set via
* ghostty_kitty_graphics_placement_iterator_set(), only placements
* matching that layer are returned.
*
* @param iterator The iterator handle (may be NULL)
* @return true if advanced to the next placement, false if at the end
*
* @ingroup kitty_graphics
*/
GHOSTTY_API bool ghostty_kitty_graphics_placement_next(
GhosttyKittyGraphicsPlacementIterator iterator);
/**
* Get data from the current placement in a placement iterator.
*
* Call ghostty_kitty_graphics_placement_next() at least once before
* calling this function.
*
* @param iterator The iterator handle (NULL returns GHOSTTY_INVALID_VALUE)
* @param data The data kind to query
* @param[out] out Pointer to receive the queried value
* @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if the
* iterator is NULL or not positioned on a placement
*
* @ingroup kitty_graphics
*/
GHOSTTY_API GhosttyResult ghostty_kitty_graphics_placement_get(
GhosttyKittyGraphicsPlacementIterator iterator,
GhosttyKittyGraphicsPlacementData data,
void* out);
/**
* Get multiple data fields from the current placement in a single call.
*
* This is an optimization over calling ghostty_kitty_graphics_placement_get()
* repeatedly, particularly useful in environments with high per-call
* overhead such as FFI or Cgo.
*
* Each element in the keys array specifies a data kind, and the
* corresponding element in the values array receives the result.
* The type of each values[i] pointer must match the output type
* documented for keys[i].
*
* Processing stops at the first error; on success out_written
* is set to count, on error it is set to the index of the
* failing key (i.e. the number of values successfully written).
*
* @param iterator The iterator handle (NULL returns GHOSTTY_INVALID_VALUE)
* @param count Number of key/value pairs
* @param keys Array of data kinds to query
* @param values Array of output pointers (types must match each key's
* documented output type)
* @param[out] out_written On return, receives the number of values
* successfully written (may be NULL)
* @return GHOSTTY_SUCCESS if all queries succeed
*
* @ingroup kitty_graphics
*/
GHOSTTY_API GhosttyResult ghostty_kitty_graphics_placement_get_multi(
GhosttyKittyGraphicsPlacementIterator iterator,
size_t count,
const GhosttyKittyGraphicsPlacementData* keys,
void** values,
size_t* out_written);
/**
* Compute the grid rectangle occupied by the current placement.
*
* Uses the placement's pin, the image dimensions, and the terminal's
* cell/pixel geometry to calculate the bounding rectangle. Virtual
* placements (unicode placeholders) return GHOSTTY_NO_VALUE.
*
* @param terminal The terminal handle
* @param image The image handle for this placement's image
* @param iterator The placement iterator positioned on a placement
* @param[out] out_selection On success, receives the bounding rectangle
* as a selection with rectangle=true
* @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if any handle
* is NULL or the iterator is not positioned, GHOSTTY_NO_VALUE for
* virtual placements or when Kitty graphics are disabled
*
* @ingroup kitty_graphics
*/
GHOSTTY_API GhosttyResult ghostty_kitty_graphics_placement_rect(
GhosttyKittyGraphicsPlacementIterator iterator,
GhosttyKittyGraphicsImage image,
GhosttyTerminal terminal,
GhosttySelection* out_selection);
/**
* Compute the rendered pixel size of the current placement.
*
* Takes into account the placement's source rectangle, specified
* columns/rows, and aspect ratio to calculate the final rendered
* pixel dimensions.
*
* @param iterator The placement iterator positioned on a placement
* @param image The image handle for this placement's image
* @param terminal The terminal handle
* @param[out] out_width On success, receives the width in pixels
* @param[out] out_height On success, receives the height in pixels
* @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if any handle
* is NULL or the iterator is not positioned, GHOSTTY_NO_VALUE when
* Kitty graphics are disabled
*
* @ingroup kitty_graphics
*/
GHOSTTY_API GhosttyResult ghostty_kitty_graphics_placement_pixel_size(
GhosttyKittyGraphicsPlacementIterator iterator,
GhosttyKittyGraphicsImage image,
GhosttyTerminal terminal,
uint32_t* out_width,
uint32_t* out_height);
/**
* Compute the grid cell size of the current placement.
*
* Returns the number of columns and rows that the placement occupies
* in the terminal grid. If the placement specifies explicit columns
* and rows, those are returned directly; otherwise they are calculated
* from the pixel size and cell dimensions.
*
* @param iterator The placement iterator positioned on a placement
* @param image The image handle for this placement's image
* @param terminal The terminal handle
* @param[out] out_cols On success, receives the number of columns
* @param[out] out_rows On success, receives the number of rows
* @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if any handle
* is NULL or the iterator is not positioned, GHOSTTY_NO_VALUE when
* Kitty graphics are disabled
*
* @ingroup kitty_graphics
*/
GHOSTTY_API GhosttyResult ghostty_kitty_graphics_placement_grid_size(
GhosttyKittyGraphicsPlacementIterator iterator,
GhosttyKittyGraphicsImage image,
GhosttyTerminal terminal,
uint32_t* out_cols,
uint32_t* out_rows);
/**
* Get the viewport-relative grid position of the current placement.
*
* Converts the placement's internal pin to viewport-relative column and
* row coordinates. The returned coordinates represent the top-left
* corner of the placement in the viewport's grid coordinate space.
*
* The row value can be negative when the placement's origin has
* scrolled above the top of the viewport. For example, a 4-row
* image that has scrolled up by 2 rows returns row=-2, meaning
* its top 2 rows are above the visible area but its bottom 2 rows
* are still on screen. Embedders should use these coordinates
* directly when computing the destination rectangle for rendering;
* the embedder is responsible for clipping the portion of the image
* that falls outside the viewport.
*
* Returns GHOSTTY_SUCCESS for any placement that is at least
* partially visible in the viewport. Returns GHOSTTY_NO_VALUE when
* the placement is completely outside the viewport (its bottom edge
* is above the viewport or its top edge is at or below the last
* viewport row), or when the placement is a virtual (unicode
* placeholder) placement.
*
* @param iterator The placement iterator positioned on a placement
* @param image The image handle for this placement's image
* @param terminal The terminal handle
* @param[out] out_col On success, receives the viewport-relative column
* @param[out] out_row On success, receives the viewport-relative row
* (may be negative for partially visible placements)
* @return GHOSTTY_SUCCESS on success, GHOSTTY_NO_VALUE if fully
* off-screen or virtual, GHOSTTY_INVALID_VALUE if any handle
* is NULL or the iterator is not positioned
*
* @ingroup kitty_graphics
*/
GHOSTTY_API GhosttyResult ghostty_kitty_graphics_placement_viewport_pos(
GhosttyKittyGraphicsPlacementIterator iterator,
GhosttyKittyGraphicsImage image,
GhosttyTerminal terminal,
int32_t* out_col,
int32_t* out_row);
/**
* Get the resolved source rectangle for the current placement.
*
* Applies kitty protocol semantics: a width or height of 0 in the
* placement means "use the full image dimension", and the resulting
* rectangle is clamped to the actual image bounds. The returned
* values are in pixels and are ready to use for texture sampling.
*
* @param iterator The placement iterator positioned on a placement
* @param image The image handle for this placement's image
* @param[out] out_x Source rect x origin in pixels
* @param[out] out_y Source rect y origin in pixels
* @param[out] out_width Source rect width in pixels
* @param[out] out_height Source rect height in pixels
* @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if any
* handle is NULL or the iterator is not positioned
*
* @ingroup kitty_graphics
*/
GHOSTTY_API GhosttyResult ghostty_kitty_graphics_placement_source_rect(
GhosttyKittyGraphicsPlacementIterator iterator,
GhosttyKittyGraphicsImage image,
uint32_t* out_x,
uint32_t* out_y,
uint32_t* out_width,
uint32_t* out_height);
/**
* Get all rendering geometry for a placement in a single call.
*
* Combines pixel size, grid size, viewport position, and source
* rectangle into one struct. Initialize with
* GHOSTTY_INIT_SIZED(GhosttyKittyGraphicsPlacementRenderInfo).
*
* When viewport_visible is false, the placement is fully off-screen
* or is a virtual placement; viewport_col and viewport_row may
* contain meaningless values in that case.
*
* @param iterator The iterator positioned on a placement
* @param image The image handle for this placement's image
* @param terminal The terminal handle
* @param[out] out_info Pointer to receive the rendering geometry
* @return GHOSTTY_SUCCESS on success
*
* @ingroup kitty_graphics
*/
GHOSTTY_API GhosttyResult ghostty_kitty_graphics_placement_render_info(
GhosttyKittyGraphicsPlacementIterator iterator,
GhosttyKittyGraphicsImage image,
GhosttyTerminal terminal,
GhosttyKittyGraphicsPlacementRenderInfo* out_info);
/** @} */
#ifdef __cplusplus
}
#endif
#endif /* GHOSTTY_VT_KITTY_GRAPHICS_H */
@@ -0,0 +1,198 @@
/**
* @file modes.h
*
* Terminal mode utilities - pack and unpack ANSI/DEC mode identifiers.
*/
#ifndef GHOSTTY_VT_MODES_H
#define GHOSTTY_VT_MODES_H
/** @defgroup modes Mode Utilities
*
* Utilities for working with terminal modes. A mode is a compact
* 16-bit representation of a terminal mode identifier that encodes both
* the numeric mode value (up to 15 bits) and whether the mode is an ANSI
* mode or a DEC private mode (?-prefixed).
*
* The packed layout (least-significant bit first) is:
* - Bits 0–14: mode value (u15)
* - Bit 15: ANSI flag (0 = DEC private mode, 1 = ANSI mode)
*
* ## Example
*
* @snippet c-vt-modes/src/main.c modes-pack-unpack
*
* ## DECRPM Report Encoding
*
* Use ghostty_mode_report_encode() to encode a DECRPM response into a
* caller-provided buffer:
*
* @snippet c-vt-modes/src/main.c modes-decrpm
*
* @{
*/
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <ghostty/vt/types.h>
#ifdef __cplusplus
extern "C" {
#endif
/** @name ANSI Modes
* Modes for standard ANSI modes.
* @{
*/
#define GHOSTTY_MODE_KAM (ghostty_mode_new(2, true)) /**< Keyboard action (disable keyboard) */
#define GHOSTTY_MODE_INSERT (ghostty_mode_new(4, true)) /**< Insert mode */
#define GHOSTTY_MODE_SRM (ghostty_mode_new(12, true)) /**< Send/receive mode */
#define GHOSTTY_MODE_LINEFEED (ghostty_mode_new(20, true)) /**< Linefeed/new line mode */
/** @} */
/** @name DEC Private Modes
* Modes for DEC private modes (?-prefixed).
* @{
*/
#define GHOSTTY_MODE_DECCKM (ghostty_mode_new(1, false)) /**< Cursor keys */
#define GHOSTTY_MODE_132_COLUMN (ghostty_mode_new(3, false)) /**< 132/80 column mode */
#define GHOSTTY_MODE_SLOW_SCROLL (ghostty_mode_new(4, false)) /**< Slow scroll */
#define GHOSTTY_MODE_REVERSE_COLORS (ghostty_mode_new(5, false)) /**< Reverse video */
#define GHOSTTY_MODE_ORIGIN (ghostty_mode_new(6, false)) /**< Origin mode */
#define GHOSTTY_MODE_WRAPAROUND (ghostty_mode_new(7, false)) /**< Auto-wrap mode */
#define GHOSTTY_MODE_AUTOREPEAT (ghostty_mode_new(8, false)) /**< Auto-repeat keys */
#define GHOSTTY_MODE_X10_MOUSE (ghostty_mode_new(9, false)) /**< X10 mouse reporting */
#define GHOSTTY_MODE_CURSOR_BLINKING (ghostty_mode_new(12, false)) /**< Cursor blink */
#define GHOSTTY_MODE_CURSOR_VISIBLE (ghostty_mode_new(25, false)) /**< Cursor visible (DECTCEM) */
#define GHOSTTY_MODE_ENABLE_MODE_3 (ghostty_mode_new(40, false)) /**< Allow 132 column mode */
#define GHOSTTY_MODE_REVERSE_WRAP (ghostty_mode_new(45, false)) /**< Reverse wrap */
#define GHOSTTY_MODE_ALT_SCREEN_LEGACY (ghostty_mode_new(47, false)) /**< Alternate screen (legacy) */
#define GHOSTTY_MODE_KEYPAD_KEYS (ghostty_mode_new(66, false)) /**< Application keypad */
#define GHOSTTY_MODE_BACKARROW_KEY_MODE (ghostty_mode_new(67, false)) /**< Backarrow key mode (DECBKM) */
#define GHOSTTY_MODE_LEFT_RIGHT_MARGIN (ghostty_mode_new(69, false)) /**< Left/right margin mode */
#define GHOSTTY_MODE_NORMAL_MOUSE (ghostty_mode_new(1000, false)) /**< Normal mouse tracking */
#define GHOSTTY_MODE_BUTTON_MOUSE (ghostty_mode_new(1002, false)) /**< Button-event mouse tracking */
#define GHOSTTY_MODE_ANY_MOUSE (ghostty_mode_new(1003, false)) /**< Any-event mouse tracking */
#define GHOSTTY_MODE_FOCUS_EVENT (ghostty_mode_new(1004, false)) /**< Focus in/out events */
#define GHOSTTY_MODE_UTF8_MOUSE (ghostty_mode_new(1005, false)) /**< UTF-8 mouse format */
#define GHOSTTY_MODE_SGR_MOUSE (ghostty_mode_new(1006, false)) /**< SGR mouse format */
#define GHOSTTY_MODE_ALT_SCROLL (ghostty_mode_new(1007, false)) /**< Alternate scroll mode */
#define GHOSTTY_MODE_URXVT_MOUSE (ghostty_mode_new(1015, false)) /**< URxvt mouse format */
#define GHOSTTY_MODE_SGR_PIXELS_MOUSE (ghostty_mode_new(1016, false)) /**< SGR-Pixels mouse format */
#define GHOSTTY_MODE_NUMLOCK_KEYPAD (ghostty_mode_new(1035, false)) /**< Ignore keypad with NumLock */
#define GHOSTTY_MODE_ALT_ESC_PREFIX (ghostty_mode_new(1036, false)) /**< Alt key sends ESC prefix */
#define GHOSTTY_MODE_ALT_SENDS_ESC (ghostty_mode_new(1039, false)) /**< Alt sends escape */
#define GHOSTTY_MODE_REVERSE_WRAP_EXT (ghostty_mode_new(1045, false)) /**< Extended reverse wrap */
#define GHOSTTY_MODE_ALT_SCREEN (ghostty_mode_new(1047, false)) /**< Alternate screen */
#define GHOSTTY_MODE_SAVE_CURSOR (ghostty_mode_new(1048, false)) /**< Save cursor (DECSC) */
#define GHOSTTY_MODE_ALT_SCREEN_SAVE (ghostty_mode_new(1049, false)) /**< Alt screen + save cursor + clear */
#define GHOSTTY_MODE_BRACKETED_PASTE (ghostty_mode_new(2004, false)) /**< Bracketed paste mode */
#define GHOSTTY_MODE_SYNC_OUTPUT (ghostty_mode_new(2026, false)) /**< Synchronized output */
#define GHOSTTY_MODE_GRAPHEME_CLUSTER (ghostty_mode_new(2027, false)) /**< Grapheme cluster mode */
#define GHOSTTY_MODE_COLOR_SCHEME_REPORT (ghostty_mode_new(2031, false)) /**< Report color scheme */
#define GHOSTTY_MODE_IN_BAND_RESIZE (ghostty_mode_new(2048, false)) /**< In-band size reports */
/** @} */
/**
* A packed 16-bit terminal mode.
*
* Encodes a mode value (bits 0–14) and an ANSI flag (bit 15) into a
* single 16-bit integer. Use the inline helper functions to construct
* and inspect modes rather than manipulating bits directly.
*/
typedef uint16_t GhosttyMode;
/**
* Create a mode from a mode value and ANSI flag.
*
* @param value The numeric mode value (0–32767)
* @param ansi true for an ANSI mode, false for a DEC private mode
* @return The packed mode
*
* @ingroup modes
*/
static inline GhosttyMode ghostty_mode_new(uint16_t value, bool ansi) {
return (GhosttyMode)((value & 0x7FFF) | ((uint16_t)ansi << 15));
}
/**
* Extract the numeric mode value from a mode.
*
* @param mode The mode
* @return The mode value (0–32767)
*
* @ingroup modes
*/
static inline uint16_t ghostty_mode_value(GhosttyMode mode) {
return mode & 0x7FFF;
}
/**
* Check whether a mode represents an ANSI mode.
*
* @param mode The mode
* @return true if this is an ANSI mode, false if it is a DEC private mode
*
* @ingroup modes
*/
static inline bool ghostty_mode_ansi(GhosttyMode mode) {
return (mode >> 15) != 0;
}
/**
* DECRPM report state values.
*
* These correspond to the Ps2 parameter in a DECRPM response
* sequence (CSI ? Ps1 ; Ps2 $ y).
*/
typedef enum GHOSTTY_ENUM_TYPED {
/** Mode is not recognized */
GHOSTTY_MODE_REPORT_NOT_RECOGNIZED = 0,
/** Mode is set (enabled) */
GHOSTTY_MODE_REPORT_SET = 1,
/** Mode is reset (disabled) */
GHOSTTY_MODE_REPORT_RESET = 2,
/** Mode is permanently set */
GHOSTTY_MODE_REPORT_PERMANENTLY_SET = 3,
/** Mode is permanently reset */
GHOSTTY_MODE_REPORT_PERMANENTLY_RESET = 4,
GHOSTTY_MODE_REPORT_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
} GhosttyModeReportState;
/**
* Encode a DECRPM (DEC Private Mode Report) response sequence.
*
* Writes a mode report escape sequence into the provided buffer.
* The generated sequence has the form:
* - DEC private mode: CSI ? Ps1 ; Ps2 $ y
* - ANSI mode: CSI Ps1 ; Ps2 $ y
*
* If the buffer is too small, the function returns GHOSTTY_OUT_OF_SPACE
* and writes the required buffer size to @p out_written. The caller can
* then retry with a sufficiently sized buffer.
*
* @param mode The mode identifying the mode to report on
* @param state The report state for this mode
* @param buf Output buffer to write the encoded sequence into (may be NULL)
* @param buf_len Size of the output buffer in bytes
* @param[out] out_written On success, the number of bytes written. On
* GHOSTTY_OUT_OF_SPACE, the required buffer size.
* @return GHOSTTY_SUCCESS on success, GHOSTTY_OUT_OF_SPACE if the buffer
* is too small
*/
GHOSTTY_API GhosttyResult ghostty_mode_report_encode(
GhosttyMode mode,
GhosttyModeReportState state,
char* buf,
size_t buf_len,
size_t* out_written);
#ifdef __cplusplus
}
#endif
/** @} */
#endif /* GHOSTTY_VT_MODES_H */
@@ -0,0 +1,70 @@
/**
* @file mouse.h
*
* Mouse encoding module - encode mouse events into terminal escape sequences.
*/
#ifndef GHOSTTY_VT_MOUSE_H
#define GHOSTTY_VT_MOUSE_H
/** @defgroup mouse Mouse Encoding
*
* Utilities for encoding mouse events into terminal escape sequences,
* supporting X10, UTF-8, SGR, URxvt, and SGR-Pixels mouse protocols.
*
* ## Basic Usage
*
* 1. Create an encoder instance with ghostty_mouse_encoder_new().
* 2. Configure encoder options with ghostty_mouse_encoder_setopt() or
* ghostty_mouse_encoder_setopt_from_terminal().
* 3. For each mouse event:
* - Create a mouse event with ghostty_mouse_event_new().
* - Set event properties (action, button, modifiers, position).
* - Encode with ghostty_mouse_encoder_encode().
* - Free the event with ghostty_mouse_event_free() or reuse it.
* 4. Free the encoder with ghostty_mouse_encoder_free() when done.
*
* For a complete working example, see example/c-vt-encode-mouse in the
* repository.
*
* ## Example
*
* @snippet c-vt-encode-mouse/src/main.c mouse-encode
*
* ## Example: Encoding with Terminal State
*
* When you have a GhosttyTerminal, you can sync its tracking mode and
* output format into the encoder automatically:
*
* @code{.c}
* // Create a terminal and feed it some VT data that enables mouse tracking
* GhosttyTerminal terminal;
* ghostty_terminal_new(NULL, &terminal,
* (GhosttyTerminalOptions){.cols = 80, .rows = 24, .max_scrollback = 0});
*
* // Application might write data that enables mouse reporting, etc.
* ghostty_terminal_vt_write(terminal, vt_data, vt_len);
*
* // Create an encoder and sync its options from the terminal
* GhosttyMouseEncoder encoder;
* ghostty_mouse_encoder_new(NULL, &encoder);
* ghostty_mouse_encoder_setopt_from_terminal(encoder, terminal);
*
* // Encode a mouse event using the terminal-derived options
* char buf[128];
* size_t written = 0;
* ghostty_mouse_encoder_encode(encoder, event, buf, sizeof(buf), &written);
*
* ghostty_mouse_encoder_free(encoder);
* ghostty_terminal_free(terminal);
* @endcode
*
* @{
*/
#include <ghostty/vt/mouse/event.h>
#include <ghostty/vt/mouse/encoder.h>
/** @} */
#endif /* GHOSTTY_VT_MOUSE_H */
@@ -0,0 +1,214 @@
/**
* @file encoder.h
*
* Mouse event encoding to terminal escape sequences.
*/
#ifndef GHOSTTY_VT_MOUSE_ENCODER_H
#define GHOSTTY_VT_MOUSE_ENCODER_H
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <ghostty/vt/allocator.h>
#include <ghostty/vt/mouse/event.h>
#include <ghostty/vt/terminal.h>
#include <ghostty/vt/types.h>
/**
* Opaque handle to a mouse encoder instance.
*
* This handle represents a mouse encoder that converts normalized
* mouse events into terminal escape sequences.
*
* @ingroup mouse
*/
typedef struct GhosttyMouseEncoderImpl *GhosttyMouseEncoder;
/**
* Mouse tracking mode.
*
* @ingroup mouse
*/
typedef enum GHOSTTY_ENUM_TYPED {
/** Mouse reporting disabled. */
GHOSTTY_MOUSE_TRACKING_NONE = 0,
/** X10 mouse mode. */
GHOSTTY_MOUSE_TRACKING_X10 = 1,
/** Normal mouse mode (button press/release only). */
GHOSTTY_MOUSE_TRACKING_NORMAL = 2,
/** Button-event tracking mode. */
GHOSTTY_MOUSE_TRACKING_BUTTON = 3,
/** Any-event tracking mode. */
GHOSTTY_MOUSE_TRACKING_ANY = 4,
GHOSTTY_MOUSE_TRACKING_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
} GhosttyMouseTrackingMode;
/**
* Mouse output format.
*
* @ingroup mouse
*/
typedef enum GHOSTTY_ENUM_TYPED {
GHOSTTY_MOUSE_FORMAT_X10 = 0,
GHOSTTY_MOUSE_FORMAT_UTF8 = 1,
GHOSTTY_MOUSE_FORMAT_SGR = 2,
GHOSTTY_MOUSE_FORMAT_URXVT = 3,
GHOSTTY_MOUSE_FORMAT_SGR_PIXELS = 4,
GHOSTTY_MOUSE_FORMAT_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
} GhosttyMouseFormat;
/**
* Mouse encoder size and geometry context.
*
* This describes the rendered terminal geometry used to convert
* surface-space positions into encoded coordinates.
*
* @ingroup mouse
*/
typedef struct {
/** Size of this struct in bytes. Must be set to sizeof(GhosttyMouseEncoderSize). */
size_t size;
/** Full screen width in pixels. */
uint32_t screen_width;
/** Full screen height in pixels. */
uint32_t screen_height;
/** Cell width in pixels. Must be non-zero. */
uint32_t cell_width;
/** Cell height in pixels. Must be non-zero. */
uint32_t cell_height;
/** Top padding in pixels. */
uint32_t padding_top;
/** Bottom padding in pixels. */
uint32_t padding_bottom;
/** Right padding in pixels. */
uint32_t padding_right;
/** Left padding in pixels. */
uint32_t padding_left;
} GhosttyMouseEncoderSize;
/**
* Mouse encoder option identifiers.
*
* These values are used with ghostty_mouse_encoder_setopt() to configure
* the behavior of the mouse encoder.
*
* @ingroup mouse
*/
typedef enum GHOSTTY_ENUM_TYPED {
/** Mouse tracking mode (value: GhosttyMouseTrackingMode). */
GHOSTTY_MOUSE_ENCODER_OPT_EVENT = 0,
/** Mouse output format (value: GhosttyMouseFormat). */
GHOSTTY_MOUSE_ENCODER_OPT_FORMAT = 1,
/** Renderer size context (value: GhosttyMouseEncoderSize). */
GHOSTTY_MOUSE_ENCODER_OPT_SIZE = 2,
/** Whether any mouse button is currently pressed (value: bool). */
GHOSTTY_MOUSE_ENCODER_OPT_ANY_BUTTON_PRESSED = 3,
/** Whether to enable motion deduplication by last cell (value: bool). */
GHOSTTY_MOUSE_ENCODER_OPT_TRACK_LAST_CELL = 4,
GHOSTTY_MOUSE_ENCODER_OPT_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
} GhosttyMouseEncoderOption;
/**
* Create a new mouse encoder instance.
*
* @param allocator Pointer to allocator, 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 mouse
*/
GHOSTTY_API GhosttyResult ghostty_mouse_encoder_new(const GhosttyAllocator *allocator,
GhosttyMouseEncoder *encoder);
/**
* Free a mouse encoder instance.
*
* @param encoder The encoder handle to free (may be NULL)
*
* @ingroup mouse
*/
GHOSTTY_API void ghostty_mouse_encoder_free(GhosttyMouseEncoder encoder);
/**
* Set an option on the mouse encoder.
*
* A null pointer value does nothing. It does not reset to defaults.
*
* @param encoder The encoder handle, must not be NULL
* @param option The option to set
* @param value Pointer to option value (type depends on option)
*
* @ingroup mouse
*/
GHOSTTY_API void ghostty_mouse_encoder_setopt(GhosttyMouseEncoder encoder,
GhosttyMouseEncoderOption option,
const void *value);
/**
* Set encoder options from a terminal's current state.
*
* This sets tracking mode and output format from terminal state.
* It does not modify size or any-button state.
*
* @param encoder The encoder handle, must not be NULL
* @param terminal The terminal handle, must not be NULL
*
* @ingroup mouse
*/
GHOSTTY_API void ghostty_mouse_encoder_setopt_from_terminal(GhosttyMouseEncoder encoder,
GhosttyTerminal terminal);
/**
* Reset internal encoder state.
*
* This clears motion deduplication state (last tracked cell).
*
* @param encoder The encoder handle (may be NULL)
*
* @ingroup mouse
*/
GHOSTTY_API void ghostty_mouse_encoder_reset(GhosttyMouseEncoder encoder);
/**
* Encode a mouse event into a terminal escape sequence.
*
* Not all mouse events produce output. In such cases this returns
* GHOSTTY_SUCCESS with out_len set to 0.
*
* If the output buffer is too small, this returns GHOSTTY_OUT_OF_SPACE
* and out_len contains the required size.
*
* @param encoder The encoder handle, must not be NULL
* @param event The mouse event to encode, must not be NULL
* @param out_buf Buffer to write encoded bytes to, or NULL to query required size
* @param out_buf_size Size of out_buf in bytes
* @param out_len Pointer to store bytes written (or required bytes on failure)
* @return GHOSTTY_SUCCESS on success, GHOSTTY_OUT_OF_SPACE if buffer is too small,
* or another error code
*
* @ingroup mouse
*/
GHOSTTY_API GhosttyResult ghostty_mouse_encoder_encode(GhosttyMouseEncoder encoder,
GhosttyMouseEvent event,
char *out_buf,
size_t out_buf_size,
size_t *out_len);
#endif /* GHOSTTY_VT_MOUSE_ENCODER_H */
@@ -0,0 +1,195 @@
/**
* @file event.h
*
* Mouse event representation and manipulation.
*/
#ifndef GHOSTTY_VT_MOUSE_EVENT_H
#define GHOSTTY_VT_MOUSE_EVENT_H
#include <stdbool.h>
#include <ghostty/vt/allocator.h>
#include <ghostty/vt/key/event.h>
#include <ghostty/vt/types.h>
/**
* Opaque handle to a mouse event.
*
* This handle represents a normalized mouse input event containing
* action, button, modifiers, and surface-space position.
*
* @ingroup mouse
*/
typedef struct GhosttyMouseEventImpl *GhosttyMouseEvent;
/**
* Mouse event action type.
*
* @ingroup mouse
*/
typedef enum GHOSTTY_ENUM_TYPED {
/** Mouse button was pressed. */
GHOSTTY_MOUSE_ACTION_PRESS = 0,
/** Mouse button was released. */
GHOSTTY_MOUSE_ACTION_RELEASE = 1,
/** Mouse moved. */
GHOSTTY_MOUSE_ACTION_MOTION = 2,
GHOSTTY_MOUSE_ACTION_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
} GhosttyMouseAction;
/**
* Mouse button identity.
*
* @ingroup mouse
*/
typedef enum GHOSTTY_ENUM_TYPED {
GHOSTTY_MOUSE_BUTTON_UNKNOWN = 0,
GHOSTTY_MOUSE_BUTTON_LEFT = 1,
GHOSTTY_MOUSE_BUTTON_RIGHT = 2,
GHOSTTY_MOUSE_BUTTON_MIDDLE = 3,
GHOSTTY_MOUSE_BUTTON_FOUR = 4,
GHOSTTY_MOUSE_BUTTON_FIVE = 5,
GHOSTTY_MOUSE_BUTTON_SIX = 6,
GHOSTTY_MOUSE_BUTTON_SEVEN = 7,
GHOSTTY_MOUSE_BUTTON_EIGHT = 8,
GHOSTTY_MOUSE_BUTTON_NINE = 9,
GHOSTTY_MOUSE_BUTTON_TEN = 10,
GHOSTTY_MOUSE_BUTTON_ELEVEN = 11,
GHOSTTY_MOUSE_BUTTON_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
} GhosttyMouseButton;
/**
* Mouse position in surface-space pixels.
*
* @ingroup mouse
*/
typedef struct {
float x;
float y;
} GhosttyMousePosition;
/**
* Create a new mouse event instance.
*
* @param allocator Pointer to allocator, or NULL to use the default allocator
* @param event Pointer to store the created event handle
* @return GHOSTTY_SUCCESS on success, or an error code on failure
*
* @ingroup mouse
*/
GHOSTTY_API GhosttyResult ghostty_mouse_event_new(const GhosttyAllocator *allocator,
GhosttyMouseEvent *event);
/**
* Free a mouse event instance.
*
* @param event The mouse event handle to free (may be NULL)
*
* @ingroup mouse
*/
GHOSTTY_API void ghostty_mouse_event_free(GhosttyMouseEvent event);
/**
* Set the event action.
*
* @param event The event handle, must not be NULL
* @param action The action to set
*
* @ingroup mouse
*/
GHOSTTY_API void ghostty_mouse_event_set_action(GhosttyMouseEvent event,
GhosttyMouseAction action);
/**
* Get the event action.
*
* @param event The event handle, must not be NULL
* @return The event action
*
* @ingroup mouse
*/
GHOSTTY_API GhosttyMouseAction ghostty_mouse_event_get_action(GhosttyMouseEvent event);
/**
* Set the event button.
*
* This sets a concrete button identity for the event.
* To represent "no button" (for motion events), use
* ghostty_mouse_event_clear_button().
*
* @param event The event handle, must not be NULL
* @param button The button to set
*
* @ingroup mouse
*/
GHOSTTY_API void ghostty_mouse_event_set_button(GhosttyMouseEvent event,
GhosttyMouseButton button);
/**
* Clear the event button.
*
* This sets the event button to "none".
*
* @param event The event handle, must not be NULL
*
* @ingroup mouse
*/
GHOSTTY_API void ghostty_mouse_event_clear_button(GhosttyMouseEvent event);
/**
* Get the event button.
*
* @param event The event handle, must not be NULL
* @param out_button Output pointer for the button value (may be NULL)
* @return true if a button is set, false if no button is set
*
* @ingroup mouse
*/
GHOSTTY_API bool ghostty_mouse_event_get_button(GhosttyMouseEvent event,
GhosttyMouseButton *out_button);
/**
* Set keyboard modifiers held during the event.
*
* @param event The event handle, must not be NULL
* @param mods Modifier bitmask
*
* @ingroup mouse
*/
GHOSTTY_API void ghostty_mouse_event_set_mods(GhosttyMouseEvent event,
GhosttyMods mods);
/**
* Get keyboard modifiers held during the event.
*
* @param event The event handle, must not be NULL
* @return Modifier bitmask
*
* @ingroup mouse
*/
GHOSTTY_API GhosttyMods ghostty_mouse_event_get_mods(GhosttyMouseEvent event);
/**
* Set the event position in surface-space pixels.
*
* @param event The event handle, must not be NULL
* @param position The position to set
*
* @ingroup mouse
*/
GHOSTTY_API void ghostty_mouse_event_set_position(GhosttyMouseEvent event,
GhosttyMousePosition position);
/**
* Get the event position in surface-space pixels.
*
* @param event The event handle, must not be NULL
* @return The current event position
*
* @ingroup mouse
*/
GHOSTTY_API GhosttyMousePosition ghostty_mouse_event_get_position(GhosttyMouseEvent event);
#endif /* GHOSTTY_VT_MOUSE_EVENT_H */
@@ -0,0 +1,215 @@
/**
* @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/types.h>
#include <ghostty/vt/allocator.h>
/** @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_ENUM_TYPED {
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,
GHOSTTY_OSC_COMMAND_TYPE_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
} 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 GHOSTTY_ENUM_TYPED {
/** 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,
GHOSTTY_OSC_DATA_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
} 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
*/
GHOSTTY_API 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
*/
GHOSTTY_API 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
*/
GHOSTTY_API 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
*/
GHOSTTY_API 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
*/
GHOSTTY_API 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
*/
GHOSTTY_API 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
*/
GHOSTTY_API bool ghostty_osc_command_data(GhosttyOscCommand command, GhosttyOscCommandData data, void *out);
/** @} */
#endif /* GHOSTTY_VT_OSC_H */
@@ -0,0 +1,101 @@
/**
* @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 and encoding paste data for terminal input.
*
* ## Basic Usage
*
* Use ghostty_paste_is_safe() to check if paste data contains potentially
* dangerous sequences before sending it to the terminal.
*
* Use ghostty_paste_encode() to encode paste data for writing to the pty,
* including bracketed paste wrapping and unsafe byte stripping.
*
* ## Examples
*
* ### Safety Check
*
* @snippet c-vt-paste/src/main.c paste-safety
*
* ### Encoding
*
* @snippet c-vt-paste/src/main.c paste-encode
*
* @{
*/
#include <stdbool.h>
#include <stddef.h>
#include <ghostty/vt/types.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
*/
GHOSTTY_API bool ghostty_paste_is_safe(const char* data, size_t len);
/**
* Encode paste data for writing to the terminal pty.
*
* This function prepares paste data for terminal input by:
* - Stripping unsafe control bytes (NUL, ESC, DEL, etc.) by replacing
* them with spaces
* - Wrapping the data in bracketed paste sequences if @p bracketed is true
* - Replacing newlines with carriage returns if @p bracketed is false
*
* The input @p data buffer is modified in place during encoding. The
* encoded result (potentially with bracketed paste prefix/suffix) is
* written to the output buffer.
*
* If the output buffer is too small, the function returns
* GHOSTTY_OUT_OF_SPACE and sets the required size in @p out_written.
* The caller can then retry with a sufficiently sized buffer.
*
* @param data The paste data to encode (modified in place, may be NULL)
* @param data_len The length of the input data in bytes
* @param bracketed Whether bracketed paste mode is active
* @param buf Output buffer to write the encoded result into (may be NULL)
* @param buf_len Size of the output buffer in bytes
* @param[out] out_written On success, the number of bytes written. On
* GHOSTTY_OUT_OF_SPACE, the required buffer size.
* @return GHOSTTY_SUCCESS on success, GHOSTTY_OUT_OF_SPACE if the buffer
* is too small
*/
GHOSTTY_API GhosttyResult ghostty_paste_encode(
char* data,
size_t data_len,
bool bracketed,
char* buf,
size_t buf_len,
size_t* out_written);
#ifdef __cplusplus
}
#endif
/** @} */
#endif /* GHOSTTY_VT_PASTE_H */
@@ -0,0 +1,89 @@
/**
* @file point.h
*
* Terminal point types for referencing locations in the terminal grid.
*/
#ifndef GHOSTTY_VT_POINT_H
#define GHOSTTY_VT_POINT_H
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
/** @defgroup point Point
*
* Types for referencing x/y positions in the terminal grid under
* different coordinate systems (active area, viewport, full screen,
* scrollback history).
*
* @{
*/
/**
* A coordinate in the terminal grid.
*
* @ingroup point
*/
typedef struct {
/** Column (0-indexed). */
uint16_t x;
/** Row (0-indexed). May exceed page size for screen/history tags. */
uint32_t y;
} GhosttyPointCoordinate;
/**
* Point reference tag.
*
* Determines which coordinate system a point uses.
*
* @ingroup point
*/
typedef enum GHOSTTY_ENUM_TYPED {
/** Active area where the cursor can move. */
GHOSTTY_POINT_TAG_ACTIVE = 0,
/** Visible viewport (changes when scrolled). */
GHOSTTY_POINT_TAG_VIEWPORT = 1,
/** Full screen including scrollback. */
GHOSTTY_POINT_TAG_SCREEN = 2,
/** Scrollback history only (before active area). */
GHOSTTY_POINT_TAG_HISTORY = 3,
GHOSTTY_POINT_TAG_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
} GhosttyPointTag;
/**
* Point value union.
*
* @ingroup point
*/
typedef union {
/** Coordinate (used for all tag variants). */
GhosttyPointCoordinate coordinate;
/** Padding for ABI compatibility. Do not use. */
uint64_t _padding[2];
} GhosttyPointValue;
/**
* Tagged union for a point in the terminal grid.
*
* @ingroup point
*/
typedef struct {
GhosttyPointTag tag;
GhosttyPointValue value;
} GhosttyPoint;
/** @} */
#ifdef __cplusplus
}
#endif
#endif /* GHOSTTY_VT_POINT_H */
@@ -0,0 +1,729 @@
/**
* @file render.h
*
* Render state for creating high performance renderers.
*/
#ifndef GHOSTTY_VT_RENDER_H
#define GHOSTTY_VT_RENDER_H
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <ghostty/vt/allocator.h>
#include <ghostty/vt/color.h>
#include <ghostty/vt/terminal.h>
#include <ghostty/vt/types.h>
#ifdef __cplusplus
extern "C" {
#endif
/** @defgroup render Render State
*
* Represents the state required to render a visible screen (a viewport)
* of a terminal instance. This is stateful and optimized for repeated
* updates from a single terminal instance and only updating dirty regions
* of the screen.
*
* The key design principle of this API is that it only needs read/write
* access to the terminal instance during the update call. This allows
* the render state to minimally impact terminal IO performance and also
* allows the renderer to be safely multi-threaded (as long as a lock is
* held during the update call to ensure exclusive access to the terminal
* instance).
*
* The basic usage of this API is:
*
* 1. Create an empty render state
* 2. Update it from a terminal instance whenever you need.
* 3. Read from the render state to get the data needed to draw your frame.
*
* ## Dirty Tracking
*
* Dirty tracking is a key feature of the render state that allows renderers
* to efficiently determine what parts of the screen have changed and only
* redraw changed regions.
*
* The render state API keeps track of dirty state at two independent layers:
* a global dirty state that indicates whether the entire frame is clean,
* partially dirty, or fully dirty, and a per-row dirty state that allows
* tracking which rows in a partially dirty frame have changed.
*
* The user of the render state API is expected to unset both of these.
* The `update` call does not unset dirty state, it only updates it.
*
* An extremely important detail: setting one dirty state doesn't unset
* the other. For example, setting the global dirty state to false does not
* reset the row-level dirty flags. So, the caller of the render state API must
* be careful to manage both layers of dirty state correctly.
*
* ## Examples
*
* ### Creating and updating render state
* @snippet c-vt-render/src/main.c render-state-update
*
* ### Checking dirty state
* @snippet c-vt-render/src/main.c render-dirty-check
*
* ### Reading colors
* @snippet c-vt-render/src/main.c render-colors
*
* ### Reading cursor state
* @snippet c-vt-render/src/main.c render-cursor
*
* ### Iterating rows and cells
* @snippet c-vt-render/src/main.c render-row-iterate
*
* ### Resetting dirty state after rendering
* @snippet c-vt-render/src/main.c render-dirty-reset
*
* @{
*/
/**
* Dirty state of a render state after update.
*
* @ingroup render
*/
typedef enum GHOSTTY_ENUM_TYPED {
/** Not dirty at all; rendering can be skipped. */
GHOSTTY_RENDER_STATE_DIRTY_FALSE = 0,
/** Some rows changed; renderer can redraw incrementally. */
GHOSTTY_RENDER_STATE_DIRTY_PARTIAL = 1,
/** Global state changed; renderer should redraw everything. */
GHOSTTY_RENDER_STATE_DIRTY_FULL = 2,
GHOSTTY_RENDER_STATE_DIRTY_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
} GhosttyRenderStateDirty;
/**
* Visual style of the cursor.
*
* @ingroup render
*/
typedef enum GHOSTTY_ENUM_TYPED {
/** Bar cursor (DECSCUSR 5, 6). */
GHOSTTY_RENDER_STATE_CURSOR_VISUAL_STYLE_BAR = 0,
/** Block cursor (DECSCUSR 1, 2). */
GHOSTTY_RENDER_STATE_CURSOR_VISUAL_STYLE_BLOCK = 1,
/** Underline cursor (DECSCUSR 3, 4). */
GHOSTTY_RENDER_STATE_CURSOR_VISUAL_STYLE_UNDERLINE = 2,
/** Hollow block cursor. */
GHOSTTY_RENDER_STATE_CURSOR_VISUAL_STYLE_BLOCK_HOLLOW = 3,
GHOSTTY_RENDER_STATE_CURSOR_VISUAL_STYLE_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
} GhosttyRenderStateCursorVisualStyle;
/**
* Queryable data kinds for ghostty_render_state_get().
*
* @ingroup render
*/
typedef enum GHOSTTY_ENUM_TYPED {
/** Invalid / sentinel value. */
GHOSTTY_RENDER_STATE_DATA_INVALID = 0,
/** Viewport width in cells (uint16_t). */
GHOSTTY_RENDER_STATE_DATA_COLS = 1,
/** Viewport height in cells (uint16_t). */
GHOSTTY_RENDER_STATE_DATA_ROWS = 2,
/** Current dirty state (GhosttyRenderStateDirty). */
GHOSTTY_RENDER_STATE_DATA_DIRTY = 3,
/** Populate a pre-allocated GhosttyRenderStateRowIterator with row data
* from the render state (GhosttyRenderStateRowIterator). Row data is
* only valid as long as the underlying render state is not updated.
* It is unsafe to use row data after updating the render state.
* */
GHOSTTY_RENDER_STATE_DATA_ROW_ITERATOR = 4,
/** Default/current background color (GhosttyColorRgb). */
GHOSTTY_RENDER_STATE_DATA_COLOR_BACKGROUND = 5,
/** Default/current foreground color (GhosttyColorRgb). */
GHOSTTY_RENDER_STATE_DATA_COLOR_FOREGROUND = 6,
/** Cursor color when explicitly set by terminal state (GhosttyColorRgb).
* Returns GHOSTTY_INVALID_VALUE if no explicit cursor color is set;
* use COLOR_CURSOR_HAS_VALUE to check first. */
GHOSTTY_RENDER_STATE_DATA_COLOR_CURSOR = 7,
/** Whether an explicit cursor color is set (bool). */
GHOSTTY_RENDER_STATE_DATA_COLOR_CURSOR_HAS_VALUE = 8,
/** The active 256-color palette (GhosttyColorRgb[256]). */
GHOSTTY_RENDER_STATE_DATA_COLOR_PALETTE = 9,
/** The visual style of the cursor (GhosttyRenderStateCursorVisualStyle). */
GHOSTTY_RENDER_STATE_DATA_CURSOR_VISUAL_STYLE = 10,
/** Whether the cursor is visible based on terminal modes (bool). */
GHOSTTY_RENDER_STATE_DATA_CURSOR_VISIBLE = 11,
/** Whether the cursor should blink based on terminal modes (bool). */
GHOSTTY_RENDER_STATE_DATA_CURSOR_BLINKING = 12,
/** Whether the cursor is at a password input field (bool). */
GHOSTTY_RENDER_STATE_DATA_CURSOR_PASSWORD_INPUT = 13,
/** Whether the cursor is visible within the viewport (bool).
* If false, the cursor viewport position values are undefined. */
GHOSTTY_RENDER_STATE_DATA_CURSOR_VIEWPORT_HAS_VALUE = 14,
/** Cursor viewport x position in cells (uint16_t).
* Only valid when CURSOR_VIEWPORT_HAS_VALUE is true. */
GHOSTTY_RENDER_STATE_DATA_CURSOR_VIEWPORT_X = 15,
/** Cursor viewport y position in cells (uint16_t).
* Only valid when CURSOR_VIEWPORT_HAS_VALUE is true. */
GHOSTTY_RENDER_STATE_DATA_CURSOR_VIEWPORT_Y = 16,
/** Whether the cursor is on the tail of a wide character (bool).
* Only valid when CURSOR_VIEWPORT_HAS_VALUE is true. */
GHOSTTY_RENDER_STATE_DATA_CURSOR_VIEWPORT_WIDE_TAIL = 17,
GHOSTTY_RENDER_STATE_DATA_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
} GhosttyRenderStateData;
/**
* Settable options for ghostty_render_state_set().
*
* @ingroup render
*/
typedef enum GHOSTTY_ENUM_TYPED {
/** Set dirty state (GhosttyRenderStateDirty). */
GHOSTTY_RENDER_STATE_OPTION_DIRTY = 0,
GHOSTTY_RENDER_STATE_OPTION_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
} GhosttyRenderStateOption;
/**
* Queryable data kinds for ghostty_render_state_row_get().
*
* @ingroup render
*/
typedef enum GHOSTTY_ENUM_TYPED {
/** Invalid / sentinel value. */
GHOSTTY_RENDER_STATE_ROW_DATA_INVALID = 0,
/** Whether the current row is dirty (bool). */
GHOSTTY_RENDER_STATE_ROW_DATA_DIRTY = 1,
/** The raw row value (GhosttyRow). */
GHOSTTY_RENDER_STATE_ROW_DATA_RAW = 2,
/** Populate a pre-allocated GhosttyRenderStateRowCells with cell data for
* the current row (GhosttyRenderStateRowCells). Cell data is only
* valid as long as the underlying render state is not updated.
* It is unsafe to use cell data after updating the render state. */
GHOSTTY_RENDER_STATE_ROW_DATA_CELLS = 3,
/** Row-local selected cell range (GhosttyRenderStateRowSelection). */
GHOSTTY_RENDER_STATE_ROW_DATA_SELECTION = 4,
GHOSTTY_RENDER_STATE_ROW_DATA_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
} GhosttyRenderStateRowData;
/**
* Settable options for ghostty_render_state_row_set().
*
* @ingroup render
*/
typedef enum GHOSTTY_ENUM_TYPED {
/** Set dirty state for the current row (bool). */
GHOSTTY_RENDER_STATE_ROW_OPTION_DIRTY = 0,
GHOSTTY_RENDER_STATE_ROW_OPTION_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
} GhosttyRenderStateRowOption;
/**
* Row-local selection range.
*
* This struct uses the sized-struct ABI pattern. Initialize with
* GHOSTTY_INIT_SIZED(GhosttyRenderStateRowSelection) before querying
* GHOSTTY_RENDER_STATE_ROW_DATA_SELECTION.
*
* Querying GHOSTTY_RENDER_STATE_ROW_DATA_SELECTION returns GHOSTTY_NO_VALUE
* if the current row does not intersect the current selection.
*
* @ingroup render
*/
typedef struct {
/** Size of this struct in bytes. Must be set to sizeof(GhosttyRenderStateRowSelection). */
size_t size;
/** Start column of the row-local selection range, inclusive. */
uint16_t start_x;
/** End column of the row-local selection range, inclusive. */
uint16_t end_x;
} GhosttyRenderStateRowSelection;
/**
* Render-state color information.
*
* This struct uses the sized-struct ABI pattern. Initialize with
* GHOSTTY_INIT_SIZED(GhosttyRenderStateColors) before calling
* ghostty_render_state_colors_get().
*
* Example:
* @code
* GhosttyRenderStateColors colors = GHOSTTY_INIT_SIZED(GhosttyRenderStateColors);
* GhosttyResult result = ghostty_render_state_colors_get(state, &colors);
* @endcode
*
* @ingroup render
*/
typedef struct {
/** Size of this struct in bytes. Must be set to sizeof(GhosttyRenderStateColors). */
size_t size;
/** The default/current background color for the render state. */
GhosttyColorRgb background;
/** The default/current foreground color for the render state. */
GhosttyColorRgb foreground;
/** The cursor color when explicitly set by terminal state. */
GhosttyColorRgb cursor;
/**
* True when cursor contains a valid explicit cursor color value.
* If this is false, the cursor color should be ignored; it will
* contain undefined data.
* */
bool cursor_has_value;
/** The active 256-color palette for this render state. */
GhosttyColorRgb palette[256];
} GhosttyRenderStateColors;
/**
* Create a new render state instance.
*
* @param allocator Pointer to allocator, or NULL to use the default allocator
* @param state Pointer to store the created render state handle
* @return GHOSTTY_SUCCESS on success, GHOSTTY_OUT_OF_MEMORY on allocation
* failure
*
* @ingroup render
*/
GHOSTTY_API GhosttyResult ghostty_render_state_new(const GhosttyAllocator* allocator,
GhosttyRenderState* state);
/**
* Free a render state instance.
*
* Releases all resources associated with the render state. After this call,
* the render state handle becomes invalid.
*
* @param state The render state handle to free (may be NULL)
*
* @ingroup render
*/
GHOSTTY_API void ghostty_render_state_free(GhosttyRenderState state);
/**
* Update a render state instance from a terminal.
*
* This consumes terminal/screen dirty state in the same way as the internal
* render state update path.
*
* @param state The render state handle (NULL returns GHOSTTY_INVALID_VALUE)
* @param terminal The terminal handle to read from (NULL returns GHOSTTY_INVALID_VALUE)
* @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if `state` or
* `terminal` is NULL, GHOSTTY_OUT_OF_MEMORY if updating the state requires
* allocation and that allocation fails
*
* @ingroup render
*/
GHOSTTY_API GhosttyResult ghostty_render_state_update(GhosttyRenderState state,
GhosttyTerminal terminal);
/**
* Get a value from a render state.
*
* The `out` pointer must point to a value of the type corresponding to the
* requested data kind (see GhosttyRenderStateData).
*
* @param state The render state handle (NULL returns GHOSTTY_INVALID_VALUE)
* @param data The data kind to query
* @param[out] out Pointer to receive the queried value
* @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if `state` is
* NULL or `data` is not a recognized enum value
*
* @ingroup render
*/
GHOSTTY_API GhosttyResult ghostty_render_state_get(GhosttyRenderState state,
GhosttyRenderStateData data,
void* out);
/**
* Get multiple data fields from a render state in a single call.
*
* Each element in the keys array specifies a data kind, and the
* corresponding element in the values array receives the result.
*
* Processing stops at the first error; on success out_written
* is set to count, on error it is set to the index of the
* failing key (i.e. the number of values successfully written).
*
* @param state The render state handle (NULL returns GHOSTTY_INVALID_VALUE)
* @param count Number of key/value pairs
* @param keys Array of data kinds to query
* @param values Array of output pointers (types must match each key's
* documented output type)
* @param[out] out_written On return, receives the number of values
* successfully written (may be NULL)
* @return GHOSTTY_SUCCESS if all queries succeed
*
* @ingroup render
*/
GHOSTTY_API GhosttyResult ghostty_render_state_get_multi(
GhosttyRenderState state,
size_t count,
const GhosttyRenderStateData* keys,
void** values,
size_t* out_written);
/**
* Set an option on a render state.
*
* The `value` pointer must point to a value of the type corresponding to the
* requested option kind (see GhosttyRenderStateOption).
*
* @param state The render state handle (NULL returns GHOSTTY_INVALID_VALUE)
* @param option The option to set
* @param[in] value Pointer to the value to set (NULL returns
* GHOSTTY_INVALID_VALUE)
* @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if `state` or
* `value` is NULL
*
* @ingroup render
*/
GHOSTTY_API GhosttyResult ghostty_render_state_set(GhosttyRenderState state,
GhosttyRenderStateOption option,
const void* value);
/**
* Get the current color information from a render state.
*
* This writes as many fields as fit in the caller-provided sized struct.
* `out_colors->size` must be set by the caller (typically via
* GHOSTTY_INIT_SIZED(GhosttyRenderStateColors)).
*
* @param state The render state handle (NULL returns GHOSTTY_INVALID_VALUE)
* @param[out] out_colors Sized output struct to receive render-state colors
* @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if `state` or
* `out_colors` is NULL, or if `out_colors->size` is smaller than
* `sizeof(size_t)`
*
* @ingroup render
*/
GHOSTTY_API GhosttyResult ghostty_render_state_colors_get(GhosttyRenderState state,
GhosttyRenderStateColors* out_colors);
/**
* Create a new row iterator instance.
*
* All fields except the allocator are left undefined until populated
* via ghostty_render_state_get() with
* GHOSTTY_RENDER_STATE_DATA_ROW_ITERATOR.
*
* @param allocator Pointer to allocator, or NULL to use the default allocator
* @param[out] out_iterator On success, receives the created iterator handle
* @return GHOSTTY_SUCCESS on success, GHOSTTY_OUT_OF_MEMORY on allocation
* failure
*
* @ingroup render
*/
GHOSTTY_API GhosttyResult ghostty_render_state_row_iterator_new(
const GhosttyAllocator* allocator,
GhosttyRenderStateRowIterator* out_iterator);
/**
* Free a render-state row iterator.
*
* @param iterator The iterator handle to free (may be NULL)
*
* @ingroup render
*/
GHOSTTY_API void ghostty_render_state_row_iterator_free(GhosttyRenderStateRowIterator iterator);
/**
* Move a render-state row iterator to the next row.
*
* Returns true if the iterator moved successfully and row data is
* available to read at the new position.
*
* @param iterator The iterator handle to advance (may be NULL)
* @return true if advanced to the next row, false if `iterator` is
* NULL or if the iterator has reached the end
*
* @ingroup render
*/
GHOSTTY_API bool ghostty_render_state_row_iterator_next(GhosttyRenderStateRowIterator iterator);
/**
* Get a value from the current row in a render-state row iterator.
*
* The `out` pointer must point to a value of the type corresponding to the
* requested data kind (see GhosttyRenderStateRowData).
* Call ghostty_render_state_row_iterator_next() at least once before
* calling this function.
*
* @param iterator The iterator handle to query (NULL returns GHOSTTY_INVALID_VALUE)
* @param data The data kind to query
* @param[out] out Pointer to receive the queried value
* @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if
* `iterator` is NULL or the iterator is not positioned on a row
*
* @ingroup render
*/
GHOSTTY_API GhosttyResult ghostty_render_state_row_get(
GhosttyRenderStateRowIterator iterator,
GhosttyRenderStateRowData data,
void* out);
/**
* Get multiple data fields from the current row in a single call.
*
* Each element in the keys array specifies a data kind, and the
* corresponding element in the values array receives the result.
*
* Processing stops at the first error; on success out_written
* is set to count, on error it is set to the index of the
* failing key (i.e. the number of values successfully written).
*
* @param iterator The iterator handle (NULL returns GHOSTTY_INVALID_VALUE)
* @param count Number of key/value pairs
* @param keys Array of data kinds to query
* @param values Array of output pointers (types must match each key's
* documented output type)
* @param[out] out_written On return, receives the number of values
* successfully written (may be NULL)
* @return GHOSTTY_SUCCESS if all queries succeed
*
* @ingroup render
*/
GHOSTTY_API GhosttyResult ghostty_render_state_row_get_multi(
GhosttyRenderStateRowIterator iterator,
size_t count,
const GhosttyRenderStateRowData* keys,
void** values,
size_t* out_written);
/**
* Set an option on the current row in a render-state row iterator.
*
* The `value` pointer must point to a value of the type corresponding to the
* requested option kind (see GhosttyRenderStateRowOption).
* Call ghostty_render_state_row_iterator_next() at least once before
* calling this function.
*
* @param iterator The iterator handle to update (NULL returns GHOSTTY_INVALID_VALUE)
* @param option The option to set
* @param[in] value Pointer to the value to set (NULL returns
* GHOSTTY_INVALID_VALUE)
* @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if
* `iterator` is NULL or the iterator is not positioned on a row
*
* @ingroup render
*/
GHOSTTY_API GhosttyResult ghostty_render_state_row_set(
GhosttyRenderStateRowIterator iterator,
GhosttyRenderStateRowOption option,
const void* value);
/**
* Create a new row cells instance.
*
* All fields except the allocator are left undefined until populated
* via ghostty_render_state_row_get() with
* GHOSTTY_RENDER_STATE_ROW_DATA_CELLS.
*
* You can reuse this value repeatedly with ghostty_render_state_row_get() to
* avoid allocating a new cells container for every row.
*
* @param allocator Pointer to allocator, or NULL to use the default allocator
* @param[out] out_cells On success, receives the created row cells handle
* @return GHOSTTY_SUCCESS on success, GHOSTTY_OUT_OF_MEMORY on allocation
* failure
*
* @ingroup render
*/
GHOSTTY_API GhosttyResult ghostty_render_state_row_cells_new(
const GhosttyAllocator* allocator,
GhosttyRenderStateRowCells* out_cells);
/**
* Queryable data kinds for ghostty_render_state_row_cells_get().
*
* @ingroup render
*/
typedef enum GHOSTTY_ENUM_TYPED {
/** Invalid / sentinel value. */
GHOSTTY_RENDER_STATE_ROW_CELLS_DATA_INVALID = 0,
/** The raw cell value (GhosttyCell). */
GHOSTTY_RENDER_STATE_ROW_CELLS_DATA_RAW = 1,
/** The style for the current cell (GhosttyStyle). */
GHOSTTY_RENDER_STATE_ROW_CELLS_DATA_STYLE = 2,
/** The total number of grapheme codepoints including the base codepoint
* (uint32_t). Returns 0 if the cell has no text. */
GHOSTTY_RENDER_STATE_ROW_CELLS_DATA_GRAPHEMES_LEN = 3,
/** Write grapheme codepoints into a caller-provided buffer (uint32_t*).
* The buffer must be at least graphemes_len elements. The base codepoint
* is written first, followed by any extra codepoints. */
GHOSTTY_RENDER_STATE_ROW_CELLS_DATA_GRAPHEMES_BUF = 4,
/** The resolved background color of the cell (GhosttyColorRgb).
* Flattens the three possible sources: content-tag bg_color_rgb,
* content-tag bg_color_palette (looked up in the palette), or the
* style's bg_color. Returns GHOSTTY_INVALID_VALUE if the cell has
* no background color, in which case the caller should use whatever
* default background color it wants (e.g. the terminal background). */
GHOSTTY_RENDER_STATE_ROW_CELLS_DATA_BG_COLOR = 5,
/** The resolved foreground color of the cell (GhosttyColorRgb).
* Resolves palette indices through the palette. Bold color handling
* is not applied; the caller should handle bold styling separately.
* Returns GHOSTTY_INVALID_VALUE if the cell has no explicit foreground
* color, in which case the caller should use whatever default foreground
* color it wants (e.g. the terminal foreground). */
GHOSTTY_RENDER_STATE_ROW_CELLS_DATA_FG_COLOR = 6,
/** Whether the cell is contained within the current selection (bool).
* This returns true when the cell's column is within the current row's
* row-local selection range, and false otherwise. Rendering policy for
* selected cells (colors, inversion, etc.) is left to the caller.
*
* Renderers that can draw cells in spans may be more efficient querying
* GHOSTTY_RENDER_STATE_ROW_DATA_SELECTION once per row and applying that
* range directly, avoiding one C API call per cell for selection state. */
GHOSTTY_RENDER_STATE_ROW_CELLS_DATA_SELECTED = 7,
/** Whether the cell has any explicit styling (bool).
* This is equivalent to querying the raw cell's
* GHOSTTY_CELL_DATA_HAS_STYLING value, but avoids materializing the raw
* GhosttyCell for renderers that only need to know whether fetching the
* full style is necessary. */
GHOSTTY_RENDER_STATE_ROW_CELLS_DATA_HAS_STYLING = 8,
/**
* Encode the current cell's full grapheme cluster as UTF-8 into a
* caller-provided buffer (GhosttyBuffer).
*
* The base codepoint is encoded first, followed by any extra grapheme
* codepoints. Returns GHOSTTY_SUCCESS with len=0 when the cell has no text.
*
* If ptr is NULL or cap is too small for a non-empty cell, returns
* GHOSTTY_OUT_OF_SPACE without writing any bytes and sets len to the required
* buffer size in bytes.
*/
GHOSTTY_RENDER_STATE_ROW_CELLS_DATA_GRAPHEMES_UTF8 = 9,
GHOSTTY_RENDER_STATE_ROW_CELLS_DATA_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
} GhosttyRenderStateRowCellsData;
/**
* Move a render-state row cells iterator to the next cell.
*
* Returns true if the iterator moved successfully and cell data is
* available to read at the new position.
*
* @param cells The row cells handle to advance (may be NULL)
* @return true if advanced to the next cell, false if `cells` is
* NULL or if the iterator has reached the end
*
* @ingroup render
*/
GHOSTTY_API bool ghostty_render_state_row_cells_next(GhosttyRenderStateRowCells cells);
/**
* Move a render-state row cells iterator to a specific column.
*
* Positions the iterator at the given x (column) index so that
* subsequent reads return data for that cell.
*
* @param cells The row cells handle to reposition (NULL returns
* GHOSTTY_INVALID_VALUE)
* @param x The zero-based column index to select
* @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if `cells`
* is NULL or `x` is out of range
*
* @ingroup render
*/
GHOSTTY_API GhosttyResult ghostty_render_state_row_cells_select(
GhosttyRenderStateRowCells cells, uint16_t x);
/**
* Get a value from the current cell in a render-state row cells iterator.
*
* The `out` pointer must point to a value of the type corresponding to the
* requested data kind (see GhosttyRenderStateRowCellsData).
* Call ghostty_render_state_row_cells_next() or
* ghostty_render_state_row_cells_select() at least once before
* calling this function.
*
* @param cells The row cells handle to query (NULL returns GHOSTTY_INVALID_VALUE)
* @param data The data kind to query
* @param[out] out Pointer to receive the queried value
* @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if
* `cells` is NULL or the iterator is not positioned on a cell
*
* @ingroup render
*/
GHOSTTY_API GhosttyResult ghostty_render_state_row_cells_get(
GhosttyRenderStateRowCells cells,
GhosttyRenderStateRowCellsData data,
void* out);
/**
* Get multiple data fields from the current cell in a single call.
*
* Each element in the keys array specifies a data kind, and the
* corresponding element in the values array receives the result.
*
* Processing stops at the first error; on success out_written
* is set to count, on error it is set to the index of the
* failing key (i.e. the number of values successfully written).
*
* @param cells The row cells handle (NULL returns GHOSTTY_INVALID_VALUE)
* @param count Number of key/value pairs
* @param keys Array of data kinds to query
* @param values Array of output pointers (types must match each key's
* documented output type)
* @param[out] out_written On return, receives the number of values
* successfully written (may be NULL)
* @return GHOSTTY_SUCCESS if all queries succeed
*
* @ingroup render
*/
GHOSTTY_API GhosttyResult ghostty_render_state_row_cells_get_multi(
GhosttyRenderStateRowCells cells,
size_t count,
const GhosttyRenderStateRowCellsData* keys,
void** values,
size_t* out_written);
/**
* Free a row cells instance.
*
* @param cells The row cells handle to free (may be NULL)
*
* @ingroup render
*/
GHOSTTY_API void ghostty_render_state_row_cells_free(GhosttyRenderStateRowCells cells);
/** @} */
#ifdef __cplusplus
}
#endif
#endif /* GHOSTTY_VT_RENDER_H */
@@ -0,0 +1,400 @@
/**
* @file screen.h
*
* Terminal screen cell and row types.
*/
#ifndef GHOSTTY_VT_SCREEN_H
#define GHOSTTY_VT_SCREEN_H
#include <stdbool.h>
#include <stdint.h>
#include <ghostty/vt/color.h>
#include <ghostty/vt/types.h>
#ifdef __cplusplus
extern "C" {
#endif
/** @defgroup screen Screen
*
* Terminal screen cell and row types.
*
* These types represent the contents of a terminal screen. A GhosttyCell
* is a single grid cell and a GhosttyRow is a single row. Both are opaque
* values whose fields are accessed via ghostty_cell_get() and
* ghostty_row_get() respectively.
*
* @{
*/
/**
* Opaque cell value.
*
* Represents a single terminal cell. The internal layout is opaque and
* must be queried via ghostty_cell_get(). Obtain cell values from
* terminal query APIs.
*
* @ingroup screen
*/
typedef uint64_t GhosttyCell;
/**
* Opaque row value.
*
* Represents a single terminal row. The internal layout is opaque and
* must be queried via ghostty_row_get(). Obtain row values from
* terminal query APIs.
*
* @ingroup screen
*/
typedef uint64_t GhosttyRow;
/**
* Cell content tag.
*
* Describes what kind of content a cell holds.
*
* @ingroup screen
*/
typedef enum GHOSTTY_ENUM_TYPED {
/** A single codepoint (may be zero for empty). */
GHOSTTY_CELL_CONTENT_CODEPOINT = 0,
/** A codepoint that is part of a multi-codepoint grapheme cluster. */
GHOSTTY_CELL_CONTENT_CODEPOINT_GRAPHEME = 1,
/** No text; background color from palette. */
GHOSTTY_CELL_CONTENT_BG_COLOR_PALETTE = 2,
/** No text; background color as RGB. */
GHOSTTY_CELL_CONTENT_BG_COLOR_RGB = 3,
GHOSTTY_CELL_CONTENT_TAG_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
} GhosttyCellContentTag;
/**
* Cell wide property.
*
* Describes the width behavior of a cell.
*
* @ingroup screen
*/
typedef enum GHOSTTY_ENUM_TYPED {
/** Not a wide character, cell width 1. */
GHOSTTY_CELL_WIDE_NARROW = 0,
/** Wide character, cell width 2. */
GHOSTTY_CELL_WIDE_WIDE = 1,
/** Spacer after wide character. Do not render. */
GHOSTTY_CELL_WIDE_SPACER_TAIL = 2,
/** Spacer at end of soft-wrapped line for a wide character. */
GHOSTTY_CELL_WIDE_SPACER_HEAD = 3,
GHOSTTY_CELL_WIDE_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
} GhosttyCellWide;
/**
* Semantic content type of a cell.
*
* Set by semantic prompt sequences (OSC 133) to distinguish between
* command output, user input, and shell prompt text.
*
* @ingroup screen
*/
typedef enum GHOSTTY_ENUM_TYPED {
/** Regular output content, such as command output. */
GHOSTTY_CELL_SEMANTIC_OUTPUT = 0,
/** Content that is part of user input. */
GHOSTTY_CELL_SEMANTIC_INPUT = 1,
/** Content that is part of a shell prompt. */
GHOSTTY_CELL_SEMANTIC_PROMPT = 2,
GHOSTTY_CELL_SEMANTIC_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
} GhosttyCellSemanticContent;
/**
* Cell data types.
*
* These values specify what type of data to extract from a cell
* using `ghostty_cell_get`.
*
* @ingroup screen
*/
typedef enum GHOSTTY_ENUM_TYPED {
/** Invalid data type. Never results in any data extraction. */
GHOSTTY_CELL_DATA_INVALID = 0,
/**
* The codepoint of the cell (0 if empty or bg-color-only).
*
* Output type: uint32_t *
*/
GHOSTTY_CELL_DATA_CODEPOINT = 1,
/**
* The content tag describing what kind of content is in the cell.
*
* Output type: GhosttyCellContentTag *
*/
GHOSTTY_CELL_DATA_CONTENT_TAG = 2,
/**
* The wide property of the cell.
*
* Output type: GhosttyCellWide *
*/
GHOSTTY_CELL_DATA_WIDE = 3,
/**
* Whether the cell has text to render.
*
* Output type: bool *
*/
GHOSTTY_CELL_DATA_HAS_TEXT = 4,
/**
* Whether the cell has non-default styling.
*
* Output type: bool *
*/
GHOSTTY_CELL_DATA_HAS_STYLING = 5,
/**
* The style ID for the cell (for use with style lookups).
*
* Output type: uint16_t *
*/
GHOSTTY_CELL_DATA_STYLE_ID = 6,
/**
* Whether the cell has a hyperlink.
*
* Output type: bool *
*/
GHOSTTY_CELL_DATA_HAS_HYPERLINK = 7,
/**
* Whether the cell is protected.
*
* Output type: bool *
*/
GHOSTTY_CELL_DATA_PROTECTED = 8,
/**
* The semantic content type of the cell (from OSC 133).
*
* Output type: GhosttyCellSemanticContent *
*/
GHOSTTY_CELL_DATA_SEMANTIC_CONTENT = 9,
/**
* The palette index for the cell's background color.
* Only valid when content_tag is GHOSTTY_CELL_CONTENT_BG_COLOR_PALETTE.
*
* Output type: GhosttyColorPaletteIndex *
*/
GHOSTTY_CELL_DATA_COLOR_PALETTE = 10,
/**
* The RGB value for the cell's background color.
* Only valid when content_tag is GHOSTTY_CELL_CONTENT_BG_COLOR_RGB.
*
* Output type: GhosttyColorRgb *
*/
GHOSTTY_CELL_DATA_COLOR_RGB = 11,
GHOSTTY_CELL_DATA_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
} GhosttyCellData;
/**
* Row semantic prompt state.
*
* Indicates whether any cells in a row are part of a shell prompt,
* as reported by OSC 133 sequences.
*
* @ingroup screen
*/
typedef enum GHOSTTY_ENUM_TYPED {
/** No prompt cells in this row. */
GHOSTTY_ROW_SEMANTIC_NONE = 0,
/** Prompt cells exist and this is a primary prompt line. */
GHOSTTY_ROW_SEMANTIC_PROMPT = 1,
/** Prompt cells exist and this is a continuation line. */
GHOSTTY_ROW_SEMANTIC_PROMPT_CONTINUATION = 2,
GHOSTTY_ROW_SEMANTIC_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
} GhosttyRowSemanticPrompt;
/**
* Row data types.
*
* These values specify what type of data to extract from a row
* using `ghostty_row_get`.
*
* @ingroup screen
*/
typedef enum GHOSTTY_ENUM_TYPED {
/** Invalid data type. Never results in any data extraction. */
GHOSTTY_ROW_DATA_INVALID = 0,
/**
* Whether this row is soft-wrapped.
*
* Output type: bool *
*/
GHOSTTY_ROW_DATA_WRAP = 1,
/**
* Whether this row is a continuation of a soft-wrapped row.
*
* Output type: bool *
*/
GHOSTTY_ROW_DATA_WRAP_CONTINUATION = 2,
/**
* Whether any cells in this row have grapheme clusters.
*
* Output type: bool *
*/
GHOSTTY_ROW_DATA_GRAPHEME = 3,
/**
* Whether any cells in this row have styling (may have false positives).
*
* Output type: bool *
*/
GHOSTTY_ROW_DATA_STYLED = 4,
/**
* Whether any cells in this row have hyperlinks (may have false positives).
*
* Output type: bool *
*/
GHOSTTY_ROW_DATA_HYPERLINK = 5,
/**
* The semantic prompt state of this row.
*
* Output type: GhosttyRowSemanticPrompt *
*/
GHOSTTY_ROW_DATA_SEMANTIC_PROMPT = 6,
/**
* Whether this row contains a Kitty virtual placeholder.
*
* Output type: bool *
*/
GHOSTTY_ROW_DATA_KITTY_VIRTUAL_PLACEHOLDER = 7,
/**
* Whether this row is dirty and requires a redraw.
*
* Output type: bool *
*/
GHOSTTY_ROW_DATA_DIRTY = 8,
GHOSTTY_ROW_DATA_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
} GhosttyRowData;
/**
* Get data from a cell.
*
* Extracts typed data from the given cell based on the specified
* data type. The output pointer must be of the appropriate type for the
* requested data kind. Valid data types and output types are documented
* in the `GhosttyCellData` enum.
*
* @param cell The cell value
* @param data The type of data to extract
* @param out Pointer to store the extracted data (type depends on data parameter)
* @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if the
* data type is invalid
*
* @ingroup screen
*/
GHOSTTY_API GhosttyResult ghostty_cell_get(GhosttyCell cell,
GhosttyCellData data,
void *out);
/**
* Get multiple data fields from a cell in a single call.
*
* Each element in the keys array specifies a data kind, and the
* corresponding element in the values array receives the result.
*
* Processing stops at the first error; on success out_written
* is set to count, on error it is set to the index of the
* failing key (i.e. the number of values successfully written).
*
* @param cell The cell value
* @param count Number of key/value pairs
* @param keys Array of data kinds to query
* @param values Array of output pointers (types must match each key's
* documented output type)
* @param[out] out_written On return, receives the number of values
* successfully written (may be NULL)
* @return GHOSTTY_SUCCESS if all queries succeed
*
* @ingroup screen
*/
GHOSTTY_API GhosttyResult ghostty_cell_get_multi(GhosttyCell cell,
size_t count,
const GhosttyCellData* keys,
void** values,
size_t* out_written);
/**
* Get data from a row.
*
* Extracts typed data from the given row based on the specified
* data type. The output pointer must be of the appropriate type for the
* requested data kind. Valid data types and output types are documented
* in the `GhosttyRowData` enum.
*
* @param row The row value
* @param data The type of data to extract
* @param out Pointer to store the extracted data (type depends on data parameter)
* @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if the
* data type is invalid
*
* @ingroup screen
*/
GHOSTTY_API GhosttyResult ghostty_row_get(GhosttyRow row,
GhosttyRowData data,
void *out);
/**
* Get multiple data fields from a row in a single call.
*
* Each element in the keys array specifies a data kind, and the
* corresponding element in the values array receives the result.
*
* Processing stops at the first error; on success out_written
* is set to count, on error it is set to the index of the
* failing key (i.e. the number of values successfully written).
*
* @param row The row value
* @param count Number of key/value pairs
* @param keys Array of data kinds to query
* @param values Array of output pointers (types must match each key's
* documented output type)
* @param[out] out_written On return, receives the number of values
* successfully written (may be NULL)
* @return GHOSTTY_SUCCESS if all queries succeed
*
* @ingroup screen
*/
GHOSTTY_API GhosttyResult ghostty_row_get_multi(GhosttyRow row,
size_t count,
const GhosttyRowData* keys,
void** values,
size_t* out_written);
/** @} */
#ifdef __cplusplus
}
#endif
#endif /* GHOSTTY_VT_SCREEN_H */
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,350 @@
/**
* @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
*
* @snippet c-vt-sgr/src/main.c sgr-basic
*
* @{
*/
#include <ghostty/vt/allocator.h>
#include <ghostty/vt/color.h>
#include <ghostty/vt/types.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* 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_ENUM_TYPED {
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_UNDERLINE_COLOR = 8,
GHOSTTY_SGR_ATTR_UNDERLINE_COLOR_256 = 9,
GHOSTTY_SGR_ATTR_RESET_UNDERLINE_COLOR = 10,
GHOSTTY_SGR_ATTR_OVERLINE = 11,
GHOSTTY_SGR_ATTR_RESET_OVERLINE = 12,
GHOSTTY_SGR_ATTR_BLINK = 13,
GHOSTTY_SGR_ATTR_RESET_BLINK = 14,
GHOSTTY_SGR_ATTR_INVERSE = 15,
GHOSTTY_SGR_ATTR_RESET_INVERSE = 16,
GHOSTTY_SGR_ATTR_INVISIBLE = 17,
GHOSTTY_SGR_ATTR_RESET_INVISIBLE = 18,
GHOSTTY_SGR_ATTR_STRIKETHROUGH = 19,
GHOSTTY_SGR_ATTR_RESET_STRIKETHROUGH = 20,
GHOSTTY_SGR_ATTR_DIRECT_COLOR_FG = 21,
GHOSTTY_SGR_ATTR_DIRECT_COLOR_BG = 22,
GHOSTTY_SGR_ATTR_BG_8 = 23,
GHOSTTY_SGR_ATTR_FG_8 = 24,
GHOSTTY_SGR_ATTR_RESET_FG = 25,
GHOSTTY_SGR_ATTR_RESET_BG = 26,
GHOSTTY_SGR_ATTR_BRIGHT_BG_8 = 27,
GHOSTTY_SGR_ATTR_BRIGHT_FG_8 = 28,
GHOSTTY_SGR_ATTR_BG_256 = 29,
GHOSTTY_SGR_ATTR_FG_256 = 30,
GHOSTTY_SGR_ATTR_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
} GhosttySgrAttributeTag;
/**
* Underline style types.
*
* @ingroup sgr
*/
typedef enum GHOSTTY_ENUM_TYPED {
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,
GHOSTTY_SGR_UNDERLINE_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
} 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
*/
GHOSTTY_API 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
*/
GHOSTTY_API 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
*/
GHOSTTY_API 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
*/
GHOSTTY_API 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
*/
GHOSTTY_API 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
*/
GHOSTTY_API 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
*/
GHOSTTY_API 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
*/
GHOSTTY_API 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
*/
GHOSTTY_API 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
*/
GHOSTTY_API 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
*/
GHOSTTY_API void ghostty_wasm_free_sgr_attribute(GhosttySgrAttribute* attr);
#endif
#ifdef __cplusplus
}
#endif
/** @} */
#endif /* GHOSTTY_VT_SGR_H */
@@ -0,0 +1,101 @@
/**
* @file size_report.h
*
* Size report encoding - encode terminal size reports into escape sequences.
*/
#ifndef GHOSTTY_VT_SIZE_REPORT_H
#define GHOSTTY_VT_SIZE_REPORT_H
/** @defgroup size_report Size Report Encoding
*
* Utilities for encoding terminal size reports into escape sequences,
* supporting in-band size reports (mode 2048) and XTWINOPS responses
* (CSI 14 t, CSI 16 t, CSI 18 t).
*
* ## Basic Usage
*
* Use ghostty_size_report_encode() to encode a size report into a
* caller-provided buffer. If the buffer is too small, the function
* returns GHOSTTY_OUT_OF_SPACE and sets the required size in the
* output parameter.
*
* ## Example
*
* @snippet c-vt-size-report/src/main.c size-report-encode
*
* @{
*/
#include <stddef.h>
#include <stdint.h>
#include <ghostty/vt/types.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* Size report style.
*
* Determines the output format for the terminal size report.
*/
typedef enum GHOSTTY_ENUM_TYPED {
/** In-band size report (mode 2048): ESC [ 48 ; rows ; cols ; height ; width t */
GHOSTTY_SIZE_REPORT_MODE_2048 = 0,
/** XTWINOPS text area size in pixels: ESC [ 4 ; height ; width t */
GHOSTTY_SIZE_REPORT_CSI_14_T = 1,
/** XTWINOPS cell size in pixels: ESC [ 6 ; height ; width t */
GHOSTTY_SIZE_REPORT_CSI_16_T = 2,
/** XTWINOPS text area size in characters: ESC [ 8 ; rows ; cols t */
GHOSTTY_SIZE_REPORT_CSI_18_T = 3,
GHOSTTY_SIZE_REPORT_STYLE_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
} GhosttySizeReportStyle;
/**
* Terminal size information for encoding size reports.
*/
typedef struct {
/** Terminal row count in cells. */
uint16_t rows;
/** Terminal column count in cells. */
uint16_t columns;
/** Width of a single terminal cell in pixels. */
uint32_t cell_width;
/** Height of a single terminal cell in pixels. */
uint32_t cell_height;
} GhosttySizeReportSize;
/**
* Encode a terminal size report into an escape sequence.
*
* Encodes a size report in the format specified by @p style into the
* provided buffer.
*
* If the buffer is too small, the function returns GHOSTTY_OUT_OF_SPACE
* and writes the required buffer size to @p out_written. The caller can
* then retry with a sufficiently sized buffer.
*
* @param style The size report format to encode
* @param size Terminal size information
* @param buf Output buffer to write the encoded sequence into (may be NULL)
* @param buf_len Size of the output buffer in bytes
* @param[out] out_written On success, the number of bytes written. On
* GHOSTTY_OUT_OF_SPACE, the required buffer size.
* @return GHOSTTY_SUCCESS on success, GHOSTTY_OUT_OF_SPACE if the buffer
* is too small
*/
GHOSTTY_API GhosttyResult ghostty_size_report_encode(
GhosttySizeReportStyle style,
GhosttySizeReportSize size,
char* buf,
size_t buf_len,
size_t* out_written);
#ifdef __cplusplus
}
#endif
/** @} */
#endif /* GHOSTTY_VT_SIZE_REPORT_H */
@@ -0,0 +1,139 @@
/**
* @file style.h
*
* Terminal cell style types.
*/
#ifndef GHOSTTY_VT_STYLE_H
#define GHOSTTY_VT_STYLE_H
#include <ghostty/vt/color.h>
#include <ghostty/vt/types.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
/** @defgroup style Style
*
* Terminal cell style attributes.
*
* A style describes the visual attributes of a terminal cell, including
* foreground, background, and underline colors, as well as flags for
* bold, italic, underline, and other text decorations.
*
* @{
*/
/**
* Style identifier type.
*
* Used to look up the full style from a grid reference.
* Obtain this from a cell via GHOSTTY_CELL_DATA_STYLE_ID.
*
* @ingroup style
*/
typedef uint16_t GhosttyStyleId;
/**
* Style color tags.
*
* These values identify the type of color in a style color.
* Use the tag to determine which field in the color value union to access.
*
* @ingroup style
*/
typedef enum GHOSTTY_ENUM_TYPED {
GHOSTTY_STYLE_COLOR_NONE = 0,
GHOSTTY_STYLE_COLOR_PALETTE = 1,
GHOSTTY_STYLE_COLOR_RGB = 2,
GHOSTTY_STYLE_COLOR_TAG_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
} GhosttyStyleColorTag;
/**
* Style color value union.
*
* Use the tag to determine which field is active.
*
* @ingroup style
*/
typedef union {
GhosttyColorPaletteIndex palette;
GhosttyColorRgb rgb;
uint64_t _padding;
} GhosttyStyleColorValue;
/**
* Style color (tagged union).
*
* A color used in a style attribute. Can be unset (none), a palette
* index, or a direct RGB value.
*
* @ingroup style
*/
typedef struct {
GhosttyStyleColorTag tag;
GhosttyStyleColorValue value;
} GhosttyStyleColor;
/**
* Terminal cell style.
*
* Describes the complete visual style for a terminal cell, including
* foreground, background, and underline colors, as well as text
* decoration flags. The underline field uses the same values as
* GhosttySgrUnderline.
*
* This is a sized struct. Use GHOSTTY_INIT_SIZED() to initialize it.
*
* @ingroup style
*/
typedef struct {
size_t size;
GhosttyStyleColor fg_color;
GhosttyStyleColor bg_color;
GhosttyStyleColor underline_color;
bool bold;
bool italic;
bool faint;
bool blink;
bool inverse;
bool invisible;
bool strikethrough;
bool overline;
int underline; /**< One of GHOSTTY_SGR_UNDERLINE_* values */
} GhosttyStyle;
/**
* Get the default style.
*
* Initializes the style to the default values (no colors, no flags).
*
* @param style Pointer to the style to initialize
*
* @ingroup style
*/
GHOSTTY_API void ghostty_style_default(GhosttyStyle* style);
/**
* Check if a style is the default style.
*
* Returns true if all colors are unset and all flags are off.
*
* @param style Pointer to the style to check
* @return true if the style is the default style
*
* @ingroup style
*/
GHOSTTY_API bool ghostty_style_is_default(const GhosttyStyle* style);
#ifdef __cplusplus
}
#endif
/** @} */
#endif /* GHOSTTY_VT_STYLE_H */
@@ -0,0 +1,210 @@
/**
* @file sys.h
*
* System interface - runtime-swappable implementations for external dependencies.
*/
#ifndef GHOSTTY_VT_SYS_H
#define GHOSTTY_VT_SYS_H
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <ghostty/vt/types.h>
#include <ghostty/vt/allocator.h>
/** @defgroup sys System Interface
*
* Runtime-swappable function pointers for operations that depend on
* external implementations (e.g. image decoding).
*
* These are process-global settings that must be configured at startup
* before any terminal functionality that depends on them is used.
* Setting these enables various optional features of the terminal. For
* example, setting a PNG decoder enables PNG image support in the Kitty
* Graphics Protocol.
*
* Use ghostty_sys_set() with a `GhosttySysOption` to install or clear
* an implementation. Passing NULL as the value clears the implementation
* and disables the corresponding feature.
*
* ## Example
*
* ### Defining a PNG decode callback
* @snippet c-vt-kitty-graphics/src/main.c kitty-graphics-decode-png
*
* ### Installing the callback and sending a PNG image
* @snippet c-vt-kitty-graphics/src/main.c kitty-graphics-main
*
* @{
*/
#ifdef __cplusplus
extern "C" {
#endif
/**
* Result of decoding an image.
*
* The `data` buffer must be allocated through the allocator provided to
* the decode callback. The library takes ownership and will free it
* with the same allocator.
*/
typedef struct {
/** Image width in pixels. */
uint32_t width;
/** Image height in pixels. */
uint32_t height;
/** Pointer to the decoded RGBA pixel data. */
uint8_t* data;
/** Length of the pixel data in bytes. */
size_t data_len;
} GhosttySysImage;
/**
* Log severity levels for the log callback.
*/
typedef enum GHOSTTY_ENUM_TYPED {
GHOSTTY_SYS_LOG_LEVEL_ERROR = 0,
GHOSTTY_SYS_LOG_LEVEL_WARNING = 1,
GHOSTTY_SYS_LOG_LEVEL_INFO = 2,
GHOSTTY_SYS_LOG_LEVEL_DEBUG = 3,
GHOSTTY_SYS_LOG_LEVEL_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
} GhosttySysLogLevel;
/**
* Callback type for logging.
*
* When installed, internal library log messages are delivered through
* this callback instead of being discarded. The embedder is responsible
* for formatting and routing log output.
*
* @p scope is the log scope name as UTF-8 bytes (e.g. "osc", "kitty").
* When the log is unscoped (default scope), @p scope_len is 0.
*
* All pointer arguments are only valid for the duration of the callback.
* The callback must be safe to call from any thread.
*
* @param userdata The userdata pointer set via GHOSTTY_SYS_OPT_USERDATA
* @param level The severity level of the log message
* @param scope Pointer to the scope name bytes
* @param scope_len Length of the scope name in bytes
* @param message Pointer to the log message bytes
* @param message_len Length of the log message in bytes
*/
typedef void (*GhosttySysLogFn)(
void* userdata,
GhosttySysLogLevel level,
const uint8_t* scope,
size_t scope_len,
const uint8_t* message,
size_t message_len);
/**
* Callback type for PNG decoding.
*
* Decodes raw PNG data into RGBA pixels. The output pixel data must be
* allocated through the provided allocator. The library takes ownership
* of the buffer and will free it with the same allocator.
*
* @param userdata The userdata pointer set via GHOSTTY_SYS_OPT_USERDATA
* @param allocator The allocator to use for the output pixel buffer
* @param data Pointer to the raw PNG data
* @param data_len Length of the raw PNG data in bytes
* @param[out] out On success, filled with the decoded image
* @return true on success, false on failure
*/
typedef bool (*GhosttySysDecodePngFn)(
void* userdata,
const GhosttyAllocator* allocator,
const uint8_t* data,
size_t data_len,
GhosttySysImage* out);
/**
* System option identifiers for ghostty_sys_set().
*/
typedef enum GHOSTTY_ENUM_TYPED {
/**
* Set the userdata pointer passed to all sys callbacks.
*
* Input type: void* (or NULL)
*/
GHOSTTY_SYS_OPT_USERDATA = 0,
/**
* Set the PNG decode function.
*
* When set, the terminal can accept PNG images via the Kitty
* Graphics Protocol. When cleared (NULL value), PNG decoding is
* unsupported and PNG image data will be rejected.
*
* Input type: GhosttySysDecodePngFn (function pointer, or NULL)
*/
GHOSTTY_SYS_OPT_DECODE_PNG = 1,
/**
* Set the log callback.
*
* When set, internal library log messages are delivered to this
* callback. When cleared (NULL value), log messages are silently
* discarded.
*
* Use ghostty_sys_log_stderr as a convenience callback that
* writes formatted messages to stderr.
*
* Which log levels are emitted depends on the build mode of the
* library and is not configurable at runtime. Debug builds emit
* all levels (debug and above). Release builds emit info and
* above; debug-level messages are compiled out entirely and will
* never reach the callback.
*
* Input type: GhosttySysLogFn (function pointer, or NULL)
*/
GHOSTTY_SYS_OPT_LOG = 2,
GHOSTTY_SYS_OPT_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
} GhosttySysOption;
/**
* Set a system-level option.
*
* Configures a process-global implementation function. These should be
* set once at startup before using any terminal functionality that
* depends on them.
*
* @param option The option to set
* @param value Pointer to the value (type depends on the option),
* or NULL to clear it
* @return GHOSTTY_SUCCESS on success, GHOSTTY_INVALID_VALUE if the
* option is not recognized
*/
GHOSTTY_API GhosttyResult ghostty_sys_set(GhosttySysOption option,
const void* value);
/**
* Built-in log callback that writes to stderr.
*
* Formats each message as "[level](scope): message\n".
* Can be passed directly to ghostty_sys_set():
*
* @code
* ghostty_sys_set(GHOSTTY_SYS_OPT_LOG, &ghostty_sys_log_stderr);
* @endcode
*/
GHOSTTY_API void ghostty_sys_log_stderr(void* userdata,
GhosttySysLogLevel level,
const uint8_t* scope,
size_t scope_len,
const uint8_t* message,
size_t message_len);
#ifdef __cplusplus
}
#endif
/** @} */
#endif /* GHOSTTY_VT_SYS_H */
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,335 @@
/**
* @file types.h
*
* Common types, macros, and utilities for libghostty-vt.
*/
#ifndef GHOSTTY_VT_TYPES_H
#define GHOSTTY_VT_TYPES_H
#include <limits.h>
#include <stddef.h>
#include <stdint.h>
// Symbol visibility for shared library builds. On Windows, functions
// are exported from the DLL when building and imported when consuming.
// On other platforms with GCC/Clang, functions are marked with default
// visibility so they remain accessible when the library is built with
// -fvisibility=hidden. For static library builds, define GHOSTTY_STATIC
// before including this header to make this a no-op.
#ifndef GHOSTTY_API
#if defined(GHOSTTY_STATIC)
#define GHOSTTY_API
#elif defined(_WIN32) || defined(_WIN64)
#ifdef GHOSTTY_BUILD_SHARED
#define GHOSTTY_API __declspec(dllexport)
#else
#define GHOSTTY_API __declspec(dllimport)
#endif
#elif defined(__GNUC__) && __GNUC__ >= 4
#define GHOSTTY_API __attribute__((visibility("default")))
#else
#define GHOSTTY_API
#endif
#endif
/**
* Enum int-sizing helpers.
*
* The Zig side backs all C enums with c_int, so the C declarations
* must use int as their underlying type to maintain ABI compatibility.
*
* C23 (detected via __STDC_VERSION__ >= 202311L) supports explicit
* enum underlying types with `enum : int { ... }`. For pre-C23
* compilers, which are free to choose any type that can represent
* all values (C11 §6.7.2.2), we add an INT_MAX sentinel as the last
* entry to force the compiler to use int.
*
* INT_MAX is used rather than a fixed constant like 0xFFFFFFFF
* because enum constants must have type int (which is signed).
* Values above INT_MAX overflow signed int and are a constraint
* violation in standard C; compilers that accept them interpret them
* as negative values via two's complement, which can collide with
* legitimate negative enum values.
*
* Usage:
* @code
* typedef enum GHOSTTY_ENUM_TYPED {
* FOO_A = 0,
* FOO_B = 1,
* FOO_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
* } Foo;
* @endcode
*/
#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 202311L
#define GHOSTTY_ENUM_TYPED : int
#else
#define GHOSTTY_ENUM_TYPED
#endif
#define GHOSTTY_ENUM_MAX_VALUE INT_MAX
/**
* Result codes for libghostty-vt operations.
*/
typedef enum GHOSTTY_ENUM_TYPED {
/** 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,
/** Operation failed because the provided buffer was too small */
GHOSTTY_OUT_OF_SPACE = -3,
/** The requested value has no value */
GHOSTTY_NO_VALUE = -4,
GHOSTTY_RESULT_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
} GhosttyResult;
/* ---- Opaque handles ---- */
/**
* Opaque handle to a terminal instance.
*
* @ingroup terminal
*/
typedef struct GhosttyTerminalImpl* GhosttyTerminal;
/**
* Opaque handle to a tracked grid reference.
*
* A tracked grid reference is owned by the caller and must be freed with
* ghostty_tracked_grid_ref_free(). If the terminal that created it is freed
* first, the handle remains valid only for tracked-grid-ref APIs: it reports no
* value and can still be freed.
*
* @ingroup grid_ref
*/
typedef struct GhosttyTrackedGridRefImpl* GhosttyTrackedGridRef;
/**
* Opaque handle to a Kitty graphics image storage.
*
* Obtained via ghostty_terminal_get() with
* GHOSTTY_TERMINAL_DATA_KITTY_GRAPHICS. The pointer is borrowed from
* the terminal and remains valid until the next mutating terminal call
* (e.g. ghostty_terminal_vt_write() or ghostty_terminal_reset()).
*
* @ingroup kitty_graphics
*/
typedef struct GhosttyKittyGraphicsImpl* GhosttyKittyGraphics;
/**
* Opaque handle to a Kitty graphics image.
*
* Obtained via ghostty_kitty_graphics_image() with an image ID. The
* pointer is borrowed from the storage and remains valid until the next
* mutating terminal call.
*
* @ingroup kitty_graphics
*/
typedef const struct GhosttyKittyGraphicsImageImpl* GhosttyKittyGraphicsImage;
/**
* Opaque handle to a Kitty graphics placement iterator.
*
* @ingroup kitty_graphics
*/
typedef struct GhosttyKittyGraphicsPlacementIteratorImpl* GhosttyKittyGraphicsPlacementIterator;
/**
* Opaque handle to a render state instance.
*
* @ingroup render
*/
typedef struct GhosttyRenderStateImpl* GhosttyRenderState;
/**
* Opaque handle to a render-state row iterator.
*
* @ingroup render
*/
typedef struct GhosttyRenderStateRowIteratorImpl* GhosttyRenderStateRowIterator;
/**
* Opaque handle to render-state row cells.
*
* @ingroup render
*/
typedef struct GhosttyRenderStateRowCellsImpl* GhosttyRenderStateRowCells;
/**
* 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 GhosttySgrParserImpl* GhosttySgrParser;
/**
* Opaque handle to a formatter instance.
*
* @ingroup formatter
*/
typedef struct GhosttyFormatterImpl* GhosttyFormatter;
/**
* 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 GhosttyOscParserImpl* 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 GhosttyOscCommandImpl* GhosttyOscCommand;
/* ---- Common value types ---- */
/**
* Terminal content output format.
*
* @ingroup formatter
*/
typedef enum GHOSTTY_ENUM_TYPED {
/** Plain text (no escape sequences). */
GHOSTTY_FORMATTER_FORMAT_PLAIN,
/** VT sequences preserving colors, styles, URLs, etc. */
GHOSTTY_FORMATTER_FORMAT_VT,
/** HTML with inline styles. */
GHOSTTY_FORMATTER_FORMAT_HTML,
GHOSTTY_FORMATTER_FORMAT_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE,
} GhosttyFormatterFormat;
/**
* A borrowed byte string (pointer + length).
*
* The memory is not owned by this struct. The pointer is only valid
* for the lifetime documented by the API that produces or consumes it.
*/
typedef struct {
/** Pointer to the string bytes. */
const uint8_t* ptr;
/** Length of the string in bytes. */
size_t len;
} GhosttyString;
/**
* A caller-provided byte buffer.
*
* APIs that write to this type use `len` for the number of bytes written on
* GHOSTTY_SUCCESS and the required byte capacity on GHOSTTY_OUT_OF_SPACE.
*/
typedef struct {
/** Destination buffer for bytes. May be NULL when cap is 0 to query required size. */
uint8_t* ptr;
/** Capacity of ptr in bytes. */
size_t cap;
/** Bytes written on success, or required byte capacity on GHOSTTY_OUT_OF_SPACE. */
size_t len;
} GhosttyBuffer;
/**
* A surface-space position in pixels.
*
* This is not a terminal grid coordinate. It represents an x/y position in the
* rendered surface coordinate space, with (0, 0) at the top-left of the
* surface.
*/
typedef struct {
/** X position in surface pixels. */
double x;
/** Y position in surface pixels. */
double y;
} GhosttySurfacePosition;
/**
* A borrowed list of Unicode scalar values.
*
* Values are encoded as uint32_t scalar values. The memory is not owned by this
* struct. The pointer is only valid for the lifetime documented by the API that
* consumes or produces it.
*
* APIs may document special handling for NULL + len 0, such as “use defaults”.
*/
typedef struct {
/** Pointer to Unicode scalar values. */
const uint32_t* ptr;
/** Number of entries in ptr. */
size_t len;
} GhosttyCodepoints;
/**
* Initialize a sized struct to zero and set its size field.
*
* Sized structs use a `size` field as the first member for ABI
* compatibility. This macro zero-initializes the struct and sets the
* size field to `sizeof(type)`, which allows the library to detect
* which version of the struct the caller was compiled against.
*
* @param type The struct type to initialize
* @return A zero-initialized struct with the size field set
*
* Example:
* @code
* GhosttyFormatterTerminalOptions opts = GHOSTTY_INIT_SIZED(GhosttyFormatterTerminalOptions);
* opts.emit = GHOSTTY_FORMATTER_FORMAT_PLAIN;
* opts.trim = true;
* @endcode
*/
#define GHOSTTY_INIT_SIZED(type) \
((type){ .size = sizeof(type) })
/**
* Return a pointer to a null-terminated JSON string describing the
* layout of every C API struct for the current target.
*
* This is primarily useful for language bindings that can't easily
* set C struct fields and need to do so via byte offsets. For example,
* WebAssembly modules can't share struct definitions with the host.
*
* Example (abbreviated):
* @code{.json}
* {
* "GhosttyMouseEncoderSize": {
* "size": 40,
* "align": 8,
* "fields": {
* "size": { "offset": 0, "size": 8, "type": "u64" },
* "screen_width": { "offset": 8, "size": 4, "type": "u32" },
* "screen_height": { "offset": 12, "size": 4, "type": "u32" },
* "cell_width": { "offset": 16, "size": 4, "type": "u32" },
* "cell_height": { "offset": 20, "size": 4, "type": "u32" },
* "padding_top": { "offset": 24, "size": 4, "type": "u32" },
* "padding_bottom": { "offset": 28, "size": 4, "type": "u32" },
* "padding_right": { "offset": 32, "size": 4, "type": "u32" },
* "padding_left": { "offset": 36, "size": 4, "type": "u32" }
* }
* }
* }
* @endcode
*
* The returned pointer is valid for the lifetime of the process.
*
* @return Pointer to the null-terminated JSON string.
*/
GHOSTTY_API const char *ghostty_type_json(void);
#endif /* GHOSTTY_VT_TYPES_H */
@@ -0,0 +1,160 @@
/**
* @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>
#include <ghostty/vt/types.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
*/
GHOSTTY_API 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
*/
GHOSTTY_API 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
*/
GHOSTTY_API 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
*/
GHOSTTY_API 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
*/
GHOSTTY_API 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
*/
GHOSTTY_API 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
*/
GHOSTTY_API 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
*/
GHOSTTY_API 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
*/
GHOSTTY_API 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
*/
GHOSTTY_API void ghostty_wasm_free_usize(size_t *ptr);
/** @} */
#endif /* __wasm__ */
#endif /* GHOSTTY_VT_WASM_H */
@@ -0,0 +1 @@
.cxx/
@@ -6,11 +6,25 @@ version = '0.0.0'
android {
namespace 'expo.modules.t3terminal'
ndkVersion rootProject.ext.ndkVersion
compileSdk rootProject.ext.compileSdkVersion
defaultConfig {
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
externalNativeBuild {
cmake {
cppFlags '-std=c++17 -Wall -Wextra -Werror'
}
}
}
externalNativeBuild {
cmake {
path 'src/main/cpp/CMakeLists.txt'
version '3.22.1'
}
}
}
@@ -0,0 +1,23 @@
cmake_minimum_required(VERSION 3.22.1)
project(t3terminal LANGUAGES CXX)
add_library(ghostty-vt SHARED IMPORTED)
set_target_properties(
ghostty-vt
PROPERTIES IMPORTED_LOCATION
"${CMAKE_CURRENT_SOURCE_DIR}/../jniLibs/${ANDROID_ABI}/libghostty-vt.so"
)
add_library(t3terminal SHARED t3_terminal_jni.cpp)
target_include_directories(
t3terminal
PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/../../../../Vendor/libghostty-vt/include"
)
target_link_options(
t3terminal PRIVATE "-Wl,-z,common-page-size=16384" "-Wl,-z,max-page-size=16384"
)
target_link_libraries(t3terminal PRIVATE ghostty-vt log)
@@ -0,0 +1,516 @@
#include <jni.h>
#include <algorithm>
#include <cstdint>
#include <mutex>
#include <utility>
#include <vector>
#include <ghostty/vt.h>
namespace {
constexpr uint32_t kSnapshotMagic = 0x54563354; // "T3VT" in little endian.
constexpr uint16_t kSnapshotVersion = 1;
constexpr size_t kMaxScrollbackRows = 10000;
enum CellFlag : uint16_t {
kBold = 1 << 0,
kItalic = 1 << 1,
kFaint = 1 << 2,
kInverse = 1 << 3,
kInvisible = 1 << 4,
kStrikethrough = 1 << 5,
kOverline = 1 << 6,
kUnderline = 1 << 7,
kSelected = 1 << 8,
};
struct Session {
GhosttyTerminal terminal = nullptr;
GhosttyRenderState render_state = nullptr;
GhosttyRenderStateRowIterator row_iterator = nullptr;
GhosttyRenderStateRowCells row_cells = nullptr;
std::vector<uint8_t> responses;
std::mutex mutex;
};
class ByteWriter {
public:
explicit ByteWriter(size_t capacity) { bytes_.reserve(capacity); }
void U8(uint8_t value) { bytes_.push_back(value); }
void U16(uint16_t value) {
U8(static_cast<uint8_t>(value));
U8(static_cast<uint8_t>(value >> 8));
}
void U32(uint32_t value) {
U16(static_cast<uint16_t>(value));
U16(static_cast<uint16_t>(value >> 16));
}
void Bytes(const std::vector<uint8_t>& value) {
bytes_.insert(bytes_.end(), value.begin(), value.end());
}
std::vector<uint8_t> Take() { return std::move(bytes_); }
private:
std::vector<uint8_t> bytes_;
};
Session* FromHandle(jlong handle) {
return reinterpret_cast<Session*>(static_cast<intptr_t>(handle));
}
jbyteArray ToJavaBytes(JNIEnv* env, const std::vector<uint8_t>& bytes) {
auto result = env->NewByteArray(static_cast<jsize>(bytes.size()));
if (result != nullptr && !bytes.empty()) {
env->SetByteArrayRegion(result, 0, static_cast<jsize>(bytes.size()),
reinterpret_cast<const jbyte*>(bytes.data()));
}
return result;
}
GhosttyColorRgb RgbFromArgb(jint color) {
const auto value = static_cast<uint32_t>(color);
return {
.r = static_cast<uint8_t>(value >> 16),
.g = static_cast<uint8_t>(value >> 8),
.b = static_cast<uint8_t>(value),
};
}
uint32_t ArgbFromRgb(GhosttyColorRgb color) {
return 0xFF000000U | (static_cast<uint32_t>(color.r) << 16U) |
(static_cast<uint32_t>(color.g) << 8U) | color.b;
}
GhosttyColorRgb Blend(GhosttyColorRgb foreground, GhosttyColorRgb background,
uint8_t foreground_weight) {
const auto blend = [foreground_weight](uint8_t front, uint8_t back) {
const uint16_t back_weight = 255 - foreground_weight;
return static_cast<uint8_t>((front * foreground_weight + back * back_weight) / 255);
};
return {
.r = blend(foreground.r, background.r),
.g = blend(foreground.g, background.g),
.b = blend(foreground.b, background.b),
};
}
void AppendUtf8(std::vector<uint8_t>* output, uint32_t codepoint) {
if (codepoint <= 0x7F) {
output->push_back(static_cast<uint8_t>(codepoint));
} else if (codepoint <= 0x7FF) {
output->push_back(static_cast<uint8_t>(0xC0 | (codepoint >> 6)));
output->push_back(static_cast<uint8_t>(0x80 | (codepoint & 0x3F)));
} else if (codepoint <= 0xFFFF && !(codepoint >= 0xD800 && codepoint <= 0xDFFF)) {
output->push_back(static_cast<uint8_t>(0xE0 | (codepoint >> 12)));
output->push_back(static_cast<uint8_t>(0x80 | ((codepoint >> 6) & 0x3F)));
output->push_back(static_cast<uint8_t>(0x80 | (codepoint & 0x3F)));
} else if (codepoint <= 0x10FFFF) {
output->push_back(static_cast<uint8_t>(0xF0 | (codepoint >> 18)));
output->push_back(static_cast<uint8_t>(0x80 | ((codepoint >> 12) & 0x3F)));
output->push_back(static_cast<uint8_t>(0x80 | ((codepoint >> 6) & 0x3F)));
output->push_back(static_cast<uint8_t>(0x80 | (codepoint & 0x3F)));
}
}
void OnWritePty(GhosttyTerminal, void* userdata, const uint8_t* data, size_t len) {
auto* session = static_cast<Session*>(userdata);
if (session == nullptr || data == nullptr || len == 0) return;
session->responses.insert(session->responses.end(), data, data + len);
}
void ApplyTheme(Session* session, jint foreground, jint background, jint cursor,
JNIEnv* env, jintArray palette_array) {
auto foreground_rgb = RgbFromArgb(foreground);
auto background_rgb = RgbFromArgb(background);
auto cursor_rgb = RgbFromArgb(cursor);
ghostty_terminal_set(session->terminal, GHOSTTY_TERMINAL_OPT_COLOR_FOREGROUND,
&foreground_rgb);
ghostty_terminal_set(session->terminal, GHOSTTY_TERMINAL_OPT_COLOR_BACKGROUND,
&background_rgb);
ghostty_terminal_set(session->terminal, GHOSTTY_TERMINAL_OPT_COLOR_CURSOR, &cursor_rgb);
if (palette_array == nullptr) return;
const auto palette_length = env->GetArrayLength(palette_array);
if (palette_length <= 0) return;
GhosttyColorRgb palette[256];
if (ghostty_terminal_get(session->terminal,
GHOSTTY_TERMINAL_DATA_COLOR_PALETTE_DEFAULT,
palette) != GHOSTTY_SUCCESS) {
return;
}
const auto copied_length = std::min<jsize>(palette_length, 256);
std::vector<jint> colors(static_cast<size_t>(copied_length));
env->GetIntArrayRegion(palette_array, 0, copied_length, colors.data());
for (jsize index = 0; index < copied_length; ++index) {
palette[index] = RgbFromArgb(colors[index]);
}
ghostty_terminal_set(session->terminal, GHOSTTY_TERMINAL_OPT_COLOR_PALETTE, palette);
}
void FreeSession(Session* session) {
if (session == nullptr) return;
ghostty_render_state_row_cells_free(session->row_cells);
ghostty_render_state_row_iterator_free(session->row_iterator);
ghostty_render_state_free(session->render_state);
ghostty_terminal_free(session->terminal);
delete session;
}
std::vector<uint8_t> DrainResponses(Session* session) {
std::vector<uint8_t> responses;
responses.swap(session->responses);
return responses;
}
bool ViewportGridRef(Session* session, jint x, jint y, GhosttyGridRef* out) {
*out = GhosttyGridRef{};
out->size = sizeof(*out);
GhosttyPoint point{};
point.tag = GHOSTTY_POINT_TAG_VIEWPORT;
point.value.coordinate.x = static_cast<uint16_t>(std::max<jint>(x, 0));
point.value.coordinate.y = static_cast<uint32_t>(std::max<jint>(y, 0));
return ghostty_terminal_grid_ref(session->terminal, point, out) == GHOSTTY_SUCCESS;
}
uint16_t StyleFlags(const GhosttyStyle& style, bool selected) {
uint16_t flags = 0;
if (style.bold) flags |= kBold;
if (style.italic) flags |= kItalic;
if (style.faint) flags |= kFaint;
if (style.inverse) flags |= kInverse;
if (style.invisible) flags |= kInvisible;
if (style.strikethrough) flags |= kStrikethrough;
if (style.overline) flags |= kOverline;
if (style.underline != 0) flags |= kUnderline;
if (selected) flags |= kSelected;
return flags;
}
} // namespace
extern "C" JNIEXPORT jlong JNICALL
Java_expo_modules_t3terminal_GhosttyBridge_nativeCreate(
JNIEnv* env, jclass, jint cols, jint rows, jint cell_width, jint cell_height,
jint foreground, jint background, jint cursor, jintArray palette) {
auto* session = new Session();
GhosttyTerminalOptions options = {
.cols = static_cast<uint16_t>(std::clamp(cols, 1, 65535)),
.rows = static_cast<uint16_t>(std::clamp(rows, 1, 65535)),
.max_scrollback = kMaxScrollbackRows,
};
if (ghostty_terminal_new(nullptr, &session->terminal, options) != GHOSTTY_SUCCESS ||
ghostty_render_state_new(nullptr, &session->render_state) != GHOSTTY_SUCCESS ||
ghostty_render_state_row_iterator_new(nullptr, &session->row_iterator) != GHOSTTY_SUCCESS ||
ghostty_render_state_row_cells_new(nullptr, &session->row_cells) != GHOSTTY_SUCCESS) {
FreeSession(session);
return 0;
}
ghostty_terminal_set(session->terminal, GHOSTTY_TERMINAL_OPT_USERDATA, session);
ghostty_terminal_set(session->terminal, GHOSTTY_TERMINAL_OPT_WRITE_PTY,
reinterpret_cast<const void*>(OnWritePty));
ApplyTheme(session, foreground, background, cursor, env, palette);
ghostty_terminal_resize(session->terminal, options.cols, options.rows,
static_cast<uint32_t>(std::max(cell_width, 1)),
static_cast<uint32_t>(std::max(cell_height, 1)));
return static_cast<jlong>(reinterpret_cast<intptr_t>(session));
}
extern "C" JNIEXPORT void JNICALL
Java_expo_modules_t3terminal_GhosttyBridge_nativeDestroy(JNIEnv*, jclass, jlong handle) {
FreeSession(FromHandle(handle));
}
extern "C" JNIEXPORT jbyteArray JNICALL
Java_expo_modules_t3terminal_GhosttyBridge_nativeFeed(JNIEnv* env, jclass, jlong handle,
jbyteArray data) {
auto* session = FromHandle(handle);
if (session == nullptr || data == nullptr) return env->NewByteArray(0);
std::lock_guard<std::mutex> lock(session->mutex);
const auto length = env->GetArrayLength(data);
std::vector<uint8_t> bytes(static_cast<size_t>(length));
if (length > 0) {
env->GetByteArrayRegion(data, 0, length, reinterpret_cast<jbyte*>(bytes.data()));
ghostty_terminal_vt_write(session->terminal, bytes.data(), bytes.size());
}
return ToJavaBytes(env, DrainResponses(session));
}
extern "C" JNIEXPORT jbyteArray JNICALL
Java_expo_modules_t3terminal_GhosttyBridge_nativeResize(
JNIEnv* env, jclass, jlong handle, jint cols, jint rows, jint cell_width, jint cell_height) {
auto* session = FromHandle(handle);
if (session == nullptr) return env->NewByteArray(0);
std::lock_guard<std::mutex> lock(session->mutex);
ghostty_terminal_resize(session->terminal,
static_cast<uint16_t>(std::clamp(cols, 1, 65535)),
static_cast<uint16_t>(std::clamp(rows, 1, 65535)),
static_cast<uint32_t>(std::max(cell_width, 1)),
static_cast<uint32_t>(std::max(cell_height, 1)));
return ToJavaBytes(env, DrainResponses(session));
}
extern "C" JNIEXPORT void JNICALL
Java_expo_modules_t3terminal_GhosttyBridge_nativeScroll(JNIEnv*, jclass, jlong handle,
jint rows) {
auto* session = FromHandle(handle);
if (session == nullptr || rows == 0) return;
std::lock_guard<std::mutex> lock(session->mutex);
GhosttyTerminalScrollViewport scroll = {
.tag = GHOSTTY_SCROLL_VIEWPORT_DELTA,
.value = {.delta = rows},
};
ghostty_terminal_scroll_viewport(session->terminal, scroll);
}
extern "C" JNIEXPORT void JNICALL
Java_expo_modules_t3terminal_GhosttyBridge_nativeSetTheme(
JNIEnv* env, jclass, jlong handle, jint foreground, jint background, jint cursor,
jintArray palette) {
auto* session = FromHandle(handle);
if (session == nullptr) return;
std::lock_guard<std::mutex> lock(session->mutex);
ApplyTheme(session, foreground, background, cursor, env, palette);
}
extern "C" JNIEXPORT jboolean JNICALL
Java_expo_modules_t3terminal_GhosttyBridge_nativeSelectWordAt(JNIEnv*, jclass,
jlong handle, jint x,
jint y) {
auto* session = FromHandle(handle);
if (session == nullptr) return JNI_FALSE;
std::lock_guard<std::mutex> lock(session->mutex);
GhosttyTerminalSelectWordOptions options{};
options.size = sizeof(options);
if (!ViewportGridRef(session, x, y, &options.ref)) return JNI_FALSE;
GhosttySelection selection{};
selection.size = sizeof(selection);
if (ghostty_terminal_select_word(session->terminal, &options, &selection) !=
GHOSTTY_SUCCESS) {
return JNI_FALSE;
}
return ghostty_terminal_set(session->terminal, GHOSTTY_TERMINAL_OPT_SELECTION,
&selection) == GHOSTTY_SUCCESS
? JNI_TRUE
: JNI_FALSE;
}
extern "C" JNIEXPORT void JNICALL
Java_expo_modules_t3terminal_GhosttyBridge_nativeExtendSelection(
JNIEnv*, jclass, jlong handle, jint anchor_x, jint anchor_y, jint x, jint y) {
auto* session = FromHandle(handle);
if (session == nullptr) return;
std::lock_guard<std::mutex> lock(session->mutex);
GhosttySelection selection{};
selection.size = sizeof(selection);
if (!ViewportGridRef(session, anchor_x, anchor_y, &selection.start)) return;
if (!ViewportGridRef(session, x, y, &selection.end)) return;
ghostty_terminal_set(session->terminal, GHOSTTY_TERMINAL_OPT_SELECTION, &selection);
}
extern "C" JNIEXPORT jboolean JNICALL
Java_expo_modules_t3terminal_GhosttyBridge_nativeSelectAll(JNIEnv*, jclass,
jlong handle) {
auto* session = FromHandle(handle);
if (session == nullptr) return JNI_FALSE;
std::lock_guard<std::mutex> lock(session->mutex);
GhosttySelection selection{};
selection.size = sizeof(selection);
if (ghostty_terminal_select_all(session->terminal, &selection) != GHOSTTY_SUCCESS) {
return JNI_FALSE;
}
return ghostty_terminal_set(session->terminal, GHOSTTY_TERMINAL_OPT_SELECTION,
&selection) == GHOSTTY_SUCCESS
? JNI_TRUE
: JNI_FALSE;
}
extern "C" JNIEXPORT void JNICALL
Java_expo_modules_t3terminal_GhosttyBridge_nativeClearSelection(JNIEnv*, jclass,
jlong handle) {
auto* session = FromHandle(handle);
if (session == nullptr) return;
std::lock_guard<std::mutex> lock(session->mutex);
ghostty_terminal_set(session->terminal, GHOSTTY_TERMINAL_OPT_SELECTION, nullptr);
}
// Returns the active selection as UTF-8 bytes (soft-wrapped lines unwrapped,
// trailing whitespace trimmed), or null when there is no selection.
extern "C" JNIEXPORT jbyteArray JNICALL
Java_expo_modules_t3terminal_GhosttyBridge_nativeGetSelectionText(JNIEnv* env, jclass,
jlong handle) {
auto* session = FromHandle(handle);
if (session == nullptr) return nullptr;
std::lock_guard<std::mutex> lock(session->mutex);
GhosttyTerminalSelectionFormatOptions options{};
options.size = sizeof(options);
options.emit = GHOSTTY_FORMATTER_FORMAT_PLAIN;
options.unwrap = true;
options.trim = true;
uint8_t* bytes = nullptr;
size_t len = 0;
if (ghostty_terminal_selection_format_alloc(session->terminal, nullptr, options,
&bytes, &len) != GHOSTTY_SUCCESS ||
bytes == nullptr) {
return nullptr;
}
auto result = env->NewByteArray(static_cast<jsize>(len));
if (result != nullptr && len > 0) {
env->SetByteArrayRegion(result, 0, static_cast<jsize>(len),
reinterpret_cast<const jbyte*>(bytes));
}
ghostty_free(nullptr, bytes, len);
return result;
}
extern "C" JNIEXPORT jbyteArray JNICALL
Java_expo_modules_t3terminal_GhosttyBridge_nativeSnapshot(JNIEnv* env, jclass,
jlong handle) {
auto* session = FromHandle(handle);
if (session == nullptr) return env->NewByteArray(0);
std::lock_guard<std::mutex> lock(session->mutex);
if (ghostty_render_state_update(session->render_state, session->terminal) != GHOSTTY_SUCCESS) {
return env->NewByteArray(0);
}
uint16_t cols = 0;
uint16_t rows = 0;
bool cursor_visible = false;
bool cursor_in_viewport = false;
bool cursor_blinking = false;
uint16_t cursor_x = 0xFFFF;
uint16_t cursor_y = 0xFFFF;
GhosttyRenderStateCursorVisualStyle cursor_style =
GHOSTTY_RENDER_STATE_CURSOR_VISUAL_STYLE_BLOCK;
ghostty_render_state_get(session->render_state, GHOSTTY_RENDER_STATE_DATA_COLS, &cols);
ghostty_render_state_get(session->render_state, GHOSTTY_RENDER_STATE_DATA_ROWS, &rows);
ghostty_render_state_get(session->render_state, GHOSTTY_RENDER_STATE_DATA_CURSOR_VISIBLE,
&cursor_visible);
ghostty_render_state_get(session->render_state,
GHOSTTY_RENDER_STATE_DATA_CURSOR_VIEWPORT_HAS_VALUE,
&cursor_in_viewport);
ghostty_render_state_get(session->render_state, GHOSTTY_RENDER_STATE_DATA_CURSOR_BLINKING,
&cursor_blinking);
ghostty_render_state_get(session->render_state,
GHOSTTY_RENDER_STATE_DATA_CURSOR_VISUAL_STYLE, &cursor_style);
if (cursor_in_viewport) {
ghostty_render_state_get(session->render_state,
GHOSTTY_RENDER_STATE_DATA_CURSOR_VIEWPORT_X, &cursor_x);
ghostty_render_state_get(session->render_state,
GHOSTTY_RENDER_STATE_DATA_CURSOR_VIEWPORT_Y, &cursor_y);
}
GhosttyRenderStateColors colors{};
colors.size = sizeof(colors);
if (ghostty_render_state_colors_get(session->render_state, &colors) != GHOSTTY_SUCCESS) {
return env->NewByteArray(0);
}
const auto cursor_color = colors.cursor_has_value ? colors.cursor : colors.foreground;
ByteWriter writer(32 + static_cast<size_t>(cols) * rows * 14);
writer.U32(kSnapshotMagic);
writer.U16(kSnapshotVersion);
writer.U16(cols);
writer.U16(rows);
writer.U16(cursor_x);
writer.U16(cursor_y);
writer.U8(cursor_visible && cursor_in_viewport ? 1 : 0);
writer.U8(static_cast<uint8_t>(cursor_style));
writer.U8(cursor_blinking ? 1 : 0);
writer.U8(0);
writer.U32(ArgbFromRgb(colors.foreground));
writer.U32(ArgbFromRgb(colors.background));
writer.U32(ArgbFromRgb(cursor_color));
if (ghostty_render_state_get(session->render_state,
GHOSTTY_RENDER_STATE_DATA_ROW_ITERATOR,
&session->row_iterator) != GHOSTTY_SUCCESS) {
return env->NewByteArray(0);
}
uint16_t written_rows = 0;
while (written_rows < rows &&
ghostty_render_state_row_iterator_next(session->row_iterator)) {
if (ghostty_render_state_row_get(session->row_iterator,
GHOSTTY_RENDER_STATE_ROW_DATA_CELLS,
&session->row_cells) != GHOSTTY_SUCCESS) {
break;
}
uint16_t written_cols = 0;
while (written_cols < cols && ghostty_render_state_row_cells_next(session->row_cells)) {
GhosttyStyle style{};
style.size = sizeof(style);
bool selected = false;
GhosttyColorRgb foreground = colors.foreground;
GhosttyColorRgb background = colors.background;
ghostty_render_state_row_cells_get(session->row_cells,
GHOSTTY_RENDER_STATE_ROW_CELLS_DATA_STYLE,
&style);
ghostty_render_state_row_cells_get(session->row_cells,
GHOSTTY_RENDER_STATE_ROW_CELLS_DATA_SELECTED,
&selected);
ghostty_render_state_row_cells_get(session->row_cells,
GHOSTTY_RENDER_STATE_ROW_CELLS_DATA_FG_COLOR,
&foreground);
ghostty_render_state_row_cells_get(session->row_cells,
GHOSTTY_RENDER_STATE_ROW_CELLS_DATA_BG_COLOR,
&background);
if (style.inverse) std::swap(foreground, background);
if (style.faint) foreground = Blend(foreground, background, 155);
uint32_t grapheme_count = 0;
ghostty_render_state_row_cells_get(
session->row_cells, GHOSTTY_RENDER_STATE_ROW_CELLS_DATA_GRAPHEMES_LEN,
&grapheme_count);
std::vector<uint8_t> utf8;
if (grapheme_count > 0) {
std::vector<uint32_t> codepoints(grapheme_count);
if (ghostty_render_state_row_cells_get(
session->row_cells, GHOSTTY_RENDER_STATE_ROW_CELLS_DATA_GRAPHEMES_BUF,
codepoints.data()) == GHOSTTY_SUCCESS) {
utf8.reserve(grapheme_count * 4);
for (const auto codepoint : codepoints) AppendUtf8(&utf8, codepoint);
}
}
const auto text_length = static_cast<uint16_t>(std::min<size_t>(utf8.size(), 65535));
writer.U32(ArgbFromRgb(foreground));
writer.U32(ArgbFromRgb(background));
writer.U16(StyleFlags(style, selected));
writer.U16(text_length);
if (text_length != utf8.size()) utf8.resize(text_length);
writer.Bytes(utf8);
++written_cols;
}
while (written_cols++ < cols) {
writer.U32(ArgbFromRgb(colors.foreground));
writer.U32(ArgbFromRgb(colors.background));
writer.U16(0);
writer.U16(0);
}
++written_rows;
}
while (written_rows++ < rows) {
for (uint16_t column = 0; column < cols; ++column) {
writer.U32(ArgbFromRgb(colors.foreground));
writer.U32(ArgbFromRgb(colors.background));
writer.U16(0);
writer.U16(0);
}
}
return ToJavaBytes(env, writer.Take());
}
@@ -0,0 +1,64 @@
package expo.modules.t3terminal
internal object GhosttyBridge {
init {
System.loadLibrary("ghostty-vt")
System.loadLibrary("t3terminal")
}
@JvmStatic
@Suppress("LongParameterList")
external fun nativeCreate(
cols: Int,
rows: Int,
cellWidth: Int,
cellHeight: Int,
foreground: Int,
background: Int,
cursor: Int,
palette: IntArray
): Long
@JvmStatic external fun nativeDestroy(handle: Long)
@JvmStatic external fun nativeFeed(handle: Long, data: ByteArray): ByteArray
@JvmStatic
external fun nativeResize(
handle: Long,
cols: Int,
rows: Int,
cellWidth: Int,
cellHeight: Int
): ByteArray
@JvmStatic external fun nativeScroll(handle: Long, rows: Int)
@JvmStatic
external fun nativeSetTheme(
handle: Long,
foreground: Int,
background: Int,
cursor: Int,
palette: IntArray
)
@JvmStatic external fun nativeSnapshot(handle: Long): ByteArray
@JvmStatic external fun nativeSelectWordAt(handle: Long, col: Int, row: Int): Boolean
@JvmStatic
external fun nativeExtendSelection(
handle: Long,
anchorCol: Int,
anchorRow: Int,
col: Int,
row: Int
)
@JvmStatic external fun nativeSelectAll(handle: Long): Boolean
@JvmStatic external fun nativeClearSelection(handle: Long)
@JvmStatic external fun nativeGetSelectionText(handle: Long): ByteArray?
}
@@ -51,6 +51,10 @@ class T3TerminalModule : Module() {
}
Events("onInput", "onResize")
OnViewDestroys { view: T3TerminalView ->
view.cleanup()
}
}
}
}
@@ -3,64 +3,69 @@ package expo.modules.t3terminal
import android.content.Context
import android.graphics.Color
import android.graphics.Typeface
import android.view.View
import android.text.Editable
import android.text.InputType
import android.text.TextWatcher
import android.view.KeyEvent
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import android.widget.LinearLayout
import android.widget.ScrollView
import android.widget.TextView
import androidx.core.widget.doAfterTextChanged
import android.widget.FrameLayout
import expo.modules.kotlin.AppContext
import expo.modules.kotlin.views.ExpoView
import expo.modules.kotlin.viewevent.EventDispatcher
import expo.modules.kotlin.views.ExpoView
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 container = FrameLayout(context)
private val terminalCanvas = TerminalCanvasView(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 terminalHandle = 0L
private var fedBuffer = ""
private var cols = 0
private var rows = 0
private var clearingInput = false
private var isCleanedUp = false
private var backgroundColorValue = Color.parseColor("#24292E")
private var foregroundColorValue = Color.parseColor("#D1D5DA")
private var mutedForegroundColorValue = Color.parseColor("#959DA5")
private var cursorColorValue = Color.parseColor("#009FFF")
private var paletteColors = IntArray(0)
var terminalKey: String = ""
set(value) {
if (field == value) return
field = value
contentDescription = "t3-terminal-$value"
recreateTerminal()
}
var initialBuffer: String = ""
set(value) {
if (field == value) return
field = value
textView.text = value.ifEmpty { "$ " }
scrollView.post {
scrollView.fullScroll(View.FOCUS_DOWN)
}
feedPendingBuffer()
}
var fontSize: Float = 10f
set(value) {
field = value
textView.textSize = value
terminalCanvas.fontSizeSp = value
inputView.textSize = max(value, 13f)
emitResize()
}
var appearanceScheme: String = "dark"
set(value) {
field = value
}
var themeConfig: String = ""
set(value) {
field = value
parseThemeConfig(value)
applyTheme()
}
var focusRequest: Double = 0.0
set(value) {
@@ -89,129 +94,320 @@ class T3TerminalView(context: Context, appContext: AppContext) : ExpoView(contex
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 = "$ "
terminalCanvas.fontSizeSp = fontSize
terminalCanvas.onRequestKeyboard = { requestKeyboardFocus() }
terminalCanvas.onScrollRows = { delta ->
if (terminalHandle != 0L) {
GhosttyBridge.nativeScroll(terminalHandle, delta)
renderSnapshot()
}
}
terminalCanvas.onCellMetricsChanged = { emitResize() }
terminalCanvas.selectionDelegate = object : TerminalSelectionDelegate {
override fun selectWordAt(col: Int, row: Int): Boolean {
if (terminalHandle == 0L) return false
val selected = GhosttyBridge.nativeSelectWordAt(terminalHandle, col, row)
if (selected) renderSnapshot()
return selected
}
override fun extendSelection(anchorCol: Int, anchorRow: Int, col: Int, row: Int) {
if (terminalHandle == 0L) return
GhosttyBridge.nativeExtendSelection(terminalHandle, anchorCol, anchorRow, col, row)
renderSnapshot()
}
override fun selectAll(): Boolean {
if (terminalHandle == 0L) return false
val selected = GhosttyBridge.nativeSelectAll(terminalHandle)
if (selected) renderSnapshot()
return selected
}
override fun clearSelection() {
if (terminalHandle == 0L) return
GhosttyBridge.nativeClearSelection(terminalHandle)
renderSnapshot()
}
override fun selectionText(): String? =
if (terminalHandle == 0L) {
null
} else {
GhosttyBridge.nativeGetSelectionText(terminalHandle)?.let { String(it, Charsets.UTF_8) }
}
}
configureInputView()
container.addView(
terminalCanvas,
FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT,
),
)
container.addView(inputView, FrameLayout.LayoutParams(1, 1))
addView(
container,
LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT),
)
applyTheme()
}
override fun onSizeChanged(width: Int, height: Int, oldWidth: Int, oldHeight: Int) {
super.onSizeChanged(width, height, oldWidth, oldHeight)
if (width != oldWidth || height != oldHeight) emitResize()
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
val childWidthSpec = MeasureSpec.makeMeasureSpec(measuredWidth, MeasureSpec.EXACTLY)
val childHeightSpec = MeasureSpec.makeMeasureSpec(measuredHeight, MeasureSpec.EXACTLY)
container.measure(childWidthSpec, childHeightSpec)
}
override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
container.layout(0, 0, right - left, bottom - top)
if (changed) emitResize()
}
fun cleanup() {
if (isCleanedUp) return
isCleanedUp = true
inputView.setOnEditorActionListener(null)
terminalCanvas.onScrollRows = null
terminalCanvas.onRequestKeyboard = null
terminalCanvas.onCellMetricsChanged = null
terminalCanvas.selectionDelegate = null
destroyTerminal()
}
private fun configureInputView() {
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.alpha = 0.01f
inputView.isFocusableInTouchMode = true
inputView.imeOptions = EditorInfo.IME_ACTION_SEND or
EditorInfo.IME_FLAG_NO_EXTRACT_UI or
EditorInfo.IME_FLAG_NO_FULLSCREEN or
EditorInfo.IME_FLAG_NO_PERSONALIZED_LEARNING
inputView.inputType = InputType.TYPE_CLASS_TEXT or
InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD or
InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS
inputView.setPadding(0, 0, 0, 0)
inputView.setOnFocusChangeListener { _, hasFocus ->
if (hasFocus) {
showKeyboard()
inputView.setOnEditorActionListener { _, actionId, event ->
val isKeyUp = event?.action == KeyEvent.ACTION_UP
val isImeSend = actionId == EditorInfo.IME_ACTION_SEND && !isKeyUp
val isHardwareEnter = event?.keyCode == KeyEvent.KEYCODE_ENTER &&
event.action == KeyEvent.ACTION_DOWN
val isEnter = isImeSend || isHardwareEnter
if (isEnter) {
// Enter must send CR: raw-mode TUIs treat LF as Ctrl+J (insert newline).
onInput(mapOf("data" to "\r"))
true
} else {
false
}
}
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
if (event.action != KeyEvent.ACTION_DOWN) return@setOnKeyListener false
when {
keyCode == android.view.KeyEvent.KEYCODE_DEL -> {
keyCode == KeyEvent.KEYCODE_DEL -> {
onInput(mapOf("data" to "\u007F"))
true
}
// Hardware keyboard Ctrl+A..Z -> control bytes 0x01..0x1A (Ctrl+C, Ctrl+Z, ...).
event.isCtrlPressed &&
keyCode in android.view.KeyEvent.KEYCODE_A..android.view.KeyEvent.KEYCODE_Z -> {
event.isCtrlPressed && keyCode in KeyEvent.KEYCODE_A..KeyEvent.KEYCODE_Z -> {
onInput(
mapOf("data" to (keyCode - android.view.KeyEvent.KEYCODE_A + 1).toChar().toString()),
mapOf("data" to (keyCode - KeyEvent.KEYCODE_A + 1).toChar().toString()),
)
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
}
inputView.addTextChangedListener(
object : TextWatcher {
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) = Unit
textView.setOnClickListener { requestKeyboardFocus() }
scrollView.setOnClickListener { requestKeyboardFocus() }
container.setOnClickListener { requestKeyboardFocus() }
isClickable = true
setOnClickListener { requestKeyboardFocus() }
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
if (clearingInput || s == null || count <= 0) return
val end = (start + count).coerceAtMost(s.length)
if (start >= end) return
val insertedText = s.subSequence(start, end).toString()
if (insertedText.isNotEmpty()) {
onInput(mapOf("data" to insertedText))
}
}
scrollView.addView(
textView,
LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT),
override fun afterTextChanged(editable: Editable?) {
if (clearingInput || editable.isNullOrEmpty()) return
clearingInput = true
editable.clear()
clearingInput = false
}
},
)
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()
}
@Suppress("ComplexCondition")
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()))
if (
width <= 0 ||
height <= 0 ||
terminalCanvas.width <= 0 ||
terminalCanvas.height <= 0 ||
isCleanedUp
) {
return
}
val nextCols = (terminalCanvas.usableWidth() / terminalCanvas.cellWidthPx)
.toInt()
.coerceIn(2, 400)
val nextRows = (terminalCanvas.usableHeight() / terminalCanvas.cellHeightPx)
.toInt()
.coerceIn(2, 200)
if (nextCols == cols && nextRows == rows && terminalHandle != 0L) return
cols = nextCols
rows = nextRows
val response = if (terminalHandle == 0L) {
createTerminal()
ByteArray(0)
} else {
GhosttyBridge.nativeResize(
terminalHandle,
cols,
rows,
terminalCanvas.cellWidthPx.toInt(),
terminalCanvas.cellHeightPx.toInt(),
)
}
emitResponse(response)
onResize(mapOf("cols" to cols, "rows" to rows))
feedPendingBuffer()
renderSnapshot()
}
@Suppress("ComplexCondition")
private fun createTerminal() {
if (terminalHandle != 0L || cols <= 0 || rows <= 0 || isCleanedUp) return
terminalHandle = GhosttyBridge.nativeCreate(
cols,
rows,
terminalCanvas.cellWidthPx.toInt(),
terminalCanvas.cellHeightPx.toInt(),
foregroundColorValue,
backgroundColorValue,
cursorColorValue,
paletteColors,
)
fedBuffer = ""
}
private fun recreateTerminal() {
if (terminalHandle == 0L) return
destroyTerminal()
createTerminal()
feedPendingBuffer()
renderSnapshot()
}
private fun destroyTerminal() {
if (terminalHandle == 0L) return
GhosttyBridge.nativeDestroy(terminalHandle)
terminalHandle = 0L
fedBuffer = ""
terminalCanvas.resetSelectionState()
}
private fun feedPendingBuffer() {
if (terminalHandle == 0L || initialBuffer == fedBuffer) return
if (!initialBuffer.startsWith(fedBuffer)) {
recreateTerminal()
if (terminalHandle == 0L) return
}
val suffix = initialBuffer.substring(fedBuffer.length)
if (suffix.isNotEmpty()) {
emitResponse(GhosttyBridge.nativeFeed(terminalHandle, suffix.toByteArray(Charsets.UTF_8)))
// New output invalidates an active selection (matches the web drawer);
// otherwise the copy toolbar drifts out of sync with the grid.
if (terminalCanvas.hasActiveSelection()) {
GhosttyBridge.nativeClearSelection(terminalHandle)
terminalCanvas.resetSelectionState()
}
}
fedBuffer = initialBuffer
renderSnapshot()
}
private fun renderSnapshot() {
if (terminalHandle == 0L) return
TerminalFrame.decode(
GhosttyBridge.nativeSnapshot(terminalHandle)
)?.let(terminalCanvas::setFrame)
}
private fun emitResponse(response: ByteArray) {
if (response.isNotEmpty()) {
onInput(mapOf("data" to String(response, Charsets.UTF_8)))
}
}
private fun requestKeyboardFocus() {
inputView.requestFocus()
showKeyboard()
val inputMethodManager = context.getSystemService(
Context.INPUT_METHOD_SERVICE
) as? InputMethodManager
inputMethodManager?.showSoftInput(inputView, InputMethodManager.SHOW_IMPLICIT)
}
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)
terminalCanvas.setBackgroundColor(backgroundColorValue)
if (terminalHandle != 0L) {
GhosttyBridge.nativeSetTheme(
terminalHandle,
foregroundColorValue,
backgroundColorValue,
cursorColorValue,
paletteColors,
)
renderSnapshot()
}
}
@Suppress("LoopWithTooManyJumpStatements")
private fun parseThemeConfig(config: String) {
val palette = sortedMapOf<Int, Int>()
for (line in config.lineSequence()) {
val parts = line.split('=', limit = 2)
if (parts.size != 2) continue
val key = parts[0].trim()
val value = parts[1].trim()
when (key) {
"cursor-color" -> cursorColorValue = parseColor(value, cursorColorValue)
"palette" -> {
val paletteParts = value.split('=', limit = 2)
val index = paletteParts.firstOrNull()?.trim()?.toIntOrNull() ?: continue
val color = paletteParts.getOrNull(1)?.trim() ?: continue
if (index in 0..255) palette[index] = parseColor(color, foregroundColorValue)
}
}
}
if (palette.isNotEmpty()) {
val lastIndex = palette.lastKey()
paletteColors = IntArray(lastIndex + 1) { index ->
palette[index] ?: foregroundColorValue
}
}
}
private fun parseColor(value: String, fallback: Int): Int =
@@ -220,9 +416,4 @@ class T3TerminalView(context: Context, appContext: AppContext) : ExpoView(contex
} 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,628 @@
package expo.modules.t3terminal
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Rect
import android.graphics.Typeface
import android.util.Log
import android.view.ActionMode
import android.view.GestureDetector
import android.view.HapticFeedbackConstants
import android.view.Menu
import android.view.MenuItem
import android.view.MotionEvent
import android.view.View
import android.widget.OverScroller
import kotlin.math.ceil
import kotlin.math.max
import kotlin.math.min
/**
* Bundled terminal font with Nerd Font glyphs (powerline, file icons).
* MesloLGS NF is the powerlevel10k-tuned Meslo Nerd Font patch.
*/
internal object TerminalTypefaces {
private var loaded = false
var regular: Typeface = Typeface.MONOSPACE
private set
var bold: Typeface = Typeface.create(Typeface.MONOSPACE, Typeface.BOLD)
private set
@Suppress("TooGenericExceptionCaught") // Typeface.createFromAsset exposes RuntimeException.
fun ensureLoaded(context: Context) {
if (loaded) return
loaded = true
try {
regular = Typeface.createFromAsset(context.assets, "fonts/MesloLGS-NF-Regular.ttf")
bold = Typeface.createFromAsset(context.assets, "fonts/MesloLGS-NF-Bold.ttf")
} catch (error: RuntimeException) {
Log.w("TerminalCanvasView", "bundled terminal font unavailable, using monospace", error)
}
}
}
/**
* Selection operations backed by the native terminal. The terminal owns the
* selection state; the canvas only drives gestures and renders the result.
*/
internal interface TerminalSelectionDelegate {
fun selectWordAt(col: Int, row: Int): Boolean
fun extendSelection(anchorCol: Int, anchorRow: Int, col: Int, row: Int)
fun selectAll(): Boolean
fun clearSelection()
fun selectionText(): String?
}
internal class TerminalCanvasView(context: Context) : View(context) {
companion object {
const val FLAG_BOLD = 1 shl 0
const val FLAG_ITALIC = 1 shl 1
const val FLAG_INVISIBLE = 1 shl 4
const val FLAG_STRIKETHROUGH = 1 shl 5
const val FLAG_OVERLINE = 1 shl 6
const val FLAG_UNDERLINE = 1 shl 7
const val FLAG_SELECTED = 1 shl 8
private const val MENU_COPY = 1
private const val MENU_SELECT_ALL = 2
private const val HANDLE_COLOR = 0xFF7AA2F7.toInt()
}
private val density = resources.displayMetrics.density
private val scaledDensity = density * resources.configuration.fontScale
private val paint = Paint(Paint.ANTI_ALIAS_FLAG or Paint.SUBPIXEL_TEXT_FLAG)
init {
TerminalTypefaces.ensureLoaded(context)
}
private val regularTypeface = TerminalTypefaces.regular
private val boldTypeface = TerminalTypefaces.bold
private val italicTypeface = Typeface.create(TerminalTypefaces.regular, Typeface.ITALIC)
private val boldItalicTypeface = Typeface.create(TerminalTypefaces.bold, Typeface.ITALIC)
private val gestureDetector = GestureDetector(context, TerminalGestureListener())
private val contentPadding = 8f * density
private var frame: TerminalFrame? = null
private var scrollRemainder = 0f
private val scroller = OverScroller(context)
private var flingLastY = 0
private val flingRunnable = object : Runnable {
override fun run() {
if (!scroller.computeScrollOffset()) return
val currentY = scroller.currY
val deltaPx = (currentY - flingLastY).toFloat()
flingLastY = currentY
scrollRemainder += -deltaPx / cellHeightPx
val rows = scrollRemainder.toInt()
if (rows != 0) {
scrollRemainder -= rows
onScrollRows?.invoke(rows)
}
postOnAnimation(this)
}
}
private var cursorOn = true
private val cursorBlink = object : Runnable {
override fun run() {
val currentFrame = frame ?: return
if (!currentFrame.cursorBlinking || !currentFrame.cursorVisible) return
cursorOn = !cursorOn
invalidate()
postDelayed(this, 500)
}
}
var onScrollRows: ((Int) -> Unit)? = null
var onRequestKeyboard: (() -> Unit)? = null
var onCellMetricsChanged: (() -> Unit)? = null
var selectionDelegate: TerminalSelectionDelegate? = null
private val handlePaint = Paint(Paint.ANTI_ALIAS_FLAG)
private var selectionActive = false
private var dragSelecting = false
private var draggingHandle = false
private var anchorCol = 0
private var anchorRow = 0
private var extentCol = 0
private var extentRow = 0
// Word-snapped span from the initial long-press; extending anchors to the
// far word edge so the word never shrinks mid-drag.
private var wordStartCol = 0
private var wordStartRow = 0
private var wordEndCol = 0
private var wordEndRow = 0
private var actionMode: ActionMode? = null
// Actual selection endpoints in viewport cells, derived from the decoded
// frame (word-snap can extend past the pressed cell). Drive handle
// placement and hit testing.
private var selectionEndpointsValid = false
private var selectionStartCol = 0
private var selectionStartRow = 0
private var selectionEndCol = 0
private var selectionEndRow = 0
var fontSizeSp: Float = 10f
set(value) {
if (field == value) return
field = value
updateCellMetrics()
}
var cellWidthPx: Float = 1f
private set
var cellHeightPx: Float = 1f
private set
private var baselineOffsetPx: Float = 1f
init {
isClickable = true
isFocusable = true
isFocusableInTouchMode = true
paint.typeface = regularTypeface
updateCellMetrics()
}
fun setFrame(value: TerminalFrame) {
frame = value
cursorOn = true
updateSelectionEndpoints()
removeCallbacks(cursorBlink)
if (value.cursorBlinking && value.cursorVisible) postDelayed(cursorBlink, 500)
invalidate()
}
fun resetSelectionState() {
selectionActive = false
dragSelecting = false
draggingHandle = false
selectionEndpointsValid = false
actionMode?.finish()
}
fun hasActiveSelection(): Boolean = selectionActive
fun usableWidth(): Float = max(width - contentPadding * 2f, 1f)
fun usableHeight(): Float = max(height - contentPadding * 2f, 1f)
@Suppress("NestedBlockDepth", "ComplexCondition")
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
val currentFrame = frame
if (currentFrame == null) {
canvas.drawColor(Color.TRANSPARENT)
return
}
canvas.drawColor(currentFrame.background)
canvas.save()
canvas.clipRect(
contentPadding,
contentPadding,
width - contentPadding,
height - contentPadding,
)
for (row in 0 until currentFrame.rows) {
val top = contentPadding + row * cellHeightPx
val bottom = top + cellHeightPx
for (column in 0 until currentFrame.cols) {
val index = row * currentFrame.cols + column
val left = contentPadding + column * cellWidthPx
val right = left + cellWidthPx
val background = currentFrame.cellBackgrounds[index]
val flags = currentFrame.cellFlags[index]
paint.style = Paint.Style.FILL
paint.color = if (flags and FLAG_SELECTED != 0) {
blend(currentFrame.cursorColor, background, 0.32f)
} else {
background
}
if (paint.color != currentFrame.background || flags and FLAG_SELECTED != 0) {
canvas.drawRect(left, top, right + 0.5f, bottom + 0.5f, paint)
}
val text = currentFrame.cellText[index]
if (text.isNotEmpty() && flags and FLAG_INVISIBLE == 0) {
configureTextPaint(flags, currentFrame.cellForegrounds[index])
canvas.drawText(text, left, top + baselineOffsetPx, paint)
if (flags and FLAG_OVERLINE != 0) {
canvas.drawRect(left, top + 1f, right, top + max(2f, density), paint)
}
}
}
}
if (currentFrame.cursorVisible && cursorOn &&
currentFrame.cursorX in 0 until currentFrame.cols &&
currentFrame.cursorY in 0 until currentFrame.rows
) {
drawCursor(canvas, currentFrame)
}
canvas.restore()
drawSelectionHandles(canvas)
}
override fun onTouchEvent(event: MotionEvent): Boolean {
if (event.actionMasked == MotionEvent.ACTION_DOWN) {
parent?.requestDisallowInterceptTouchEvent(true)
// Touch-down always stops momentum, even when the event is consumed by
// a selection-handle grab and never reaches the gesture detector.
scroller.forceFinished(true)
removeCallbacks(flingRunnable)
} else if (event.actionMasked == MotionEvent.ACTION_UP ||
event.actionMasked == MotionEvent.ACTION_CANCEL
) {
parent?.requestDisallowInterceptTouchEvent(false)
}
return when {
dragSelecting -> {
when (event.actionMasked) {
MotionEvent.ACTION_MOVE -> extendSelectionTo(event.x, event.y)
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
dragSelecting = false
showSelectionActions()
}
}
true
}
event.actionMasked == MotionEvent.ACTION_DOWN && grabHandleAt(event.x, event.y) -> true
else -> gestureDetector.onTouchEvent(event) || super.onTouchEvent(event)
}
}
override fun onDetachedFromWindow() {
removeCallbacks(cursorBlink)
removeCallbacks(flingRunnable)
actionMode?.finish()
super.onDetachedFromWindow()
}
private fun updateCellMetrics() {
paint.textSize = fontSizeSp * scaledDensity
paint.typeface = regularTypeface
cellWidthPx = ceil(paint.measureText("M").toDouble()).toFloat().coerceAtLeast(1f)
val metrics = paint.fontMetrics
val glyphHeight = metrics.descent - metrics.ascent
cellHeightPx = ceil((glyphHeight * 1.12f).toDouble()).toFloat().coerceAtLeast(1f)
baselineOffsetPx = (cellHeightPx - glyphHeight) / 2f - metrics.ascent
onCellMetricsChanged?.invoke()
invalidate()
}
private fun configureTextPaint(flags: Int, color: Int) {
val bold = flags and FLAG_BOLD != 0
val italic = flags and FLAG_ITALIC != 0
paint.typeface = when {
bold && italic -> boldItalicTypeface
bold -> boldTypeface
italic -> italicTypeface
else -> regularTypeface
}
paint.textSize = fontSizeSp * scaledDensity
paint.color = color
paint.style = Paint.Style.FILL
paint.isUnderlineText = flags and FLAG_UNDERLINE != 0
paint.isStrikeThruText = flags and FLAG_STRIKETHROUGH != 0
}
private fun drawCursor(canvas: Canvas, currentFrame: TerminalFrame) {
val left = contentPadding + currentFrame.cursorX * cellWidthPx
val top = contentPadding + currentFrame.cursorY * cellHeightPx
val right = left + cellWidthPx
val bottom = top + cellHeightPx
paint.color = currentFrame.cursorColor
paint.isUnderlineText = false
paint.isStrikeThruText = false
when (currentFrame.cursorStyle) {
0 -> canvas.drawRect(left, top, left + max(2f * density, 2f), bottom, paint)
2 -> canvas.drawRect(left, bottom - max(2f * density, 2f), right, bottom, paint)
3 -> {
paint.style = Paint.Style.STROKE
paint.strokeWidth = max(density, 1f)
canvas.drawRect(left, top, right, bottom, paint)
}
else -> {
paint.style = Paint.Style.FILL
canvas.drawRect(left, top, right, bottom, paint)
val index = currentFrame.cursorY * currentFrame.cols + currentFrame.cursorX
val text = currentFrame.cellText[index]
if (text.isNotEmpty()) {
configureTextPaint(currentFrame.cellFlags[index], currentFrame.background)
canvas.drawText(text, left, top + baselineOffsetPx, paint)
}
}
}
}
private fun columnAt(px: Float): Int {
val cols = frame?.cols ?: return 0
return ((px - contentPadding) / cellWidthPx).toInt().coerceIn(0, max(cols - 1, 0))
}
private fun rowAt(py: Float): Int {
val rows = frame?.rows ?: return 0
return ((py - contentPadding) / cellHeightPx).toInt().coerceIn(0, max(rows - 1, 0))
}
private fun startWordSelection(px: Float, py: Float) {
val delegate = selectionDelegate ?: return
val col = columnAt(px)
val row = rowAt(py)
// Set before selectWordAt: the delegate re-renders synchronously and
// updateSelectionEndpoints only scans while a selection is active.
selectionActive = true
if (!delegate.selectWordAt(col, row)) {
selectionActive = false
return
}
dragSelecting = true
draggingHandle = false
if (selectionEndpointsValid) {
wordStartCol = selectionStartCol
wordStartRow = selectionStartRow
wordEndCol = selectionEndCol
wordEndRow = selectionEndRow
} else {
wordStartCol = col
wordStartRow = row
wordEndCol = col
wordEndRow = row
}
anchorCol = wordStartCol
anchorRow = wordStartRow
extentCol = col
extentRow = row
performHapticFeedback(HapticFeedbackConstants.LONG_PRESS)
}
private fun extendSelectionTo(px: Float, py: Float) {
if (!selectionActive) return
val col = columnAt(px)
val row = rowAt(py)
if (col == extentCol && row == extentRow) return
extentCol = col
extentRow = row
if (!draggingHandle) {
val beforeWord = row < wordStartRow || (row == wordStartRow && col < wordStartCol)
if (beforeWord) {
anchorCol = wordEndCol
anchorRow = wordEndRow
} else {
anchorCol = wordStartCol
anchorRow = wordStartRow
}
}
selectionDelegate?.extendSelection(anchorCol, anchorRow, col, row)
}
private fun clearSelection() {
if (!selectionActive) return
selectionActive = false
dragSelecting = false
draggingHandle = false
selectionEndpointsValid = false
actionMode?.finish()
selectionDelegate?.clearSelection()
}
private fun copySelection() {
val text = selectionDelegate?.selectionText() ?: return
if (text.isEmpty()) return
val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as? ClipboardManager
clipboard?.setPrimaryClip(ClipData.newPlainText("Terminal", text))
}
private fun handleCenterX(col: Int, leadingEdge: Boolean): Float =
contentPadding + (col + if (leadingEdge) 0 else 1) * cellWidthPx
private fun handleCenterY(row: Int): Float =
contentPadding + (row + 1) * cellHeightPx + handleRadius()
private fun handleRadius(): Float = max(cellHeightPx * 0.45f, 12f)
/**
* Begin dragging when the touch lands on a selection handle. The opposite
* endpoint becomes the drag anchor so the grabbed end follows the finger.
*/
private fun grabHandleAt(px: Float, py: Float): Boolean {
if (!selectionActive || !selectionEndpointsValid) return false
val slop = max(handleRadius() * 2f, 24 * density)
fun near(cx: Float, cy: Float): Boolean {
val dx = px - cx
val dy = py - cy
return dx * dx + dy * dy <= slop * slop
}
val startGrabbed =
near(handleCenterX(selectionStartCol, true), handleCenterY(selectionStartRow))
val endGrabbed =
!startGrabbed && near(handleCenterX(selectionEndCol, false), handleCenterY(selectionEndRow))
val handleGrabbed = startGrabbed || endGrabbed
if (handleGrabbed) {
if (startGrabbed) {
anchorCol = selectionEndCol
anchorRow = selectionEndRow
extentCol = selectionStartCol
extentRow = selectionStartRow
} else {
anchorCol = selectionStartCol
anchorRow = selectionStartRow
extentCol = selectionEndCol
extentRow = selectionEndRow
}
dragSelecting = true
draggingHandle = true
actionMode?.finish()
}
return handleGrabbed
}
/** Scan the decoded frame for the first/last selected cells. */
private fun updateSelectionEndpoints() {
selectionEndpointsValid = false
val currentFrame = frame
if (!selectionActive || currentFrame == null) return
val totalCells = currentFrame.cols * currentFrame.rows
var first = -1
var last = -1
for (index in 0 until totalCells) {
if (currentFrame.cellFlags[index] and FLAG_SELECTED != 0) {
if (first < 0) first = index
last = index
}
}
if (first >= 0 && currentFrame.cols > 0) {
selectionStartCol = first % currentFrame.cols
selectionStartRow = first / currentFrame.cols
selectionEndCol = last % currentFrame.cols
selectionEndRow = last / currentFrame.cols
selectionEndpointsValid = true
}
}
// Anchor the toolbar to the actual word-snapped endpoints when known;
// gesture cells can lag behind what the terminal selected.
private fun selectionBounds(): Rect {
val startCol = if (selectionEndpointsValid) selectionStartCol else min(anchorCol, extentCol)
val endCol = if (selectionEndpointsValid) selectionEndCol else max(anchorCol, extentCol)
val startRow = if (selectionEndpointsValid) selectionStartRow else min(anchorRow, extentRow)
val endRow = if (selectionEndpointsValid) selectionEndRow else max(anchorRow, extentRow)
val left = contentPadding + min(startCol, endCol) * cellWidthPx
val right = contentPadding + (max(startCol, endCol) + 1) * cellWidthPx
val top = contentPadding + startRow * cellHeightPx
val bottom = contentPadding + (endRow + 1) * cellHeightPx
return Rect(left.toInt(), top.toInt(), right.toInt(), bottom.toInt())
}
private fun showSelectionActions() {
if (actionMode != null || !selectionActive) return
actionMode = startActionMode(
object : ActionMode.Callback2() {
override fun onCreateActionMode(mode: ActionMode, menu: Menu): Boolean {
menu.add(Menu.NONE, MENU_COPY, 0, android.R.string.copy)
menu.add(Menu.NONE, MENU_SELECT_ALL, 1, android.R.string.selectAll)
return true
}
override fun onPrepareActionMode(mode: ActionMode, menu: Menu): Boolean = false
override fun onActionItemClicked(mode: ActionMode, item: MenuItem): Boolean =
when (item.itemId) {
MENU_COPY -> {
copySelection()
clearSelection()
true
}
MENU_SELECT_ALL -> {
val currentFrame = frame
if (currentFrame != null && selectionDelegate?.selectAll() == true) {
anchorCol = 0
anchorRow = 0
extentCol = max(currentFrame.cols - 1, 0)
extentRow = max(currentFrame.rows - 1, 0)
}
true
}
else -> false
}
override fun onDestroyActionMode(mode: ActionMode) {
actionMode = null
// Dismissing the toolbar (e.g. Back) drops the selection too —
// except mid-drag, where grabHandleAt finishes the mode on purpose.
if (selectionActive && !dragSelecting) clearSelection()
}
override fun onGetContentRect(mode: ActionMode, view: View, outRect: Rect) {
outRect.set(selectionBounds())
}
},
ActionMode.TYPE_FLOATING,
)
}
private fun drawSelectionHandles(canvas: Canvas) {
if (!selectionActive || !selectionEndpointsValid) return
val radius = handleRadius()
handlePaint.color = HANDLE_COLOR
val stemWidth = max(radius / 4f, 2f)
fun drawHandle(cx: Float, row: Int) {
val cornerY = contentPadding + (row + 1) * cellHeightPx
val cy = handleCenterY(row)
canvas.drawRect(cx - stemWidth / 2f, cornerY, cx + stemWidth / 2f, cy, handlePaint)
canvas.drawCircle(cx, cy, radius, handlePaint)
}
drawHandle(handleCenterX(selectionStartCol, true), selectionStartRow)
drawHandle(handleCenterX(selectionEndCol, false), selectionEndRow)
}
private fun blend(foreground: Int, background: Int, amount: Float): Int {
val inverseAmount = 1f - amount
return Color.rgb(
(Color.red(foreground) * amount + Color.red(background) * inverseAmount).toInt(),
(Color.green(foreground) * amount + Color.green(background) * inverseAmount).toInt(),
(Color.blue(foreground) * amount + Color.blue(background) * inverseAmount).toInt(),
)
}
private inner class TerminalGestureListener : GestureDetector.SimpleOnGestureListener() {
override fun onDown(event: MotionEvent): Boolean {
scroller.forceFinished(true)
removeCallbacks(flingRunnable)
onRequestKeyboard?.invoke()
return true
}
override fun onSingleTapUp(event: MotionEvent): Boolean {
if (selectionActive) {
clearSelection()
} else {
performClick()
}
return true
}
override fun onLongPress(event: MotionEvent) {
startWordSelection(event.x, event.y)
}
override fun onScroll(
first: MotionEvent?,
current: MotionEvent,
distanceX: Float,
distanceY: Float
): Boolean {
scrollRemainder += distanceY / cellHeightPx
val rows = scrollRemainder.toInt()
if (rows != 0) {
scrollRemainder -= rows
onScrollRows?.invoke(rows)
}
return true
}
override fun onFling(
first: MotionEvent?,
current: MotionEvent,
velocityX: Float,
velocityY: Float
): Boolean {
flingLastY = 0
scroller.fling(0, 0, 0, velocityY.toInt(), 0, 0, Int.MIN_VALUE / 2, Int.MAX_VALUE / 2)
postOnAnimation(flingRunnable)
return true
}
}
}
@@ -0,0 +1,82 @@
package expo.modules.t3terminal
import java.nio.ByteBuffer
import java.nio.ByteOrder
internal data class TerminalFrame(
val cols: Int,
val rows: Int,
val cursorX: Int,
val cursorY: Int,
val cursorVisible: Boolean,
val cursorStyle: Int,
val cursorBlinking: Boolean,
val foreground: Int,
val background: Int,
val cursorColor: Int,
val cellForegrounds: IntArray,
val cellBackgrounds: IntArray,
val cellFlags: IntArray,
val cellText: Array<String>
) {
companion object {
private const val MAGIC = 0x54563354
private const val VERSION = 1
private const val HEADER_BYTES = 32
private const val CELL_HEADER_BYTES = 12
@Suppress("ReturnCount")
fun decode(bytes: ByteArray): TerminalFrame? {
if (bytes.size < HEADER_BYTES) return null
val buffer = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN)
if (buffer.int != MAGIC || buffer.short.toInt() != VERSION) return null
val cols = buffer.short.toInt() and 0xFFFF
val rows = buffer.short.toInt() and 0xFFFF
val cursorX = buffer.short.toInt() and 0xFFFF
val cursorY = buffer.short.toInt() and 0xFFFF
val cursorVisible = buffer.get().toInt() != 0
val cursorStyle = buffer.get().toInt() and 0xFF
val cursorBlinking = buffer.get().toInt() != 0
buffer.get()
val foreground = buffer.int
val background = buffer.int
val cursorColor = buffer.int
val cellCount = cols * rows
val foregrounds = IntArray(cellCount)
val backgrounds = IntArray(cellCount)
val flags = IntArray(cellCount)
val text = Array(cellCount) { "" }
for (index in 0 until cellCount) {
if (buffer.remaining() < CELL_HEADER_BYTES) return null
foregrounds[index] = buffer.int
backgrounds[index] = buffer.int
flags[index] = buffer.short.toInt() and 0xFFFF
val textLength = buffer.short.toInt() and 0xFFFF
if (buffer.remaining() < textLength) return null
if (textLength > 0) {
text[index] = String(bytes, buffer.position(), textLength, Charsets.UTF_8)
buffer.position(buffer.position() + textLength)
}
}
return TerminalFrame(
cols = cols,
rows = rows,
cursorX = cursorX,
cursorY = cursorY,
cursorVisible = cursorVisible,
cursorStyle = cursorStyle,
cursorBlinking = cursorBlinking,
foreground = foreground,
background = background,
cursorColor = cursorColor,
cellForegrounds = foregrounds,
cellBackgrounds = backgrounds,
cellFlags = flags,
cellText = text,
)
}
}
}
@@ -0,0 +1,152 @@
#!/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-vt"
PATCH_DIR="${SCRIPT_DIR}/libghostty-android-patches"
GHOSTTY_REVISION="${GHOSTTY_REVISION:-9f62873bf195e4d8a762d768a1405a5f2f7b1697}"
GHOSTTY_SOURCE_DIR="${GHOSTTY_SOURCE_DIR:-${HOME}/.cache/t3code/ghostty-${GHOSTTY_REVISION:0:8}}"
GHOSTTY_ZIG_VERSION="${GHOSTTY_ZIG_VERSION:-0.15.2}"
GHOSTTY_ZIG="${GHOSTTY_ZIG:-}"
ANDROID_NDK_HOME="${ANDROID_NDK_HOME:-}"
log() {
printf '[libghostty-vt-android] %s\n' "$*"
}
die() {
printf '[libghostty-vt-android] 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 host_os host_arch cache_dir
host_os="$(uname -s | tr '[:upper:]' '[:lower:]')"
host_arch="$(uname -m)"
case "${host_os}" in
darwin) host_os="macos" ;;
linux) ;;
*) die "unsupported host OS for Zig download: ${host_os}" ;;
esac
case "${host_arch}" in
arm64) host_arch="aarch64" ;;
aarch64 | x86_64) ;;
*) die "unsupported host architecture for Zig download: ${host_arch}" ;;
esac
cache_dir="${HOME}/.cache/t3code/zig-${GHOSTTY_ZIG_VERSION}"
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-${host_arch}-${host_os}-${GHOSTTY_ZIG_VERSION}.tar.xz" \
| tar -xJ --strip-components=1 -C "${cache_dir}"
}
ensure_ghostty_source() {
if [[ ! -d "${GHOSTTY_SOURCE_DIR}/.git" ]]; then
require_cmd git
log "cloning Ghostty ${GHOSTTY_REVISION}"
git clone --filter=blob:none --no-checkout https://github.com/ghostty-org/ghostty.git \
"${GHOSTTY_SOURCE_DIR}"
git -C "${GHOSTTY_SOURCE_DIR}" fetch --depth=1 origin "${GHOSTTY_REVISION}"
git -C "${GHOSTTY_SOURCE_DIR}" checkout --detach "${GHOSTTY_REVISION}"
fi
local actual_revision
actual_revision="$(git -C "${GHOSTTY_SOURCE_DIR}" rev-parse HEAD)"
[[ "${actual_revision}" == "${GHOSTTY_REVISION}" ]] || \
die "expected Ghostty ${GHOSTTY_REVISION}, found ${actual_revision}"
}
apply_ghostty_patches() {
[[ -d "${PATCH_DIR}" ]] || return
local patch_file patch_name
for patch_file in "${PATCH_DIR}"/*.patch; do
[[ -e "${patch_file}" ]] || continue
patch_name="$(basename "${patch_file}")"
if git -C "${GHOSTTY_SOURCE_DIR}" apply --reverse --check "${patch_file}" >/dev/null 2>&1; then
log "patch already applied: ${patch_name}"
continue
fi
log "applying patch: ${patch_name}"
git -C "${GHOSTTY_SOURCE_DIR}" apply --check "${patch_file}"
git -C "${GHOSTTY_SOURCE_DIR}" apply "${patch_file}"
done
}
if [[ -z "${ANDROID_NDK_HOME}" ]]; then
die "ANDROID_NDK_HOME must point to an installed Android NDK"
fi
[[ -d "${ANDROID_NDK_HOME}" ]] || die "Android NDK not found: ${ANDROID_NDK_HOME}"
ensure_zig
ensure_ghostty_source
apply_ghostty_patches
strip_tool="${ANDROID_NDK_HOME}/toolchains/llvm/prebuilt"
strip_tool="$(find "${strip_tool}" -path '*/bin/llvm-strip' -print -quit)"
[[ -x "${strip_tool}" ]] || die "llvm-strip not found under ${ANDROID_NDK_HOME}"
targets=(
"arm64-v8a:aarch64-linux-android"
"armeabi-v7a:arm-linux-androideabi"
"x86:x86-linux-android"
"x86_64:x86_64-linux-android"
)
build_root="$(mktemp -d)"
trap 'rm -rf "${build_root}"' EXIT
mkdir -p "${VENDOR_DIR}/include"
for entry in "${targets[@]}"; do
abi="${entry%%:*}"
target="${entry#*:}"
prefix="${build_root}/${abi}"
log "building ${abi} (${target})"
(
cd "${GHOSTTY_SOURCE_DIR}"
ANDROID_NDK_HOME="${ANDROID_NDK_HOME}" "${GHOSTTY_ZIG}" build \
-Demit-lib-vt \
-Dtarget="${target}" \
-Doptimize=ReleaseFast \
-Dstrip=true \
-Dsimd=false \
-p "${prefix}"
)
mkdir -p "${MODULE_DIR}/android/src/main/jniLibs/${abi}"
cp "${prefix}/lib/libghostty-vt.so.0.1.0" \
"${MODULE_DIR}/android/src/main/jniLibs/${abi}/libghostty-vt.so"
"${strip_tool}" --strip-unneeded \
"${MODULE_DIR}/android/src/main/jniLibs/${abi}/libghostty-vt.so"
done
rm -rf "${VENDOR_DIR}/include/ghostty"
cp -R "${build_root}/arm64-v8a/include/ghostty" "${VENDOR_DIR}/include/ghostty"
cp "${GHOSTTY_SOURCE_DIR}/LICENSE" "${VENDOR_DIR}/LICENSE"
printf '%s\n' "${GHOSTTY_REVISION}" > "${VENDOR_DIR}/VERSION"
log "done"
@@ -0,0 +1,25 @@
diff --git a/src/build/GhosttyZig.zig b/src/build/GhosttyZig.zig
index 44c300e15..f8d4296a2 100644
--- a/src/build/GhosttyZig.zig
+++ b/src/build/GhosttyZig.zig
@@ -123,7 +123,7 @@ fn initVt(
// no-libcxx mode (HWY_NO_LIBCXX / SIMDUTF_NO_LIBCXX) so we
// don't need libcpp. System-provided simdutf headers still
// use C++ stdlib headers, so we need libcpp in that case.
- .link_libc = if (cfg.simd) true else null,
+ .link_libc = if (cfg.simd or cfg.target.result.abi.isAndroid()) true else null,
.link_libcpp = if (cfg.simd and
b.systemIntegrationOption("simdutf", .{}) and
cfg.target.result.abi != .msvc) true else null,
diff --git a/src/terminal/c/sys.zig b/src/terminal/c/sys.zig
index c4b2b17f2..afb98ed4b 100644
--- a/src/terminal/c/sys.zig
+++ b/src/terminal/c/sys.zig
@@ -227,6 +227,7 @@ pub fn logStderr(
message_len: usize,
) callconv(lib.calling_conv) void {
if (comptime builtin.target.cpu.arch.isWasm()) return;
+ if (comptime builtin.target.abi.isAndroid()) return;
const scope = scope_ptr[0..scope_len];
const message = message_ptr[0..message_len];
@@ -0,0 +1,11 @@
diff --git a/src/build/GhosttyLibVt.zig b/src/build/GhosttyLibVt.zig
--- a/src/build/GhosttyLibVt.zig
+++ b/src/build/GhosttyLibVt.zig
@@ -236,6 +236,7 @@ fn initLib(
if (lib.rootModuleTarget().abi.isAndroid()) {
// Support 16kb page sizes, required for Android 15+.
+ lib.link_z_common_page_size = 16384; // 16kb
lib.link_z_max_page_size = 16384; // 16kb
try @import("android_ndk").addPaths(b, lib);
}
+9 -2
View File
@@ -5,13 +5,14 @@
"main": "index.ts",
"scripts": {
"dev": "expo start --clear",
"dev:client": "APP_VARIANT=development expo start --dev-client --scheme t3code-dev --clear",
"dev:client": "APP_VARIANT=development expo start --dev-client --scheme t3code-dev --clear --lan",
"dev:client:preview": "eas env:exec preview 'EXPO_NO_DOTENV=1 APP_VARIANT=preview expo start --dev-client --scheme t3code-preview --clear --lan'",
"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:dev": "APP_VARIANT=development EXPO_NO_GIT_STATUS=1 expo prebuild --clean --platform android && REACT_NATIVE_PACKAGER_HOSTNAME=localhost 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",
@@ -22,6 +23,7 @@
"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",
"ios:release": "APP_VARIANT=production EXPO_NO_GIT_STATUS=1 expo prebuild --clean --platform ios && expo run:ios --configuration Release --no-bundler",
"eas:ios:dev": "eas build --profile development -p ios",
"eas:ios:preview": "eas build --profile preview -p ios",
"eas:ios:preview:dev": "eas build --profile preview:dev -p ios",
@@ -63,12 +65,14 @@
"@t3tools/mobile-review-diff-native": "file:./modules/t3-review-diff",
"@t3tools/mobile-terminal-native": "file:./modules/t3-terminal",
"@t3tools/shared": "workspace:*",
"@tabler/icons-react-native": "^3.44.0",
"clsx": "^2.1.1",
"diff": "8.0.3",
"effect": "catalog:",
"expo": "~56.0.12",
"expo-asset": "~56.0.17",
"expo-auth-session": "~56.0.14",
"expo-blur": "~56.0.3",
"expo-build-properties": "~56.0.19",
"expo-camera": "~56.0.8",
"expo-clipboard": "~56.0.4",
@@ -79,13 +83,16 @@
"expo-font": "~56.0.7",
"expo-glass-effect": "~56.0.4",
"expo-haptics": "~56.0.3",
"expo-image": "~56.0.11",
"expo-image-picker": "~56.0.18",
"expo-linking": "~56.0.14",
"expo-network": "~56.0.5",
"expo-notifications": "~56.0.18",
"expo-paste-input": "^0.1.15",
"expo-quick-actions": "^6.0.2",
"expo-secure-store": "~56.0.4",
"expo-splash-screen": "~56.0.10",
"expo-sqlite": "~56.0.5",
"expo-symbols": "~56.0.6",
"expo-updates": "~56.0.19",
"expo-web-browser": "~56.0.5",
@@ -0,0 +1,22 @@
const { withGradleProperties } = require("expo/config-plugins");
// The Expo template's 2GB heap is too small for D8 dex merging in this app,
// causing OutOfMemoryError in :app:mergeExtDexDebug.
const JVM_ARGS = "-Xmx4096m -XX:MaxMetaspaceSize=1024m";
module.exports = function withAndroidGradleHeap(config) {
return withGradleProperties(config, (nextConfig) => {
const properties = nextConfig.modResults.filter(
(item) => !(item.type === "property" && item.key === "org.gradle.jvmargs"),
);
properties.push({
type: "property",
key: "org.gradle.jvmargs",
value: JVM_ARGS,
});
nextConfig.modResults = properties;
return nextConfig;
});
};
@@ -0,0 +1,188 @@
const fs = require("node:fs");
const path = require("node:path");
const {
AndroidConfig,
withAndroidColors,
withAndroidColorsNight,
withAndroidStyles,
withDangerousMod,
} = require("expo/config-plugins");
// React Native's Alert renders an AppCompat AlertDialog on Android, which
// inherits the dated framework dialog chrome (square gray panel, teal
// all-caps buttons) from the app theme. These resources restyle it with the
// app's uniwind tokens from global.css: --color-card panel, --color-foreground
// text, --color-primary buttons, DM Sans type. The @font resources referenced
// here are embedded by the expo-font plugin config in app.config.ts.
// AppCompat's default dialog window background is an inset rounded rect, so
// the replacement keeps the same 16dp inset to preserve the dialog's margins.
const DIALOG_BACKGROUND_DRAWABLE = `<?xml version="1.0" encoding="utf-8"?>
<inset xmlns:android="http://schemas.android.com/apk/res/android"
android:insetLeft="16dp"
android:insetTop="16dp"
android:insetRight="16dp"
android:insetBottom="16dp">
<shape android:shape="rectangle">
<solid android:color="@color/alert_dialog_background" />
<corners android:radius="24dp" />
</shape>
</inset>
`;
const COLORS = {
light: {
background: "#FFFFFF", // --color-card
text: "#262626", // --color-foreground
secondaryText: "#525252", // --color-foreground-secondary
buttonText: "#262626", // --color-primary
},
night: {
background: "#171717",
text: "#F5F5F5",
secondaryText: "#A3A3A3",
buttonText: "#F5F5F5",
},
};
function assignStyleItem(style, name, value) {
style.item = style.item ?? [];
const existing = style.item.find((item) => item.$?.name === name);
if (existing) {
existing._ = value;
} else {
style.item.push({ _: value, $: { name } });
}
}
function withAlertDialogStyles(config) {
return withAndroidStyles(config, (config) => {
const resources = config.modResults.resources;
resources.style = resources.style ?? [];
const appTheme = resources.style.find((style) => style.$?.name === "AppTheme");
if (appTheme) {
// React Native's dialog module builds an androidx.appcompat AlertDialog,
// which resolves its theme from the AppCompat attr; the framework attr is
// set too for any native code that inflates a platform AlertDialog.
assignStyleItem(appTheme, "alertDialogTheme", "@style/AppAlertDialog");
assignStyleItem(appTheme, "android:alertDialogTheme", "@style/AppAlertDialog");
}
resources.style = resources.style.filter(
(style) =>
!["AppAlertDialog", "AppAlertDialog.Title", "AppAlertDialog.Button"].includes(
style.$?.name,
),
);
resources.style.push(
{
$: { name: "AppAlertDialog", parent: "ThemeOverlay.AppCompat.Dialog.Alert" },
item: [
{ _: "@drawable/alert_dialog_background", $: { name: "android:windowBackground" } },
// The message body resolves textColorPrimary in AppCompat's alert
// layout; pointing it at the secondary token dims the message
// relative to the title, which keeps full-strength text via the
// explicit color in AppAlertDialog.Title.
{ _: "@color/alert_dialog_secondary_text", $: { name: "android:textColorPrimary" } },
{ _: "@color/alert_dialog_secondary_text", $: { name: "android:textColorSecondary" } },
// Theme-level fontFamily is the lowest-priority fallback in attribute
// resolution, so it reaches every text view in the dialog that does
// not carry its own fontFamily (the message body in particular).
{ _: "@font/xml_dm_sans_regular", $: { name: "android:fontFamily" } },
// AppCompat's alert title view styles itself from the framework
// attr (?android:attr/windowTitleStyle); there is no unprefixed
// AppCompat equivalent.
{ _: "@style/AppAlertDialog.Title", $: { name: "android:windowTitleStyle" } },
{ _: "@style/AppAlertDialog.Button", $: { name: "buttonBarPositiveButtonStyle" } },
{ _: "@style/AppAlertDialog.Button", $: { name: "buttonBarNegativeButtonStyle" } },
{ _: "@style/AppAlertDialog.Button", $: { name: "buttonBarNeutralButtonStyle" } },
],
},
{
$: { name: "AppAlertDialog.Title", parent: "RtlOverlay.DialogWindowTitle.AppCompat" },
item: [
{ _: "@font/dm_sans_500medium", $: { name: "android:fontFamily" } },
{ _: "18sp", $: { name: "android:textSize" } },
{ _: "@color/alert_dialog_text", $: { name: "android:textColor" } },
],
},
{
$: {
name: "AppAlertDialog.Button",
parent: "Widget.AppCompat.Button.ButtonBar.AlertDialog",
},
item: [
// The AppCompat button appearance hardcodes sans-serif-medium, so
// the font must be set here rather than relying on the theme
// fallback.
{ _: "@font/dm_sans_500medium", $: { name: "android:fontFamily" } },
{ _: "@color/alert_dialog_button_text", $: { name: "android:textColor" } },
{ _: "false", $: { name: "android:textAllCaps" } },
{ _: "0", $: { name: "android:letterSpacing" } },
],
},
);
return config;
});
}
function assignColors(colorsResource, palette) {
let result = colorsResource;
result = AndroidConfig.Colors.assignColorValue(result, {
name: "alert_dialog_background",
value: palette.background,
});
result = AndroidConfig.Colors.assignColorValue(result, {
name: "alert_dialog_text",
value: palette.text,
});
result = AndroidConfig.Colors.assignColorValue(result, {
name: "alert_dialog_secondary_text",
value: palette.secondaryText,
});
result = AndroidConfig.Colors.assignColorValue(result, {
name: "alert_dialog_button_text",
value: palette.buttonText,
});
return result;
}
function withAlertDialogColors(config) {
config = withAndroidColors(config, (config) => {
config.modResults = assignColors(config.modResults, COLORS.light);
return config;
});
config = withAndroidColorsNight(config, (config) => {
config.modResults = assignColors(config.modResults, COLORS.night);
return config;
});
return config;
}
function withAlertDialogBackgroundDrawable(config) {
return withDangerousMod(config, [
"android",
async (config) => {
const drawableDir = path.join(
config.modRequest.platformProjectRoot,
"app",
"src",
"main",
"res",
"drawable",
);
fs.mkdirSync(drawableDir, { recursive: true });
fs.writeFileSync(
path.join(drawableDir, "alert_dialog_background.xml"),
DIALOG_BACKGROUND_DRAWABLE,
);
return config;
},
]);
}
module.exports = function withAndroidModernAlertDialog(config) {
return withAlertDialogBackgroundDrawable(withAlertDialogColors(withAlertDialogStyles(config)));
};
@@ -0,0 +1,250 @@
const fs = require("node:fs");
const path = require("node:path");
const {
AndroidConfig,
withAndroidColors,
withAndroidColorsNight,
withAndroidStyles,
withDangerousMod,
} = require("expo/config-plugins");
// @react-native-menu/menu renders an AppCompat PopupMenu on Android, which
// inherits the dated default popup chrome from the app theme. These resources
// restyle it to match the app palette (global.css --color-card / --color-foreground)
// with rounded corners, and anchor it below the button instead of overlapping it.
const POPUP_BACKGROUND_DRAWABLE = `<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<solid android:color="@color/popup_menu_background" />
<corners android:radius="12dp" />
</shape>
`;
// Checkable menu rows insert a CheckBox at the row's right edge; the theme
// swaps its square-box button for this check glyph so the selected option
// shows a plain right-aligned check.
const CHECK_DRAWABLE = `<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="18dp"
android:height="18dp"
android:viewportWidth="24"
android:viewportHeight="24"
android:tint="@color/popup_menu_item_text">
<path
android:fillColor="#FFFFFFFF"
android:pathData="M9,16.17L4.83,12l-1.42,1.41L9,19 21,7l-1.41,-1.41z" />
</vector>
`;
// CheckBox button drawable: check glyph when selected, nothing otherwise.
const CHECKBOX_BUTTON_SELECTOR = `<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true" android:drawable="@drawable/ic_menu_check" />
<item android:drawable="@android:color/transparent" />
</selector>
`;
// Replaces the default filled-triangle submenu indicator with a stroked ">"
// chevron.
const SUBMENU_ARROW_DRAWABLE = `<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="20dp"
android:height="20dp"
android:viewportWidth="24"
android:viewportHeight="24"
android:alpha="0.6"
android:tint="@color/popup_menu_item_text">
<path
android:pathData="M9,6l6,6l-6,6"
android:strokeColor="#FFFFFFFF"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round"
android:fillColor="#00000000" />
</vector>
`;
const COLORS = {
light: { background: "#F7F7F7", itemText: "#262626" },
night: { background: "#161616", itemText: "#F5F5F5" },
};
function assignStyleItem(style, name, value) {
style.item = style.item ?? [];
const existing = style.item.find((item) => item.$?.name === name);
if (existing) {
existing._ = value;
} else {
style.item.push({ _: value, $: { name } });
}
}
function withPopupMenuStyles(config) {
return withAndroidStyles(config, (config) => {
const resources = config.modResults.resources;
resources.style = resources.style ?? [];
const appTheme = resources.style.find((style) => style.$?.name === "AppTheme");
if (appTheme) {
assignStyleItem(appTheme, "popupMenuStyle", "@style/AppPopupMenu");
assignStyleItem(appTheme, "android:popupMenuStyle", "@style/AppPopupMenu");
assignStyleItem(
appTheme,
"textAppearanceLargePopupMenu",
"@style/AppPopupMenu.TextAppearance",
);
assignStyleItem(
appTheme,
"textAppearanceSmallPopupMenu",
"@style/AppPopupMenu.TextAppearance",
);
// Submenu popups show their parent item as a header row that reads a
// separate theme attribute, so it needs the same themed text color.
assignStyleItem(
appTheme,
"textAppearancePopupMenuHeader",
"@style/AppPopupMenu.HeaderTextAppearance",
);
// Menu item views resolve their submenu arrow from this style
// (android:listMenuViewStyle / android:subMenuArrow are public attrs).
assignStyleItem(appTheme, "android:listMenuViewStyle", "@style/AppPopupMenuListMenuView");
// Checkable rows inflate a plain CheckBox at the row end; restyle its
// button so the selected option shows a right-aligned check glyph
// instead of a square box. Both framework and AppCompat attrs are set
// since the popup may inflate either CheckBox flavor. App-wide for
// native checkboxes, which the app otherwise doesn't use.
assignStyleItem(appTheme, "android:checkboxStyle", "@style/AppPopupMenuCheckBox");
assignStyleItem(appTheme, "checkboxStyle", "@style/AppPopupMenuCheckBoxCompat");
}
resources.style = resources.style.filter(
(style) =>
![
"AppPopupMenu",
"AppPopupMenu.TextAppearance",
"AppPopupMenu.HeaderTextAppearance",
"AppPopupMenuListMenuView",
"AppPopupMenuCheckBox",
"AppPopupMenuCheckBoxCompat",
].includes(style.$?.name),
);
resources.style.push(
{
$: { name: "AppPopupMenu", parent: "Widget.AppCompat.PopupMenu" },
item: [
{ _: "@drawable/popup_menu_background", $: { name: "android:popupBackground" } },
{ _: "false", $: { name: "android:overlapAnchor" } },
{ _: "4dp", $: { name: "android:dropDownVerticalOffset" } },
],
},
{
$: { name: "AppPopupMenu.TextAppearance", parent: "TextAppearance.AppCompat.Menu" },
item: [
{ _: "15sp", $: { name: "android:textSize" } },
{ _: "@color/popup_menu_item_text", $: { name: "android:textColor" } },
// DM Sans (--font-sans); embedded by the expo-font plugin config in
// app.config.ts.
{ _: "@font/xml_dm_sans_regular", $: { name: "android:fontFamily" } },
],
},
{
$: {
name: "AppPopupMenu.HeaderTextAppearance",
parent: "TextAppearance.AppCompat.Widget.PopupMenu.Header",
},
item: [
{ _: "15sp", $: { name: "android:textSize" } },
{ _: "@color/popup_menu_item_text", $: { name: "android:textColor" } },
{ _: "@font/xml_dm_sans_regular", $: { name: "android:fontFamily" } },
],
},
// The framework default (Widget.Material.ListMenuView) only carries
// subMenuArrow, so replacing the style wholesale is safe.
{
$: { name: "AppPopupMenuListMenuView" },
item: [{ _: "@drawable/popup_menu_submenu_arrow", $: { name: "android:subMenuArrow" } }],
},
{
$: {
name: "AppPopupMenuCheckBox",
parent: "android:Widget.Material.CompoundButton.CheckBox",
},
item: [{ _: "@drawable/popup_menu_check_button", $: { name: "android:button" } }],
},
{
$: {
name: "AppPopupMenuCheckBoxCompat",
parent: "Widget.AppCompat.CompoundButton.CheckBox",
},
item: [
{ _: "@drawable/popup_menu_check_button", $: { name: "android:button" } },
// buttonCompat wins over android:button in AppCompatCheckBox.
{ _: "@drawable/popup_menu_check_button", $: { name: "buttonCompat" } },
],
},
);
return config;
});
}
function withPopupMenuColors(config) {
config = withAndroidColors(config, (config) => {
config.modResults = AndroidConfig.Colors.assignColorValue(config.modResults, {
name: "popup_menu_background",
value: COLORS.light.background,
});
config.modResults = AndroidConfig.Colors.assignColorValue(config.modResults, {
name: "popup_menu_item_text",
value: COLORS.light.itemText,
});
return config;
});
config = withAndroidColorsNight(config, (config) => {
config.modResults = AndroidConfig.Colors.assignColorValue(config.modResults, {
name: "popup_menu_background",
value: COLORS.night.background,
});
config.modResults = AndroidConfig.Colors.assignColorValue(config.modResults, {
name: "popup_menu_item_text",
value: COLORS.night.itemText,
});
return config;
});
return config;
}
function withPopupMenuBackgroundDrawable(config) {
return withDangerousMod(config, [
"android",
async (config) => {
const drawableDir = path.join(
config.modRequest.platformProjectRoot,
"app",
"src",
"main",
"res",
"drawable",
);
fs.mkdirSync(drawableDir, { recursive: true });
fs.writeFileSync(
path.join(drawableDir, "popup_menu_background.xml"),
POPUP_BACKGROUND_DRAWABLE,
);
fs.writeFileSync(path.join(drawableDir, "ic_menu_check.xml"), CHECK_DRAWABLE);
fs.writeFileSync(
path.join(drawableDir, "popup_menu_check_button.xml"),
CHECKBOX_BUTTON_SELECTOR,
);
fs.writeFileSync(
path.join(drawableDir, "popup_menu_submenu_arrow.xml"),
SUBMENU_ARROW_DRAWABLE,
);
return config;
},
]);
}
module.exports = function withAndroidModernPopupMenu(config) {
return withPopupMenuBackgroundDrawable(withPopupMenuColors(withPopupMenuStyles(config)));
};
@@ -0,0 +1,104 @@
const { withMainActivity } = require("expo/config-plugins");
// predictiveBackGestureEnabled writes android:enableOnBackInvokedCallback="true",
// which retires the legacy KEYCODE_BACK/onBackPressed() delivery on Android 13+.
// From then on back gestures only reach the app through OnBackPressedDispatcher
// callbacks. react-native 0.85 registers its own always-enabled callback, but
// only on Android 16 with targetSdk 36 (ReactActivity's enforced-predictive-back
// workaround) — on Android 13-15 nothing is registered, the system consumes
// every back gesture itself, and JS back handling (React Navigation pops,
// BackHandler listeners) silently dies: each gesture just backgrounds the app.
// This plugin mirrors react-native's shim on API 33-35 so back keeps flowing
// to JS there. See https://github.com/software-mansion/react-native-screens/discussions/2540.
const CALLBACK_PROPERTY = `
// Routes predictive-back gestures to JS on Android 13-15, where react-native
// registers no OnBackPressedDispatcher callback of its own (it only does on
// Android 16+). Registered in onCreate; added by withAndroidPredictiveBackCompat.
private val predictiveBackCompatCallback = object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
isEnabled = false
onBackPressed()
isEnabled = true
}
}
`;
const CALLBACK_REGISTRATION = `
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU && Build.VERSION.SDK_INT < Build.VERSION_CODES.BAKLAVA) {
onBackPressedDispatcher.addCallback(this, predictiveBackCompatCallback)
}`;
// Wraps the template's invokeDefaultOnBackPressed: the default action ends in
// ComponentActivity.onBackPressed(), which re-enters the dispatcher — with the
// compat callback still enabled that would bounce back into JS forever instead
// of backgrounding the app.
const INVOKE_DEFAULT_WRAPPER = `override fun invokeDefaultOnBackPressed() {
predictiveBackCompatCallback.isEnabled = false
try {
invokeDefaultOnBackPressedLegacy()
} finally {
predictiveBackCompatCallback.isEnabled = true
}
}
private fun invokeDefaultOnBackPressedLegacy() {`;
function insertAfter(contents, anchor, insertion, description) {
const index = contents.indexOf(anchor);
if (index === -1) {
throw new Error(
`withAndroidPredictiveBackCompat: could not find ${description} in MainActivity — the Expo template changed; update the plugin anchors.`,
);
}
const end = index + anchor.length;
return contents.slice(0, end) + insertion + contents.slice(end);
}
module.exports = function withAndroidPredictiveBackCompat(config) {
if (config.android?.predictiveBackGestureEnabled !== true) {
return config;
}
return withMainActivity(config, (nextConfig) => {
let contents = nextConfig.modResults.contents;
if (nextConfig.modResults.language !== "kt") {
throw new Error("withAndroidPredictiveBackCompat: MainActivity must be Kotlin.");
}
if (contents.includes("predictiveBackCompatCallback")) {
return nextConfig;
}
contents = insertAfter(
contents,
"import android.os.Bundle",
"\nimport androidx.activity.OnBackPressedCallback",
"the android.os.Bundle import",
);
contents = insertAfter(
contents,
"class MainActivity : ReactActivity() {",
CALLBACK_PROPERTY,
"the MainActivity class declaration",
);
contents = insertAfter(
contents,
"super.onCreate(null)",
CALLBACK_REGISTRATION,
"the super.onCreate call",
);
if (!contents.includes("override fun invokeDefaultOnBackPressed() {")) {
throw new Error(
"withAndroidPredictiveBackCompat: could not find invokeDefaultOnBackPressed in MainActivity — the Expo template changed; update the plugin anchors.",
);
}
contents = contents.replace(
"override fun invokeDefaultOnBackPressed() {",
INVOKE_DEFAULT_WRAPPER,
);
nextConfig.modResults.contents = contents;
return nextConfig;
});
};
@@ -0,0 +1,10 @@
const { withEntitlementsPlist } = require("expo/config-plugins");
module.exports = function withoutIosPersonalTeamCapabilities(config) {
return withEntitlementsPlist(config, (modConfig) => {
delete modConfig.modResults["aps-environment"];
delete modConfig.modResults["com.apple.developer.applesignin"];
delete modConfig.modResults["com.apple.security.application-groups"];
return modConfig;
});
};
+24 -19
View File
@@ -1,11 +1,7 @@
import {
DMSans_400Regular,
DMSans_500Medium,
DMSans_700Bold,
useFonts,
} from "@expo-google-fonts/dm-sans";
import { BlurTargetView } from "expo-blur";
import * as Linking from "expo-linking";
import * as SplashScreen from "expo-splash-screen";
import { useEffect } from "react";
import { StatusBar, useColorScheme } from "react-native";
import { GestureHandlerRootView } from "react-native-gesture-handler";
import { KeyboardProvider } from "react-native-keyboard-controller";
@@ -13,39 +9,41 @@ import { SafeAreaProvider } from "react-native-safe-area-context";
import { createStaticNavigation, DarkTheme, DefaultTheme } from "@react-navigation/native";
import { RegistryContext } from "@effect/atom-react";
import { useEffect } from "react";
import { ConfirmDialogHost } from "./components/ConfirmDialogHost";
import { CloudAuthProvider } from "./features/cloud/CloudAuthProvider";
import { AppearancePreferencesProvider } from "./features/settings/appearance/AppearancePreferencesProvider";
import { RootStack } from "./Stack";
import { appAtomRegistry } from "./state/atom-registry";
import { OverlayPortalHost } from "./components/OverlayPortal";
import { appBlurTargetRef } from "./lib/appBlurTarget";
import { useThemeColor } from "./lib/useThemeColor";
import "../global.css";
const appLinking = {
prefixes: [Linking.createURL("/"), "t3code://", "t3code-dev://", "t3code-preview://"],
// The Expo dev client launches the app via
// <scheme>://expo-development-client/?url=<packager> — that URL addresses
// the launcher, not app navigation. Without this filter it falls through
// to the NotFound wildcard route on every dev launch.
filter: (url: string) => !url.includes("expo-development-client"),
};
const Navigation = createStaticNavigation(RootStack);
export default function App() {
const [fontsLoaded] = useFonts({
DMSans_400Regular,
DMSans_500Medium,
DMSans_700Bold,
});
const colorScheme = useColorScheme();
const statusBarBg = useThemeColor("--color-status-bar");
useEffect(() => {
if (fontsLoaded) SplashScreen.hide();
}, [fontsLoaded]);
SplashScreen.hide();
}, []);
return (
<RegistryContext.Provider value={appAtomRegistry}>
<CloudAuthProvider>
<AppearancePreferencesProvider>
<GestureHandlerRootView style={{ flex: 1 }}>
<GestureHandlerRootView className="flex-1">
<KeyboardProvider statusBarTranslucent>
<SafeAreaProvider>
<StatusBar
@@ -58,10 +56,17 @@ export default function App() {
this, React Navigation defaults to its light theme and every native
header (glass buttons, title, materials) is forced light even when
the system is in dark mode. */}
<Navigation
linking={appLinking}
theme={colorScheme === "dark" ? DarkTheme : DefaultTheme}
/>
{/* Blur target for Android dropdown backdrops — see appBlurTarget.ts. */}
<BlurTargetView ref={appBlurTargetRef} style={{ flex: 1 }}>
<Navigation
linking={appLinking}
theme={colorScheme === "dark" ? DarkTheme : DefaultTheme}
/>
<ConfirmDialogHost />
</BlurTargetView>
{/* Anchored-menu overlays render here — in-window, so the
keyboard stays up while a dropdown is open. */}
<OverlayPortalHost />
</SafeAreaProvider>
</KeyboardProvider>
</GestureHandlerRootView>
+68 -15
View File
@@ -41,10 +41,17 @@ import { NewTaskDraftRouteScreen } from "./features/threads/NewTaskDraftRouteScr
import { NewTaskFlowProvider } from "./features/threads/new-task-flow-provider";
import { NewTaskRouteScreen } from "./features/threads/NewTaskRouteScreen";
import { SettingsAppearanceRouteScreen } from "./features/settings/SettingsAppearanceRouteScreen";
import { SettingsClientStorageRouteScreen } from "./features/settings/SettingsClientStorageRouteScreen";
import { SettingsAuthRouteScreen } from "./features/settings/SettingsAuthRouteScreen";
import { SettingsEnvironmentsRouteScreen } from "./features/settings/SettingsEnvironmentsRouteScreen";
import { SettingsLegalRouteScreen } from "./features/settings/SettingsLegalRouteScreen";
import { SettingsRouteScreen } from "./features/settings/SettingsRouteScreen";
import { SettingsWaitlistRouteScreen } from "./features/settings/SettingsWaitlistRouteScreen";
import {
SettingsLegalDocumentCloseHeaderButton,
SettingsLegalDocumentExternalHeaderButton,
} from "./features/settings/components/SettingsLegalDocumentRouteScreen";
import { useAppShortcuts } from "./features/shortcuts/useAppShortcuts";
import { nativeHeaderScrollEdgeEffects } from "./native/StackHeader";
import { useThreadOutboxDrain } from "./state/use-thread-outbox-drain";
@@ -104,6 +111,14 @@ const SHEET_SOLID_HEADER_OPTIONS: AppScreenOptions = {
unstable_navigationItemStyle: undefined,
};
const LEGAL_DOCUMENT_HEADER_OPTIONS: AppScreenOptions = {
...SHEET_SOLID_HEADER_OPTIONS,
headerBackVisible: false,
headerLeft: SettingsLegalDocumentCloseHeaderButton,
headerRight: () => <SettingsLegalDocumentExternalHeaderButton />,
presentation: "fullScreenModal",
};
const SettingsSheetStack = createNativeStackNavigator({
initialRouteName: "Settings",
screenOptions: {
@@ -147,6 +162,13 @@ const SettingsSheetStack = createNativeStackNavigator({
title: "Appearance",
},
}),
SettingsClientStorage: createNativeStackScreen({
screen: SettingsClientStorageRouteScreen,
linking: "client-storage",
options: {
title: "Client Storage",
},
}),
SettingsAuth: createNativeStackScreen({
screen: SettingsAuthRouteScreen,
linking: "auth",
@@ -230,6 +252,7 @@ const WORKSPACE_OVERLAY_ROUTES = new Set([
"GitConfirm",
"GitOverview",
"NewTaskSheet",
"SettingsLegal",
"SettingsSheet",
"ThreadReviewComment",
]);
@@ -256,6 +279,8 @@ function RootStackLayout(props: {
useThreadOutboxDrain();
// Presents the T3 Connect onboarding sheet after an in-session sign-in.
useConnectOnboardingNavigation();
// Launcher app shortcuts: routes shortcut taps and tracks opened threads.
useAppShortcuts(props.state);
// Full pathname (sheets included) for keyboard-command scoping; the
// workspace layout only reacts to the underlying non-overlay route.
const path = getPathFromState(props.state, navigationPathConfig);
@@ -348,9 +373,11 @@ export const RootStack = createNativeStackNavigator({
screen: ReviewCommentComposerSheet,
linking: `${THREAD_LINKING_PREFIX}/review-comment`,
options: {
presentation: "formSheet",
sheetAllowedDetents: [0.55, 0.92],
sheetGrabberVisible: true,
// Android cannot host the keyboard-driven comment composer inside a
// formSheet; use a full-screen modal there instead.
presentation: Platform.OS === "android" ? "fullScreenModal" : "formSheet",
sheetAllowedDetents: Platform.OS === "android" ? undefined : [0.55, 0.92],
sheetGrabberVisible: Platform.OS !== "android",
},
}),
ThreadFiles: createNativeStackScreen({
@@ -412,18 +439,32 @@ export const RootStack = createNativeStackNavigator({
options: {
gestureEnabled: true,
headerShown: false,
presentation: "formSheet",
sheetAllowedDetents: [0.7, 0.92],
sheetGrabberVisible: true,
// Android pushes settings as a regular full page with an in-screen
// back header; iOS keeps the detented form sheet.
...(Platform.OS === "android"
? { presentation: "card" as const }
: {
presentation: "formSheet" as const,
sheetAllowedDetents: [0.7, 0.92],
sheetGrabberVisible: true,
}),
},
}),
SettingsLegal: createNativeStackScreen({
screen: SettingsLegalRouteScreen,
linking: "settings/legal",
options: {
...LEGAL_DOCUMENT_HEADER_OPTIONS,
title: "Legal",
},
}),
ConnectOnboarding: createNativeStackScreen({
screen: ConnectOnboardingRouteScreen,
linking: "connect-onboarding",
options: {
// Root screenOptions hide headers; formSheets that want the native
// title bar opt back in with the sheet header preset.
...SHEET_SOLID_HEADER_OPTIONS,
// A root-level Android formSheet does not host the native stack bar;
// the route renders an embedded AndroidSheetHeader instead.
...(Platform.OS === "android" ? { headerShown: false } : SHEET_SOLID_HEADER_OPTIONS),
title: "Set up T3 Connect",
gestureEnabled: true,
presentation: "formSheet",
@@ -436,9 +477,15 @@ export const RootStack = createNativeStackNavigator({
linking: "connections",
options: {
title: "Environments",
presentation: "formSheet",
sheetAllowedDetents: [0.55, 0.7],
sheetGrabberVisible: true,
// Android: full page; the screen renders its own AndroidScreenHeader,
// so the native bar stays hidden. iOS keeps the sheet.
...(Platform.OS === "android"
? { presentation: "card" as const, headerShown: false }
: {
presentation: "formSheet" as const,
sheetAllowedDetents: [0.55, 0.7],
sheetGrabberVisible: true,
}),
},
}),
ConnectionsNew: createNativeStackScreen({
@@ -460,9 +507,15 @@ export const RootStack = createNativeStackNavigator({
options: {
gestureEnabled: true,
headerShown: false,
presentation: "formSheet",
sheetAllowedDetents: [0.92],
sheetGrabberVisible: true,
// Android pushes the flow as a regular full page — the draft should
// read like a thread that just doesn't exist yet; iOS keeps the sheet.
...(Platform.OS === "android"
? { presentation: "card" as const }
: {
presentation: "formSheet" as const,
sheetAllowedDetents: [0.92],
sheetGrabberVisible: true,
}),
},
}),
NotFound: createNativeStackScreen({
@@ -0,0 +1,337 @@
import type { MenuAction, MenuComponentProps } from "@react-native-menu/menu";
import { BlurView } from "expo-blur";
import type { ReactNode } from "react";
import { useCallback, useEffect, useRef, useState } from "react";
import type { StyleProp, ViewStyle } from "react-native";
import { BackHandler, Pressable, ScrollView, useColorScheme, View } from "react-native";
import { useKeyboardState } from "react-native-keyboard-controller";
import Animated, { FadeIn } from "react-native-reanimated";
import { appBlurTargetRef } from "../lib/appBlurTarget";
import { useThemeColor } from "../lib/useThemeColor";
import { cn } from "../lib/cn";
import { type AppSymbolName, SymbolView } from "./AppSymbol";
import { AppText as Text } from "./AppText";
import { OverlayPortal } from "./OverlayPortal";
const MENU_WIDTH = 250;
const SCREEN_MARGIN = 12;
const ANCHOR_GAP = 6;
// Anchor position is snapshotted in window coordinates when the menu opens;
// the overlay root measures itself the same way, and the menu is placed from
// the delta. Both snapshots are taken at open time so later reflows (keyboard
// show/hide, screen transitions) can't flip an opens-up menu to opens-down
// mid-presentation.
type AnchorSnapshot = {
readonly x: number;
readonly y: number;
readonly width: number;
readonly height: number;
};
type OverlayFrame = {
readonly x: number;
readonly y: number;
readonly width: number;
readonly height: number;
};
export type AndroidAnchoredMenuProps = {
readonly actions: readonly MenuAction[];
readonly title?: string;
readonly onPressAction?: MenuComponentProps["onPressAction"];
/** Applied to the anchor wrapper — call sites flex these to fill toolbars. */
readonly className?: string;
readonly style?: StyleProp<ViewStyle>;
/**
* Plain children open the menu on tap (the wrapper owns the press). A
* render function keeps the children interactive and hands them `open` to
* call from their own gesture — e.g. a row that selects on tap and opens
* this menu on long-press.
*/
readonly children: ReactNode | ((open: () => void) => ReactNode);
};
/**
* Token-styled anchored dropdown for Android, drop-in for the subset of the
* MenuView contract the app uses (actions with state/subtitle/image/
* attributes, one level of subactions). The native AppCompat PopupMenu caps
* out on theming — stock animation, item metrics, and submenu chrome — so
* ControlPillMenu renders this instead on Android while iOS keeps the native
* UIMenu. Styling follows the themed native popup (12dp radius, plain rows,
* trailing check glyph); submenus drill in under a muted parent-title header.
*/
export function AndroidAnchoredMenu(props: AndroidAnchoredMenuProps) {
const [anchor, setAnchor] = useState<AnchorSnapshot | null>(null);
const [path, setPath] = useState<readonly MenuAction[]>([]);
// Height of the modal's root view, in the modal's own coordinate space.
// Menus that flip above their anchor are pinned by their BOTTOM edge
// (bottom = rootHeight - anchorTop), so drill-in height changes grow
// upward without any re-measurement — positioning them via `top` from the
// menu's measured height made every submenu transition settle over two
// frames and jitter.
const [rootHeight, setRootHeight] = useState<number | null>(null);
// Window frame of the overlay root, measured on layout. Anchor coordinates
// are converted into this frame, so the menu lands correctly no matter
// where the portal host sits (status bar, keyboard resize, etc.).
const [overlay, setOverlay] = useState<OverlayFrame | null>(null);
const anchorRef = useRef<View>(null);
const overlayRef = useRef<View>(null);
const isDarkMode = useColorScheme() === "dark";
const keyboardVisible = useKeyboardState((state) => state.isVisible);
const keyboardHeight = useKeyboardState((state) => state.height);
const rippleColor = useThemeColor("--color-subtle");
const iconColor = useThemeColor("--color-icon");
const iconSubtleColor = useThemeColor("--color-icon-subtle");
const dangerColor = useThemeColor("--color-danger-foreground");
const close = useCallback(() => {
setAnchor(null);
setPath([]);
setOverlay(null);
setRootHeight(null);
}, []);
const open = useCallback(() => {
anchorRef.current?.measureInWindow((x, y, width, height) => {
setAnchor({ x, y, width, height });
});
}, []);
const measureOverlay = useCallback(() => {
overlayRef.current?.measureInWindow((x, y, width, height) => {
setOverlay({ x, y, width, height });
setRootHeight(height);
});
}, []);
// The dropdown renders in-window (no Modal takes focus), so the hardware
// back gesture needs explicit handling while it is open. Back steps out of
// a drilled-in submenu one level at a time (mirroring the tappable parent
// header) before closing the menu. Under predictive back
// (enableOnBackInvokedCallback) this stays correct: back reaches JS
// through always-registered OnBackPressedDispatcher callbacks (react-native
// core on Android 16+, withAndroidPredictiveBackCompat on 13-15), which
// also keeps the system from playing a "leave app" preview while the menu
// merely closes.
const submenuDepth = path.length;
useEffect(() => {
if (anchor === null) {
return;
}
const subscription = BackHandler.addEventListener("hardwareBackPress", () => {
if (submenuDepth > 0) {
setPath((current) => current.slice(0, -1));
} else {
close();
}
return true;
});
return () => subscription.remove();
}, [anchor, close, submenuDepth]);
const parent = path.length > 0 ? path[path.length - 1] : null;
const levelActions = (parent?.subactions ?? props.actions).filter(
(action) => !(action.attributes?.hidden ?? false),
);
// Anchor in overlay-local coordinates (both measured in window space).
const local =
anchor === null || overlay === null
? null
: {
x: anchor.x - overlay.x,
y: anchor.y - overlay.y,
width: anchor.width,
height: anchor.height,
};
const preferredLeft =
local === null || overlay === null
? 0
: local.x + local.width / 2 <= overlay.width / 2
? local.x
: local.x + local.width - MENU_WIDTH;
const left =
overlay === null
? 0
: Math.min(
Math.max(preferredLeft, SCREEN_MARGIN),
overlay.width - MENU_WIDTH - SCREEN_MARGIN,
);
// The keyboard stays up while the menu is open (in-window overlay, no
// focus change), so the space it covers is not usable — without this the
// composer-pill menus "open down" into the IME and can't be tapped.
const usableBottom =
overlay === null ? 0 : overlay.height - (keyboardVisible ? keyboardHeight : 0);
const spaceBelow =
local === null || overlay === null
? 0
: usableBottom - (local.y + local.height) - ANCHOR_GAP - SCREEN_MARGIN;
const spaceAbove = local === null ? 0 : local.y - ANCHOR_GAP - SCREEN_MARGIN;
const opensDown = spaceBelow >= 280 || spaceBelow >= spaceAbove;
const maxHeight = Math.min(opensDown ? spaceBelow : spaceAbove, 480);
// The menu needs the overlay frame before it can be placed; it stays
// unmounted for that first frame so the fade-in plays at the final position.
const placeable = local !== null && rootHeight !== null;
const onPressItem = useCallback(
(action: MenuAction) => {
if ((action.subactions?.length ?? 0) > 0) {
setPath((current) => [...current, action]);
return;
}
close();
if (action.id !== undefined) {
props.onPressAction?.({
nativeEvent: { event: action.id },
} as Parameters<NonNullable<MenuComponentProps["onPressAction"]>>[0]);
}
},
[close, props.onPressAction],
);
return (
<>
{typeof props.children === "function" ? (
<View ref={anchorRef} collapsable={false} className={props.className} style={props.style}>
{props.children(open)}
</View>
) : (
<Pressable
ref={anchorRef}
accessibilityRole="button"
className={props.className}
collapsable={false}
style={props.style}
onPress={open}
>
<View pointerEvents="none">{props.children}</View>
</Pressable>
)}
{anchor === null ? null : (
<OverlayPortal>
<View
ref={overlayRef}
collapsable={false}
className="absolute inset-0"
onLayout={measureOverlay}
>
<Pressable accessible={false} className="absolute inset-0" onPress={close} />
{!placeable || local === null ? null : (
<Animated.View
entering={FadeIn.duration(120)}
className="absolute w-[250px] overflow-hidden rounded-[12px] border border-border shadow-2xl"
style={{
left,
maxHeight,
...(opensDown
? { top: local.y + local.height + ANCHOR_GAP }
: { bottom: (rootHeight ?? 0) - local.y + ANCHOR_GAP }),
}}
>
{/* Frosted backdrop: blur of the app content behind the menu,
washed with the translucent card tone so rows keep contrast. */}
<BlurView
blurMethod="dimezisBlurView"
blurTarget={appBlurTargetRef}
intensity={40}
tint={isDarkMode ? "dark" : "light"}
className="absolute inset-0"
/>
<View className="absolute inset-0 bg-card-translucent" />
{/* keyboardShouldPersistTaps: the menu often opens over an
active editor; the first item tap must act, not just
dismiss the keyboard. */}
<ScrollView
bounces={false}
keyboardShouldPersistTaps="always"
showsVerticalScrollIndicator={false}
>
{parent !== null ? (
// Muted parent title as the submenu header; tapping it
// steps back, but it reads as a label, not a button.
<Pressable
className="px-3.5 pb-1 pt-2.5"
onPress={() => setPath((current) => current.slice(0, -1))}
>
<Text className="text-xs font-t3-bold text-foreground-muted">
{parent.title}
</Text>
</Pressable>
) : props.title ? (
<>
<View className="px-3.5 py-2">
<Text className="text-center text-xs text-foreground-muted">
{props.title}
</Text>
</View>
<View className="h-px bg-border" />
</>
) : null}
{levelActions.map((action, index) => {
const destructive = action.attributes?.destructive ?? false;
const disabled = action.attributes?.disabled ?? false;
const hasSubmenu = (action.subactions?.length ?? 0) > 0;
return (
<Pressable
key={action.id ?? `${index}-${action.title}`}
android_ripple={{ color: rippleColor }}
disabled={disabled}
className={cn(
"min-h-11 flex-row items-center gap-2.5 px-3.5 py-2.5",
disabled && "opacity-45",
)}
onPress={() => onPressItem(action)}
>
<View className="flex-1 gap-0.5">
<Text
className={cn(
// Same face as the pill labels that open these menus.
"text-sm font-t3-bold",
destructive && "text-danger-foreground",
)}
>
{action.title}
</Text>
{action.subtitle ? (
<Text className="text-xs leading-snug text-foreground-muted">
{action.subtitle}
</Text>
) : null}
</View>
{hasSubmenu ? (
<SymbolView
name="chevron.right"
size={13}
tintColor={iconSubtleColor}
type="monochrome"
/>
) : action.state === "on" ? (
<SymbolView
name="checkmark"
size={15}
tintColor={iconColor}
type="monochrome"
/>
) : action.image ? (
<SymbolView
name={action.image as AppSymbolName}
size={15}
tintColor={destructive ? dangerColor : iconColor}
type="monochrome"
/>
) : null}
</Pressable>
);
})}
</ScrollView>
</Animated.View>
)}
</View>
</OverlayPortal>
)}
</>
);
}
Loaded 100 of 295 files, more files were not shown because too many files have changed in this diff. Show more