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
91 changes: 56 additions & 35 deletions src/main/ghostty/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
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,
Expand All @@ -13,7 +14,7 @@ import { chooseTerminalConfigFile } from '../terminal-config-import/choose-confi
import { findGhosttyConfigPaths } from './discovery'
import { parseGhosttyConfig } from './parser'
import { mapGhosttyToOrca } from './mapper'
import { resolveGhosttyThemeColors } from './theme-resolution'
import { importGhosttyTheme } from './theme-mapping'

// Bound config reads to avoid loading arbitrarily large files into main.
const MAX_CONFIG_BYTES = 1_000_000
Expand Down Expand Up @@ -43,6 +44,11 @@ function valuesEqual(a: unknown, b: unknown): boolean {
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
}

function asArray(value: string | string[] | undefined): string[] {
if (value === undefined) {
return []
Expand All @@ -64,39 +70,47 @@ function mergeParsedConfig(
}
}

function usesConditionalThemePair(themeName: string): boolean {
return themeName
.split(',')
.map((part) => part.trim())
.some((part) => part.startsWith('light:') || part.startsWith('dark:'))
type ThemeReferencePatch = {
diff: Partial<GlobalSettings>
themeNames?: GhosttyImportPreview['terminalThemes']
unsupportedKeys: string[]
}

// Theme colors are defaults; explicit config colors and palette entries take precedence.
async function applyThemeReference(parsed: Record<string, string | string[]>): Promise<string[]> {
const rawTheme = parsed['theme']
// A slot whose theme the import selects gets exactly the config's explicit colors; other slots keep merging them.
async function themeReferencePatch(
rawTheme: string | string[] | undefined,
explicit: Partial<GlobalSettings>,
pickedConfigDir: string | undefined,
currentSettings: GlobalSettings
): Promise<ThemeReferencePatch> {
if (rawTheme === undefined) {
return []
}
delete parsed['theme']

const themeName = (Array.isArray(rawTheme) ? (rawTheme.at(-1) ?? '') : rawTheme).trim()
if (usesConditionalThemePair(themeName)) {
return ['theme (light:/dark: pairs not supported)']
return { diff: {}, unsupportedKeys: [] }
}

const themeColors = await resolveGhosttyThemeColors(themeName)
if (themeColors === null) {
return ['theme (theme file not found)']
const { diff, themeNames, unsupportedKeys } = await importGhosttyTheme(
Array.isArray(rawTheme) ? (rawTheme.at(-1) ?? '') : rawTheme,
pickedConfigDir,
currentSettings.terminalCustomThemes
)
if (themeNames.dark === undefined && themeNames.light === undefined) {
return { diff: {}, unsupportedKeys }
}

for (const [key, value] of Object.entries(themeColors)) {
if (key === 'palette') {
parsed[key] = [...asArray(value), ...asArray(parsed[key])]
} else if (parsed[key] === undefined) {
parsed[key] = value
}
const colors = explicit.terminalColorOverrides ?? {}
// Explicit config keys (e.g. split-divider-color) override what the theme supplies, as in Ghostty.
const themeDefaults = Object.fromEntries(
Object.entries(diff).filter(([key]) => !Object.hasOwn(explicit, key))
)
return {
diff: {
...themeDefaults,
terminalColorOverrides:
themeNames.dark !== undefined
? colors
: { ...currentSettings.terminalColorOverrides, ...colors },
...(themeNames.light !== undefined ? { terminalColorOverridesLight: colors } : {})
},
themeNames,
unsupportedKeys
}
return []
}

async function resolveConfigPaths(
Expand Down Expand Up @@ -168,19 +182,25 @@ export async function previewGhosttyImport(
}
}

const themeUnsupportedKeys = await applyThemeReference(parsed)

const { theme: rawTheme, ...configKeys } = parsed
const { diff: rawDiff, unsupportedKeys: mappedUnsupportedKeys } = mapGhosttyToOrca(
parsed,
configKeys,
platform() === 'darwin'
)
const unsupportedKeys = [...mappedUnsupportedKeys, ...themeUnsupportedKeys]

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], value)) {
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
Expand All @@ -192,6 +212,7 @@ export async function previewGhosttyImport(
configPath: readPaths[0],
configPaths: readPaths,
diff: actualDiff,
unsupportedKeys
unsupportedKeys,
...(theme.themeNames ? { terminalThemes: theme.themeNames } : {})
}
}
161 changes: 97 additions & 64 deletions src/main/ghostty/theme-import.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,92 +47,125 @@ function createStore(settings: Record<string, unknown> = {}): Store {
} as Store
}

const CONFIG_PATH = '/Users/alice/Library/Application Support/com.mitchellh.ghostty/config'
const USER_THEMES = '/Users/alice/.config/ghostty/themes'

function mockFiles(files: Record<string, string>): void {
statMock.mockImplementation(async (p: string) => {
if (p in files) {
return { isFile: () => true, size: files[p].length }
}
throw Object.assign(new Error('ENOENT'), { code: 'ENOENT' })
})
readFileMock.mockImplementation(async (p: string) => files[p])
}

describe('previewGhosttyImport theme references', () => {
it('resolves a theme reference into color overrides', async () => {
const configPath = '/Users/alice/Library/Application Support/com.mitchellh.ghostty/config'
const themePath = '/Users/alice/.config/ghostty/themes/Tomorrow Night Bright'
statMock.mockImplementation(async (p: string) => {
if (p === configPath || p === themePath) {
return { isFile: () => true, size: 128 }
}
throw Object.assign(new Error('ENOENT'), { code: 'ENOENT' })
})
readFileMock.mockImplementation(async (p: string) => {
if (p === themePath) {
return 'palette = 1=#d54e53\nbackground = #000000\nforeground = #eaeaea\n'
}
return 'theme = Tomorrow Night Bright\nfont-size = 14\n'
it('imports a theme file as a custom theme and keeps explicit colors as overrides', async () => {
mockFiles({
[CONFIG_PATH]: 'theme = Tomorrow Night Bright\nbackground = #101010\nfont-size = 14\n',
[`${USER_THEMES}/Tomorrow Night Bright`]:
'palette = 1=#d54e53\nbackground = #000000\nforeground = #eaeaea\nfont-size = 30\n'
})

const result = await previewGhosttyImport(createStore())
const result = await previewGhosttyImport(
createStore({ terminalColorOverrides: { red: '#ff0000' } })
)

expect(result.diff).toEqual({
const [theme] = result.diff.terminalCustomThemes ?? []
expect(theme).toMatchObject({
id: 'ghostty:tomorrow-night-bright',
name: 'Tomorrow Night Bright',
source: 'ghostty',
mode: 'dark',
terminal: { red: '#d54e53', background: '#000000', foreground: '#eaeaea', cursor: '#eaeaea' }
})
expect(result.diff).toMatchObject({
terminalFontSize: 14,
terminalColorOverrides: {
red: '#d54e53',
background: '#000000',
foreground: '#eaeaea'
}
terminalThemeDark: 'custom:ghostty:tomorrow-night-bright',
terminalUseSeparateLightTheme: false,
// Overrides from an earlier import must not tint the newly selected theme.
terminalColorOverrides: { background: '#101010' }
})
expect(result.terminalThemes).toEqual({ dark: 'Tomorrow Night Bright' })
expect(result.unsupportedKeys).toEqual([])
})

it('lets explicit config colors override theme colors', async () => {
const configPath = '/Users/alice/Library/Application Support/com.mitchellh.ghostty/config'
const themePath = '/Users/alice/.config/ghostty/themes/night'
statMock.mockImplementation(async (p: string) => {
if (p === configPath || p === themePath) {
return { isFile: () => true, size: 128 }
}
throw Object.assign(new Error('ENOENT'), { code: 'ENOENT' })
it('maps a light/dark pair to both slots, falling back to Orca built-ins by name', async () => {
mockFiles({
[CONFIG_PATH]: 'theme = dark:night , light: catppuccin-latte.conf\npalette = 2=#00ff00\n',
[`${USER_THEMES}/night`]: 'background = #000000\nforeground = #ffffff\n'
})
readFileMock.mockImplementation(async (p: string) => {
if (p === themePath) {
return 'palette = 1=#d54e53\npalette = 2=#b9ca4a\nbackground = #000000\n'
}
return 'theme = night\nbackground = #101010\npalette = 1=#ff0000\n'

const result = await previewGhosttyImport(createStore())

expect(result.diff).toMatchObject({
terminalThemeDark: 'custom:ghostty:night',
terminalThemeLight: 'Catppuccin Latte',
terminalUseSeparateLightTheme: true,
terminalColorOverrides: { green: '#00ff00' },
terminalColorOverridesLight: { green: '#00ff00' }
})
expect(result.terminalThemes).toEqual({ dark: 'night', light: 'Catppuccin Latte' })
})

it('reports unresolved names and incomplete pairs without touching theme settings', async () => {
mockFiles({ [CONFIG_PATH]: 'theme = No Such Theme\n' })
const missing = await previewGhosttyImport(createStore())
expect(missing.diff).toEqual({})
expect(missing.terminalThemes).toBeUndefined()
expect(missing.unsupportedKeys).toEqual(['theme (No Such Theme: not found)'])

mockFiles({ [CONFIG_PATH]: 'theme = light:Catppuccin Latte\n' })
const half = await previewGhosttyImport(createStore())
expect(half.diff).toEqual({})
expect(half.unsupportedKeys).toEqual([
'theme (light:/dark: pairs need both a light and a dark theme)'
])
})

it('keeps same-named theme files from different folders apart and imports their divider colors', async () => {
mockFiles({
[CONFIG_PATH]: 'theme = light:/Users/alice/a/theme,dark:/Users/alice/b/theme\n',
'/Users/alice/a/theme':
'background = #ffffff\nforeground = #000000\nsplit-divider-color = #cccccc\n',
'/Users/alice/b/theme':
'background = #000000\nforeground = #ffffff\nsplit-divider-color = #333333\n'
})

const result = await previewGhosttyImport(createStore())

expect(result.diff).toEqual({
terminalColorOverrides: {
red: '#ff0000',
green: '#b9ca4a',
background: '#101010'
}
expect(result.diff).toMatchObject({
terminalThemeDark: 'custom:ghostty:theme',
terminalThemeLight: 'custom:ghostty:theme-light',
terminalDividerColorDark: '#333333',
terminalDividerColorLight: '#cccccc'
})
expect(result.unsupportedKeys).toEqual([])
})

it('reports nothing to change when the same theme is imported again', async () => {
mockFiles({
[CONFIG_PATH]: 'theme = night\n',
[`${USER_THEMES}/night`]: 'background = #000000\nforeground = #ffffff\n'
})
const first = await previewGhosttyImport(createStore())

const second = await previewGhosttyImport(createStore({ ...first.diff }))

expect(second.diff).toEqual({})
})

it('resolves an absolute theme path without probing theme search dirs', async () => {
const configPath = '/Users/alice/Library/Application Support/com.mitchellh.ghostty/config'
const themePath = '/Users/alice/themes/work'
statMock.mockImplementation(async (p: string) => {
if (p === configPath || p === themePath) {
return { isFile: () => true, size: 128 }
}
throw Object.assign(new Error('ENOENT'), { code: 'ENOENT' })
})
readFileMock.mockImplementation(async (p: string) => {
if (p === themePath) {
return 'background = #202020\nforeground = #f0f0f0\n'
}
return `theme = ${themePath}\n`
mockFiles({
[CONFIG_PATH]: `theme = ${themePath}\n`,
[themePath]: 'background = #f0f0f0\nforeground = #202020\n'
})

const result = await previewGhosttyImport(createStore())

expect(result.diff).toEqual({
terminalColorOverrides: {
background: '#202020',
foreground: '#f0f0f0'
}
})
expect(statMock).toHaveBeenCalledWith(themePath)
expect(statMock).not.toHaveBeenCalledWith(
'/Users/alice/.config/ghostty/themes/Users/alice/themes/work'
)
expect(result.unsupportedKeys).toEqual([])
expect(result.diff.terminalThemeDark).toBe('custom:ghostty:work')
expect(result.diff.terminalCustomThemes?.[0]?.mode).toBe('light')
expect(statMock).not.toHaveBeenCalledWith(`${USER_THEMES}/Users/alice/themes/work`)
})
})
Loading
Loading