Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions config/localization-coverage-allowlist.json
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,27 @@
"dynamic": false,
"count": 2
},
{
"filePath": "src/renderer/src/components/settings/terminal-advanced-platform-search.ts",
"kind": "object-property:keywords",
"text": "Kitty",
"dynamic": false,
"count": 1
},
{
"filePath": "src/renderer/src/components/settings/terminal-advanced-platform-search.ts",
"kind": "object-property:keywords",
"text": "kitty",
"dynamic": false,
"count": 1
},
{
"filePath": "src/renderer/src/components/settings/terminal-advanced-platform-search.ts",
"kind": "object-property:keywords",
"text": "kitty.conf",
"dynamic": false,
"count": 1
},
{
"filePath": "src/renderer/src/components/settings/terminal-pane-appearance-search.ts",
"kind": "object-property:keywords",
Expand Down
177 changes: 40 additions & 137 deletions src/main/ghostty/index.ts
Original file line number Diff line number Diff line change
@@ -1,53 +1,21 @@
import { readFile, stat } from 'node:fs/promises'
import { platform } from 'node:os'
import path from 'node:path'
import type { WebContents } from 'electron'
import type {
GhosttyImportPreview,
GhosttyImportSource,
GlobalSettings
} from '../../shared/global-settings-types'
import type { GlobalSettings } from '../../shared/global-settings-types'
import type { TerminalConfigImportPreview } from '../../shared/terminal-config-import-preview'
import type { Store } from '../persistence/loading-store/store'
import { translateMain } from '../i18n/main-i18n'
import { validateImportSource } from '../import-source-validation'
import { chooseTerminalConfigFile } from '../terminal-config-import/choose-config-file'
import { readConfigFile } from '../terminal-config-import/config-file-reader'
import {
previewTerminalConfigImport,
type TerminalConfigImporter,
type TerminalConfigMapping
} from '../terminal-config-import/preview'
import { findGhosttyConfigPaths } from './discovery'
import { parseGhosttyConfig } from './parser'
import { mapGhosttyToOrca } from './mapper'
import { importGhosttyTheme } from './theme-mapping'

// Bound config reads to avoid loading arbitrarily large files into main.
const MAX_CONFIG_BYTES = 1_000_000
const GHOSTTY_IMPORT_SOURCE_KINDS = ['auto', 'chooseFile'] as const

// Compare nested values structurally with sorted keys while preserving meaningful array order.
function stableStringify(v: unknown): string {
if (v === null || typeof v !== 'object') {
return JSON.stringify(v)
}
if (Array.isArray(v)) {
return `[${v.map(stableStringify).join(',')}]`
}
const entries = Object.entries(v as Record<string, unknown>).sort(([ka], [kb]) =>
ka.localeCompare(kb)
)
return `{${entries.map(([k, val]) => `${JSON.stringify(k)}:${stableStringify(val)}`).join(',')}}`
}

function valuesEqual(a: unknown, b: unknown): boolean {
if (a === b) {
return true
}
if (typeof a === 'object' && a !== null && typeof b === 'object' && b !== null) {
return stableStringify(a) === stableStringify(b)
}
return false
}

// An unset object setting already matches an import that clears it.
function emptyLike(value: unknown): unknown {
return typeof value === 'object' && value !== null && !Array.isArray(value) ? {} : undefined
}
type GhosttyConfig = Record<string, string | string[]>

function asArray(value: string | string[] | undefined): string[] {
if (value === undefined) {
Expand All @@ -72,7 +40,7 @@ function mergeParsedConfig(

type ThemeReferencePatch = {
diff: Partial<GlobalSettings>
themeNames?: GhosttyImportPreview['terminalThemes']
themeNames?: TerminalConfigImportPreview['terminalThemes']
unsupportedKeys: string[]
}

Expand Down Expand Up @@ -113,106 +81,41 @@ async function themeReferencePatch(
}
}

async function resolveConfigPaths(
source: GhosttyImportSource,
webContents?: WebContents
): Promise<string[] | null> {
switch (source.kind) {
case 'auto':
return findGhosttyConfigPaths()
case 'chooseFile': {
const picked = await chooseTerminalConfigFile(
translateMain('native.dialog.importGhosttyConfig', 'Import Ghostty Config'),
webContents
)
return picked === null ? null : [picked]
}
}
}

export async function previewGhosttyImport(
store: Store,
source: unknown = { kind: 'auto' },
webContents?: WebContents
): Promise<GhosttyImportPreview> {
const validatedSource = validateImportSource(source, GHOSTTY_IMPORT_SOURCE_KINDS)
if (!validatedSource) {
return { found: false, diff: {}, unsupportedKeys: [], error: 'Invalid Ghostty import source.' }
}
const configPaths = await resolveConfigPaths(validatedSource, webContents)
if (configPaths === null) {
return { found: false, canceled: true, diff: {}, unsupportedKeys: [] }
}
if (configPaths.length === 0) {
return { found: false, diff: {}, unsupportedKeys: [] }
}

const parsed: Record<string, string | string[]> = {}
const readPaths: string[] = []
let firstError: string | null = null
for (const configPath of configPaths) {
let content: string
try {
const info = await stat(configPath)
// Picked paths can be devices or FIFOs whose zero size would slip past the byte limit.
if (!info.isFile()) {
firstError ??= 'Config path is not a regular file.'
continue
}
if (info.size > MAX_CONFIG_BYTES) {
firstError ??= `Config file is too large to import (${info.size} bytes, limit ${MAX_CONFIG_BYTES}).`
const GHOSTTY_IMPORTER: TerminalConfigImporter<GhosttyConfig> = {
appName: 'Ghostty',
pickerTitle: () => translateMain('native.dialog.importGhosttyConfig', 'Import Ghostty Config'),
discover: findGhosttyConfigPaths,
load: async (configPaths) => {
const config: GhosttyConfig = {}
const readPaths: string[] = []
let firstError: string | null = null
for (const configPath of configPaths) {
const read = await readConfigFile(configPath)
if (!read.ok) {
firstError ??= read.error
continue
}
content = await readFile(configPath, 'utf-8')
} catch (err) {
const message = err instanceof Error ? err.message : 'Could not read config file'
firstError ??= `Could not read config: ${message}`
continue
mergeParsedConfig(config, parseGhosttyConfig(read.content))
readPaths.push(configPath)
}
mergeParsedConfig(parsed, parseGhosttyConfig(content))
readPaths.push(configPath)
}

if (readPaths.length === 0) {
return { config, readPaths, firstError }
},
map: async (config, { currentSettings, pickedConfigDir }): Promise<TerminalConfigMapping> => {
const { theme: rawTheme, ...configKeys } = config
const mapped = mapGhosttyToOrca(configKeys, platform() === 'darwin')
const theme = await themeReferencePatch(rawTheme, mapped.diff, pickedConfigDir, currentSettings)
return {
found: false,
diff: {},
unsupportedKeys: [],
error: firstError ?? 'Could not read config'
}
}

const { theme: rawTheme, ...configKeys } = parsed
const { diff: rawDiff, unsupportedKeys: mappedUnsupportedKeys } = mapGhosttyToOrca(
configKeys,
platform() === 'darwin'
)
const currentSettings = store.getSettings()
const theme = await themeReferencePatch(
rawTheme,
rawDiff,
validatedSource.kind === 'chooseFile' ? path.dirname(readPaths[0]) : undefined,
currentSettings
)
Object.assign(rawDiff, theme.diff)
const unsupportedKeys = [...mappedUnsupportedKeys, ...theme.unsupportedKeys]

const actualDiff: Partial<typeof rawDiff> = {}
for (const key of Object.keys(rawDiff) as (keyof typeof rawDiff)[]) {
const value = rawDiff[key]
if (value !== undefined && !valuesEqual(currentSettings[key] ?? emptyLike(value), value)) {
// Why: TypeScript's strict assignment checking for Partial<T>[K] requires
// a cast because GlobalSettings has no index signature.
;(actualDiff as Record<string, GlobalSettings[keyof GlobalSettings]>)[key] = value
diff: { ...mapped.diff, ...theme.diff },
unsupportedKeys: [...mapped.unsupportedKeys, ...theme.unsupportedKeys],
...(theme.themeNames ? { terminalThemes: theme.themeNames } : {})
}
}
}

return {
found: true,
configPath: readPaths[0],
configPaths: readPaths,
diff: actualDiff,
unsupportedKeys,
...(theme.themeNames ? { terminalThemes: theme.themeNames } : {})
}
export function previewGhosttyImport(
store: Store,
source?: unknown,
webContents?: WebContents
): Promise<TerminalConfigImportPreview> {
return previewTerminalConfigImport(GHOSTTY_IMPORTER, store, source, webContents)
}
4 changes: 1 addition & 3 deletions src/main/ghostty/mapper.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { GhosttyImportPreview, GlobalSettings } from '../../shared/global-settings-types'
import type { GlobalSettings } from '../../shared/global-settings-types'
import type { TerminalColorOverrides } from '../../shared/terminal-color-overrides'
import { HEX_COLOR_RE } from '../../shared/color-validation'
import { parsePaddingValue, parseStrictInt } from './numeric-config-values'
Expand Down Expand Up @@ -334,5 +334,3 @@ export function mapGhosttyToOrca(

return { diff, unsupportedKeys }
}

export type { GhosttyImportPreview }
18 changes: 18 additions & 0 deletions src/main/ipc/settings-import-handlers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { ipcMain } from 'electron'
import type { Store } from '../persistence/loading-store/store'
import { previewGhosttyImport } from '../ghostty/index'
import { previewKittyImport } from '../kitty'
import { previewWarpThemeImport } from '../warp-themes'

// Omitted sources fall back to each importer's auto-discovery default.
export function registerSettingsImportHandlers(store: Store): void {
ipcMain.handle('settings:previewGhosttyImport', (event, source?: unknown) =>
previewGhosttyImport(store, source, event.sender)
)
ipcMain.handle('settings:previewKittyImport', (event, source?: unknown) =>
previewKittyImport(store, source, event.sender)
)
ipcMain.handle('settings:previewWarpThemeImport', (event, source?: unknown) =>
previewWarpThemeImport(store, source, event.sender)
)
}
12 changes: 2 additions & 10 deletions src/main/ipc/settings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,7 @@ import type { Store } from '../persistence/loading-store/store'
import type { GlobalSettings } from '../../shared/global-settings-types'
import type { PersistedState } from '../../shared/persisted-state-types'
import { listSystemFontFamilies } from '../system-fonts'
import { previewGhosttyImport } from '../ghostty/index'
import { previewWarpThemeImport } from '../warp-themes'
import { registerSettingsImportHandlers } from './settings-import-handlers'
import { setMainUiLanguage } from '../i18n/main-i18n'
import { rebuildAppMenu } from '../menu/register-app-menu'
import { rebuildSystemTrayMenu } from '../tray/system-tray'
Expand Down Expand Up @@ -308,14 +307,7 @@ export function registerSettingsHandlers(

ipcMain.handle('settings:listFonts', () => listSystemFontFamilies())

// Omitted sources fall back to each importer's auto-discovery default.
ipcMain.handle('settings:previewGhosttyImport', (event, source?: unknown) =>
previewGhosttyImport(store, source, event.sender)
)

ipcMain.handle('settings:previewWarpThemeImport', (event, source?: unknown) =>
previewWarpThemeImport(store, source, event.sender)
)
registerSettingsImportHandlers(store)

ipcMain.handle('cache:getGitHub', () => {
return store.getGitHubCache()
Expand Down
47 changes: 47 additions & 0 deletions src/main/kitty/discovery.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { homedir, platform } from 'node:os'
import path from 'node:path'
import { constants } from 'node:fs'
import { access, stat } from 'node:fs/promises'

function expandHome(dir: string, home: string): string {
return dir === '~' || dir.startsWith('~/') ? path.join(home, dir.slice(1)) : dir
}

// Kitty's ConfigDirForName order; Kitty has no Windows build, so only an explicit directory applies there.
export function getKittyConfigPaths(): string[] {
const home = homedir()
const explicitDir = process.env.KITTY_CONFIG_DIRECTORY
if (explicitDir) {
return [path.join(expandHome(explicitDir, home), 'kitty.conf')]
}
const plat = platform()
if (plat === 'win32') {
return []
}
const roots = [
process.env.XDG_CONFIG_HOME,
...(process.env.XDG_CONFIG_DIRS ?? '').split(':'),
'~/.config',
...(plat === 'darwin' ? ['~/Library/Preferences'] : [])
]
const dirs = roots
.filter((root): root is string => Boolean(root))
.map((root) => path.posix.join(expandHome(root, home), 'kitty'))
return [...new Set(dirs)].map((dir) => path.posix.join(dir, 'kitty.conf'))
}
Comment on lines +11 to +31

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor · Functional Correctness · Quick win

Supported by static analysis

Web query:

Kitty terminal configuration file search order XDG_CONFIG_HOME XDG_CONFIG_DIRS ~/.config kitty.conf official documentation

Result:

Sources consulted:
- kitty.conf - kitty — https://sw.kovidgoyal.net/kitty/conf/
- The kitty command line interface - kitty — https://sw.kovidgoyal.net/kitty/invocation/
- kitty/docs/conf.rst at master · kovidgoyal/kitty · GitHub — https://github.com/kovidgoyal/kitty/blob/master/docs/conf.rst
- Selecting files, fast - kitty — https://sw.kovidgoyal.net/kitty/kittens/choose-files/
- Glossary - kitty — https://sw.kovidgoyal.net/kitty/glossary/
- …and 19 more

Script executed:

set -eu
printf '%s\n' '--- src/main/kitty/discovery.ts ---'
nl -ba src/main/kitty/discovery.ts | sed -n '1,110p'
printf '%s\n' '--- direct references ---'
rg -n -F --glob '*.ts' -e 'findKittyConfigPaths' -e 'getKittyConfigPaths' src/main src/shared src/renderer || test "$?" -eq 1
printf '%s\n' '--- automatic import caller ---'
nl -ba src/main/terminal-config-import/preview.ts | sed -n '45,95p'
printf '%s\n' '--- Kitty import entrypoint ---'
nl -ba src/main/kitty/index.ts | sed -n '1,60p'

Repository: stablyai/orca

Length of output: 5930


Preserve Kitty’s configuration precedence.

When both candidates exist, place ~/.config before XDG_CONFIG_DIRS. The current order can import a system configuration instead of the user configuration that Kitty selects.

Suggested fix
  const roots = [
    process.env.XDG_CONFIG_HOME,
-   ...(process.env.XDG_CONFIG_DIRS ?? '').split(':'),
    '~/.config',
+   ...(process.env.XDG_CONFIG_DIRS ?? '').split(':'),
    ...(plat === 'darwin' ? ['~/Library/Preferences'] : [])
  ]
Committable suggestion

IMPORTANT
Review the replacement and indentation, then test before committing.

Suggested change
export function getKittyConfigPaths(): string[] {
const home = homedir()
const explicitDir = process.env.KITTY_CONFIG_DIRECTORY
if (explicitDir) {
return [path.join(expandHome(explicitDir, home), 'kitty.conf')]
}
const plat = platform()
if (plat === 'win32') {
return []
}
const roots = [
process.env.XDG_CONFIG_HOME,
...(process.env.XDG_CONFIG_DIRS ?? '').split(':'),
'~/.config',
...(plat === 'darwin' ? ['~/Library/Preferences'] : [])
]
const dirs = roots
.filter((root): root is string => Boolean(root))
.map((root) => path.posix.join(expandHome(root, home), 'kitty'))
return [...new Set(dirs)].map((dir) => path.posix.join(dir, 'kitty.conf'))
}
export function getKittyConfigPaths(): string[] {
const home = homedir()
const explicitDir = process.env.KITTY_CONFIG_DIRECTORY
if (explicitDir) {
return [path.join(expandHome(explicitDir, home), 'kitty.conf')]
}
const plat = platform()
if (plat === 'win32') {
return []
}
const roots = [
process.env.XDG_CONFIG_HOME,
'~/.config',
...(process.env.XDG_CONFIG_DIRS ?? '').split(':'),
...(plat === 'darwin' ? ['~/Library/Preferences'] : [])
]
const dirs = roots
.filter((root): root is string => Boolean(root))
.map((root) => path.posix.join(expandHome(root, home), 'kitty'))
return [...new Set(dirs)].map((dir) => path.posix.join(dir, 'kitty.conf'))
}


/** Kitty reads a single kitty.conf: the first location that has one in a writable directory. */
export async function findKittyConfigPaths(): Promise<string[]> {
for (const configPath of getKittyConfigPaths()) {
try {
// The writability check keeps a read-only system default (e.g. /etc/xdg) from shadowing the user's config.
if ((await stat(configPath)).isFile()) {
await access(path.dirname(configPath), constants.W_OK)
return [configPath]
}
} catch {
// Unreadable candidates must not prevent probing the remaining locations.
}
}
return []
}
Comment on lines +33 to +47

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor · Functional Correctness · Quick win

Do not require write access to the Kitty config directory.

When the process can read kitty.conf but cannot write its parent directory, await access(path.dirname(configPath), constants.W_OK) skips the file. Automatic import then returns found: false, even though the importer only reads the config.

Suggested fix
-import { constants } from 'node:fs'
-import { access, stat } from 'node:fs/promises'
+import { stat } from 'node:fs/promises'

-/** Kitty reads a single kitty.conf: the first location that has one in a writable directory. */
+/** Kitty reads a single kitty.conf: the first location that has one. */
 export async function findKittyConfigPaths(): Promise<string[]> {
   for (const configPath of getKittyConfigPaths()) {
     try {
-      // The writability check keeps a read-only system default (e.g. /etc/xdg) from shadowing the user's config.
       if ((await stat(configPath)).isFile()) {
-        await access(path.dirname(configPath), constants.W_OK)
         return [configPath]
       }
Committable suggestion

IMPORTANT
Review the replacement and indentation, then test before committing.

Suggested change
/** Kitty reads a single kitty.conf: the first location that has one in a writable directory. */
export async function findKittyConfigPaths(): Promise<string[]> {
for (const configPath of getKittyConfigPaths()) {
try {
// The writability check keeps a read-only system default (e.g. /etc/xdg) from shadowing the user's config.
if ((await stat(configPath)).isFile()) {
await access(path.dirname(configPath), constants.W_OK)
return [configPath]
}
} catch {
// Unreadable candidates must not prevent probing the remaining locations.
}
}
return []
}
/** Kitty reads a single kitty.conf: the first location that has one. */
export async function findKittyConfigPaths(): Promise<string[]> {
for (const configPath of getKittyConfigPaths()) {
try {
if ((await stat(configPath)).isFile()) {
return [configPath]
}
} catch {
// Unreadable candidates must not prevent probing the remaining locations.
}
}
return []
}

29 changes: 29 additions & 0 deletions src/main/kitty/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { homedir, platform } from 'node:os'
import type { WebContents } from 'electron'
import type { TerminalConfigImportPreview } from '../../shared/terminal-config-import-preview'
import type { Store } from '../persistence/loading-store/store'
import { translateMain } from '../i18n/main-i18n'
import {
previewTerminalConfigImport,
type TerminalConfigImporter
} from '../terminal-config-import/preview'
import { findKittyConfigPaths } from './discovery'
import { mapKittyToOrca } from './mapper'
import { loadKittyConfig, type KittyConfig } from './parser'

const KITTY_IMPORTER: TerminalConfigImporter<KittyConfig> = {
appName: 'Kitty',
pickerTitle: () => translateMain('native.dialog.importKittyConfig', 'Import Kitty Config'),
discover: findKittyConfigPaths,
// Kitty reads one kitty.conf; anything else arrives through its include directives.
load: ([entryPath = '']) => loadKittyConfig(entryPath, homedir()),
map: async (config) => mapKittyToOrca(config, platform() === 'darwin')
}

export function previewKittyImport(
store: Store,
source?: unknown,
webContents?: WebContents
): Promise<TerminalConfigImportPreview> {
return previewTerminalConfigImport(KITTY_IMPORTER, store, source, webContents)
}
Loading
Loading