Files
orca/src/main/ghostty/mapper.ts
T
f5ad7aa249 feat(settings): import Ghostty config with preview, color overrides, opacity and blur (#1001)
* feat(settings): add Ghostty config import

Add safe one-shot Ghostty import with preview and success summary,
and probe documented Ghostty config paths before applying changes.

Refs #958

* chore(git): ignore atl artifacts

* feat(settings): map font-weight, cursor-blink and focus-follows-mouse from Ghostty

Adds three safe direct-mapping Ghostty keys that have clear equivalents
in GlobalSettings: font-weight, cursor-style-blink, and focus-follows-mouse.

Refs #958

* feat(settings): expand Ghostty import to support colors, opacity and option-as-alt

- Add TerminalColorOverrides type grouping 21 optional xterm ITheme fields
- Add terminalBackgroundOpacity, terminalPanePaddingColor, terminalPaddingBalance
  to GlobalSettings
- Extend parser to collect repeated keys as string[] (needed for palette lines)
- Map background-opacity, background, foreground, cursor-color,
  selection-background/foreground, palette (0-15), window-padding-color,
  window-padding-balance, macos-option-as-alt in mapper
- Merge terminalColorOverrides into xterm ITheme at theme resolution; apply
  opacity as rgba() with allowTransparency enabled
- Accept hex colors with or without leading # (Ghostty omits it)
- Fix preview diff to use deep equality for object values so already-applied
  color overrides no longer reappear on next import

* feat(settings): support background-blur-radius and window-padding-color extend in Ghostty import

- Map background-blur-radius > 0 to windowBackgroundBlur: true; apply
  vibrancy on macOS and backgroundMaterial acrylic on Windows at window
  creation (blur requires restart — no hot-reload IPC exists)
- Accept window-padding-color = extend/background as valid Ghostty values;
  both map to default Orca padding behavior (undefined field) instead of
  landing in unsupportedKeys
- Split mapper.test.ts into domain-scoped describes to stay under 300-line limit

* feat(settings): add Window section to Terminal settings panel

Expose terminalBackgroundOpacity, windowBackgroundBlur, terminalPaddingBalance,
terminalPanePaddingColor, and terminalColorOverrides in the settings UI so
imported Ghostty values can be viewed and changed manually.

- New TerminalWindowSection component (extracted from TerminalPane to stay
  under the 400-line limit)
- Collapsible color overrides sub-section with ColorField for all 21 xterm
  ITheme fields grouped as base, ANSI normal, and ANSI bright
- Reset button clears all color overrides at once
- Window blur toggle shows restart-required note (blur applies at window
  creation, no hot-reload IPC exists)
- Search entries added for all new controls

* feat(settings): expand Ghostty import with scrollback, padding, divider, cursor and word-chars keys

Map 9 additional Ghostty keys to Orca settings:

- split-divider-color → terminalDividerColorDark + terminalDividerColorLight
  (single value applies to both; Ghostty has no dark/light distinction)
- unfocused-split-opacity → terminalInactivePaneOpacity (direct float 0-1)
- scrollback-limit → terminalScrollbackLimit; applied to xterm scrollback option
- window-padding-x / window-padding-y → terminalPaddingX/Y; applied as CSS
  vars --pane-padding-x / --pane-padding-y in terminal.css
- cursor-text → terminalColorOverrides.cursorAccent (xterm ITheme field)
- bold-color → terminalColorOverrides.bold (persisted; xterm ITheme has no
  bold field yet — stored for future xterm upgrade)
- cursor-opacity → terminalCursorOpacity; blended into cursor rgba at theme
  resolution time
- selection-word-chars → terminalWordSeparator; applied to xterm wordSeparator
- mouse-hide-while-typing → terminalMouseHideWhileTyping field added; renderer
  application deferred (needs per-pane disposable + global mousemove listener)

* feat(settings): expose new Ghostty-imported settings in Terminal Settings UI

- Window section: scrollback limit, horizontal/vertical padding, hide mouse
  while typing toggle, cursor text and bold color in Color Overrides
- Cursor section: cursor opacity NumberField
- Advanced section: word separators text input
- Search entries added for all new controls
- terminalDividerColorDark/Light and terminalInactivePaneOpacity skipped —
  already present in Theme and Pane Styling sections respectively

* feat(terminal): implement mouse-hide-while-typing per pane

Register terminal.onData → cursor:none and mousemove → restore, scoped to
the pane container element. Uses the existing IDisposable per-pane pattern
(same as selectionDisposablesRef). Cleans up on pane close and effect teardown.

* refactor(settings): address ghostty import code review findings

- Centralize GhosttyImportPreview type in shared/types (remove duplicate from mapper)
- Fix parser to strip inline comments without breaking hex color values (#1a1a1a)
- Extract HEX_COLOR_RE to shared/color-validation to avoid duplication
- Remove redundant Number.isNaN checks after Number.isFinite (4 sites)
- Replace unsafe catch-all assignment with explicit font-family branch
- Migrate 280-line if-chain in mapGhosttyToOrca to FIELD_PARSERS registry
- Add human-readable setting labels in GhosttyImportModal via setting-labels map
- Add clarifying comment in index.ts re JSON.stringify undefined behavior

* fix(settings): harden ghostty import from judgment-day review

- Surface readFile errors in GhosttyImportPreview.error instead of
  showing misleading 'No config found' on permission denied
- Guard handleApply against double-apply when already applied
- Strip surrounding quotes from parsed config values (font-family)
- Return null from palette handler when all entries fail validation
- Inform user when background-blur-radius radius is not preserved
- Add valuesEqual key-order stability via stableStringify
- Normalize hex colors to #-prefixed format across all color mappers
- Reject blank values before numeric parsing (Number('') === 0 trap)
- Remove selection-word-chars mapping (inverted xterm semantics)
- Guard window-padding-x/y against negative integers
- Reactive mouse-hide-while-typing on existing panes when setting toggles
- Merge terminalColorOverrides on import instead of replacing

* fix(ghostty): drop broken imports, tighten parsing, prompt restart for blur

Review found three high-impact issues in the Ghostty import: scrollback-limit
semantics are inverted/rescaled (Ghostty is bytes with 0=unlimited, xterm is
rows with 0=disabled), and window-padding-color + window-padding-balance set
CSS custom properties (--pane-padding-color, --pane-padding-balance) that
have no consuming rule anywhere in the tree — so users confirming "changes"
to those keys would see nothing happen.

Because none of the three keys have a safe mapping today, drop them from the
import and remove the dead UI controls + GlobalSettings fields + CSS var
plumbing. The mapper now lists them as unsupportedKeys alongside the
existing window-decoration / keybind / custom-shader entries.

Other fixes in the same review:

- allowTransparency now clears when background-opacity returns to 1 (prior
  code only ever set it to true, leaving a stale flag with measurable render
  cost).
- background-blur-radius = 0 no longer emits a misleading "radius value not
  preserved" note (0 cleanly maps to blur=false with no radius to lose).
- Add a 1 MB size cap on the config read so a pathological or symlinked file
  cannot OOM the main process.
- Make handleApply async and surface IPC errors inline in the modal instead
  of flipping straight to "Import complete" on failure.
- Type settings.previewGhosttyImport as Promise<GhosttyImportPreview> in
  preload so shape drift is caught at compile time.
- Make stableStringify recursive so future nested settings round-trip
  cleanly through valuesEqual.
- Restrict window-padding-x/y and background-blur-radius to decimal ints;
  prior code accepted exponent notation (1e10 sails through Number.isInteger)
  and would have landed absurd values in the store.
- Window blur now shows a "Restart required" banner with a Restart now
  button when the setting differs from the mount-time snapshot, mirroring
  the ExperimentalPane daemon pattern. Blur only applies at BrowserWindow
  creation on macOS/Windows.

Co-authored-by: Orca <help@stably.ai>

* feat(settings): move Ghostty import trigger to Terminal section header

Per review feedback: the "Import from Ghostty" row was taking its own slot
in the Terminal settings list alongside real configuration sections. Move
the trigger into the Terminal section's header (upper-right corner) as a
headerAction, next to the Terminal heading — it's a one-shot action, not a
setting.

- SettingsSection gains an optional `headerAction` slot rendered to the
  right of the section title/description.
- The useGhosttyImport hook is lifted from TerminalPane into Settings.tsx
  so the section header button (owned by Settings.tsx) and the modal
  (still rendered inside TerminalPane) share one state instance.
- TerminalPane drops its own "Import" section + the TERMINAL_GHOSTTY_IMPORT
  search entry group is no longer referenced there.
- Button carries the official Ghostty mark as a 16x16 icon so it reads
  clearly as a cross-app import even before users parse the label.

useGhosttyImport now accepts `GlobalSettings | null` so the parent can call
it above the pre-load spinner guard without violating hook ordering; the
apply path no-ops until settings arrive. Related test file updated to
pass the new `ghostty` prop and to assert the trigger is *not* rendered
inside TerminalPane anymore.

Co-authored-by: Orca <help@stably.ai>

---------

Co-authored-by: Neil <4138956+nwparker@users.noreply.github.com>
Co-authored-by: Orca <help@stably.ai>
2026-04-26 17:00:46 -07:00

329 lines
9.0 KiB
TypeScript

import type {
GlobalSettings,
TerminalColorOverrides,
GhosttyImportPreview
} from '../../shared/types'
import { HEX_COLOR_RE } from '../../shared/color-validation'
const PALETTE_INDEX_MAP: Record<number, keyof TerminalColorOverrides> = {
0: 'black',
1: 'red',
2: 'green',
3: 'yellow',
4: 'blue',
5: 'magenta',
6: 'cyan',
7: 'white',
8: 'brightBlack',
9: 'brightRed',
10: 'brightGreen',
11: 'brightYellow',
12: 'brightBlue',
13: 'brightMagenta',
14: 'brightCyan',
15: 'brightWhite'
}
type FieldAssignment = { key: keyof GlobalSettings; value: unknown }
type FieldResult =
| FieldAssignment
| FieldAssignment[]
| { colorOverrides: Partial<TerminalColorOverrides> }
| null
const normalizeHex = (v: string): string => (v.startsWith('#') ? v : `#${v}`)
// Why: `Number("1e10")` succeeds and passes `Number.isInteger`, so a Ghostty
// config with `window-padding-x = 1e9` would sail through the mapper and land
// an absurd value in the store. Restrict to plain decimal integers.
const STRICT_INT_RE = /^-?\d+$/
const parseStrictInt = (v: string): number | null => {
if (!STRICT_INT_RE.test(v)) {
return null
}
const num = Number(v)
return Number.isFinite(num) ? num : null
}
type FieldParser = (value: string, rawValue: string | string[]) => FieldResult
export function mapGhosttyToOrca(
parsed: Record<string, string | string[]>,
isMacOS = process.platform === 'darwin'
): {
diff: Partial<GlobalSettings>
unsupportedKeys: string[]
} {
const diff: Partial<GlobalSettings> = {}
const unsupportedKeys: string[] = []
const colorOverrides: TerminalColorOverrides = {}
const FIELD_PARSERS: Record<string, FieldParser> = {
'macos-option-as-alt': (v) => {
if (!isMacOS) {
return null
}
if (v === 'true' || v === 'on') {
return { key: 'terminalMacOptionAsAlt', value: 'true' }
}
if (v === 'false' || v === 'off') {
return { key: 'terminalMacOptionAsAlt', value: 'false' }
}
if (v === 'left' || v === 'right') {
return { key: 'terminalMacOptionAsAlt', value: v }
}
return null
},
'background-opacity': (v) => {
const num = Number(v)
if (!Number.isFinite(num) || num < 0 || num > 1) {
return null
}
return { key: 'terminalBackgroundOpacity', value: num }
},
background: (v) => {
if (!HEX_COLOR_RE.test(v)) {
return null
}
return { colorOverrides: { background: normalizeHex(v) } }
},
foreground: (v) => {
if (!HEX_COLOR_RE.test(v)) {
return null
}
return { colorOverrides: { foreground: normalizeHex(v) } }
},
'cursor-color': (v) => {
if (!HEX_COLOR_RE.test(v)) {
return null
}
return { colorOverrides: { cursor: normalizeHex(v) } }
},
'selection-background': (v) => {
if (!HEX_COLOR_RE.test(v)) {
return null
}
return { colorOverrides: { selectionBackground: normalizeHex(v) } }
},
'selection-foreground': (v) => {
if (!HEX_COLOR_RE.test(v)) {
return null
}
return { colorOverrides: { selectionForeground: normalizeHex(v) } }
},
palette: (_v, rawValue) => {
const entries = Array.isArray(rawValue) ? rawValue : [rawValue]
const overrides: Partial<TerminalColorOverrides> = {}
for (const entry of entries) {
const eqIdx = entry.indexOf('=')
if (eqIdx === -1) {
continue
}
const idxStr = entry.slice(0, eqIdx).trim()
const color = entry.slice(eqIdx + 1).trim()
const index = parseInt(idxStr, 10)
if (Number.isNaN(index) || !HEX_COLOR_RE.test(color)) {
continue
}
const mapped = PALETTE_INDEX_MAP[index]
if (mapped) {
overrides[mapped] = normalizeHex(color)
}
}
if (Object.keys(overrides).length === 0 && entries.length > 0) {
return null
}
return { colorOverrides: overrides }
},
'background-blur-radius': (v) => {
const num = parseStrictInt(v)
if (num === null || num < 0) {
return null
}
return { key: 'windowBackgroundBlur', value: num > 0 }
},
'split-divider-color': (v) => {
if (!HEX_COLOR_RE.test(v)) {
return null
}
return [
{ key: 'terminalDividerColorDark', value: normalizeHex(v) },
{ key: 'terminalDividerColorLight', value: normalizeHex(v) }
]
},
'unfocused-split-opacity': (v) => {
const num = Number(v)
if (!Number.isFinite(num) || num < 0 || num > 1) {
return null
}
return { key: 'terminalInactivePaneOpacity', value: num }
},
'window-padding-x': (v) => {
const num = parseStrictInt(v)
if (num === null || num < 0 || num > 512) {
return null
}
return { key: 'terminalPaddingX', value: num }
},
'window-padding-y': (v) => {
const num = parseStrictInt(v)
if (num === null || num < 0 || num > 512) {
return null
}
return { key: 'terminalPaddingY', value: num }
},
'cursor-text': (v) => {
if (!HEX_COLOR_RE.test(v)) {
return null
}
return { colorOverrides: { cursorAccent: normalizeHex(v) } }
},
'bold-color': (v) => {
if (!HEX_COLOR_RE.test(v)) {
return null
}
return { colorOverrides: { bold: normalizeHex(v) } }
},
'mouse-hide-while-typing': (v) => {
if (v !== 'true' && v !== 'false') {
return null
}
return { key: 'terminalMouseHideWhileTyping', value: v === 'true' }
},
'cursor-opacity': (v) => {
const num = Number(v)
if (!Number.isFinite(num) || num < 0 || num > 1) {
return null
}
return { key: 'terminalCursorOpacity', value: num }
},
'font-family': (v) => {
if (typeof v !== 'string' || v.trim().length === 0) {
return null
}
return { key: 'terminalFontFamily', value: v }
},
'font-size': (v) => {
const num = Number(v)
if (!Number.isFinite(num) || num <= 0) {
return null
}
return { key: 'terminalFontSize', value: num }
},
'font-weight': (v) => {
const num = Number(v)
if (!Number.isFinite(num) || num < 100 || num > 900) {
return null
}
return { key: 'terminalFontWeight', value: num }
},
'cursor-style': (v) => {
if (v !== 'bar' && v !== 'block' && v !== 'underline') {
return null
}
return { key: 'terminalCursorStyle', value: v }
},
'cursor-style-blink': (v) => {
// Why: Ghostty uses 'true'/'false' strings for booleans; anything else
// is treated as unsupported rather than silently coerced.
if (v !== 'true' && v !== 'false') {
return null
}
return { key: 'terminalCursorBlink', value: v === 'true' }
},
'focus-follows-mouse': (v) => {
// Why: Ghostty's focus-follows-mouse is semantically identical to Orca's
// terminalFocusFollowsMouse — both control pointer-hover focus transfer.
if (v !== 'true' && v !== 'false') {
return null
}
return { key: 'terminalFocusFollowsMouse', value: v === 'true' }
}
}
for (const [key, rawValue] of Object.entries(parsed)) {
const value = Array.isArray(rawValue) ? rawValue[0] : rawValue
// Why: Ghostty's selection-word-chars defines characters that ARE part of a
// word, while xterm.js wordSeparator defines characters that BREAK words.
// Passing the same string inverts the semantics, and correctly inverting a
// character set is non-trivial. Treat as unsupported to avoid silent misbehavior.
if (key === 'selection-word-chars') {
unsupportedKeys.push(key)
continue
}
if (!value.trim()) {
unsupportedKeys.push(key)
continue
}
const parser = FIELD_PARSERS[key]
if (!parser) {
unsupportedKeys.push(key)
continue
}
const result = parser(value, rawValue)
if (result === null) {
unsupportedKeys.push(key)
continue
}
// Why: Orca's windowBackgroundBlur is a boolean; the numeric radius is lost.
// Only note the drop when blur is actually being turned on — a `0` cleanly
// maps to `false` and there is no radius to lose.
if (
key === 'background-blur-radius' &&
!Array.isArray(result) &&
'key' in result &&
result.value === true
) {
unsupportedKeys.push('background-blur-radius (radius value not preserved)')
}
if (Array.isArray(result)) {
for (const entry of result) {
// Why: TypeScript's strict assignment checking for Partial<T>[K] requires
// a cast because GlobalSettings has no index signature.
diff[entry.key] = entry.value as never
}
} else if ('colorOverrides' in result) {
Object.assign(colorOverrides, result.colorOverrides)
} else {
diff[result.key] = result.value as never
}
}
if (Object.keys(colorOverrides).length > 0) {
diff.terminalColorOverrides = colorOverrides
}
return { diff, unsupportedKeys }
}
export type { GhosttyImportPreview }