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
48 changes: 21 additions & 27 deletions src/main/system-fonts.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,16 +27,6 @@ const timedOut: ProcessResult = {
timedOut: true
}

function expectedFallbackFont(platform = process.platform): string {
if (platform === 'darwin') {
return 'SF Mono'
}
if (platform === 'win32') {
return 'Cascadia Mono'
}
return 'JetBrains Mono'
}

async function withPlatform<T>(platform: NodeJS.Platform, fn: () => Promise<T>): Promise<T> {
const originalPlatform = process.platform
Object.defineProperty(process, 'platform', { configurable: true, value: platform })
Expand Down Expand Up @@ -94,14 +84,14 @@ describe('listSystemFontFamilies', () => {
})
})

it('falls back when the platform font command never exits', async () => {
it('returns no fonts when the platform font command never exits', async () => {
runProcessMock.mockResolvedValue(timedOut)

const { listSystemFontFamilies } = await import('./system-fonts')
await expect(listSystemFontFamilies()).resolves.toContain(expectedFallbackFont())
await expect(listSystemFontFamilies()).resolves.toEqual([])
})

it('falls back when the platform font command reports failure', async () => {
it('returns no fonts when the platform font command reports failure', async () => {
runProcessMock.mockResolvedValue({
code: 1,
signal: null,
Expand All @@ -111,20 +101,24 @@ describe('listSystemFontFamilies', () => {
})

const { listSystemFontFamilies } = await import('./system-fonts')
await expect(listSystemFontFamilies()).resolves.toContain(expectedFallbackFont())
await expect(listSystemFontFamilies()).resolves.toEqual([])
})

it.each([
['darwin' as NodeJS.Platform, 45_000],
['linux' as NodeJS.Platform, 15_000],
['win32' as NodeJS.Platform, 15_000]
])('asks for the %s font command timeout of %dms', async (platform, timeoutMs) => {
await withPlatform(platform, async () => {
runProcessMock.mockResolvedValue(ok('Consolas\n'))
const { listSystemFontFamilies } = await import('./system-fonts')
await listSystemFontFamilies()

expect(runProcessMock.mock.calls[0]?.[0].timeoutMs).toBe(timeoutMs)
})
})
const platformTimeouts: [NodeJS.Platform, number][] = [
['darwin', 45_000],
['linux', 15_000],
['win32', 15_000]
]
it.each(platformTimeouts)(
'asks for the %s font command timeout of %dms',
async (platform, timeoutMs) => {
await withPlatform(platform, async () => {
runProcessMock.mockResolvedValue(ok('Consolas\n'))
const { listSystemFontFamilies } = await import('./system-fonts')
await listSystemFontFamilies()

expect(runProcessMock.mock.calls[0]?.[0].timeoutMs).toBe(timeoutMs)
})
}
)
})
30 changes: 7 additions & 23 deletions src/main/system-fonts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ const SYSTEM_FONT_LIST_TIMEOUT_MS = 15_000
// Large macOS font catalogs need more time in system_profiler.
const MAC_SYSTEM_FONT_LIST_TIMEOUT_MS = 45_000

/** Empty when the OS list is unreadable; the renderer then shows its curated fonts and says so. */
export async function listSystemFontFamilies(): Promise<string[]> {
if (cachedFonts) {
return cachedFonts
Expand All @@ -16,13 +17,13 @@ export async function listSystemFontFamilies(): Promise<string[]> {
}

fontsPromise = loadSystemFontFamilies()
.then((fonts) => {
cachedFonts = fonts.length > 0 ? fonts : fallbackFonts()
return cachedFonts
.catch((error: unknown) => {
console.warn('[system-fonts] failed to list installed fonts:', error)
return []
})
.catch(() => {
cachedFonts = fallbackFonts()
return cachedFonts
.then((fonts) => {
cachedFonts = fonts
return fonts
})
.finally(() => {
fontsPromise = null
Expand Down Expand Up @@ -130,20 +131,3 @@ function uniqueSorted(values: (string | undefined)[]): string[] {
)
).sort((a, b) => a.localeCompare(b))
}

function fallbackFonts(): string[] {
if (process.platform === 'darwin') {
return ['SF Mono', 'Menlo', 'Monaco', 'JetBrains Mono', 'Fira Code']
}
if (process.platform === 'win32') {
return ['Cascadia Mono', 'Consolas', 'Lucida Console', 'JetBrains Mono', 'Fira Code']
}
return [
'JetBrains Mono',
'Fira Code',
'DejaVu Sans Mono',
'Liberation Mono',
'Ubuntu Mono',
'Noto Sans Mono'
]
}
8 changes: 7 additions & 1 deletion src/main/window/attach-main-window-services.ts
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,13 @@ export function attachMainWindowServices(
}
)
mainWindow.webContents.session.setPermissionCheckHandler(
(_webContents, permission, _origin, details) => {
(webContents, permission, _origin, details) => {
// Electron's typings omit 'local-fonts', which Chromium checks before queryLocalFonts().
const permissionName: string = permission
// Only the app frame's font picker may list fonts; not subframes or other default-session pages.
if (permissionName === 'local-fonts') {
return webContents?.id === mainWindow.webContents.id && details.isMainFrame === true
}
if (permission !== 'media') {
return allowedPermissions.has(permission)
}
Expand Down
10 changes: 10 additions & 0 deletions src/renderer/src/components/settings/FontAutocomplete.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { Input } from '../ui/input'
import { Popover, PopoverAnchor, PopoverContent } from '../ui/popover'
import { ScrollArea } from '../ui/scroll-area'
import { filterFontSuggestions, getRenderedFontSuggestions } from './settings-form-option-filter'
import { useInstalledFontsUnavailable } from './installed-font-list'
import { translate } from '@/i18n/i18n'

type FontAutocompleteProps = {
Expand Down Expand Up @@ -43,6 +44,7 @@ export function FontAutocomplete({
const lastCommittedValueRef = useRef(value)
const previewFontFamilyRef = useRef(onPreviewFontFamily)
const listboxId = useId()
const installedFontsUnavailable = useInstalledFontsUnavailable()

useEffect(() => {
previewFontFamilyRef.current = onPreviewFontFamily
Expand Down Expand Up @@ -372,6 +374,14 @@ export function FontAutocomplete({
)}
</div>
</ScrollArea>
{installedFontsUnavailable ? (
<p className="border-t border-border px-3 py-2 text-xs text-muted-foreground">
{translate(
'auto.components.settings.FontAutocomplete.installedFontsUnavailable',
'Couldn’t list installed fonts. Type any installed font name to use it.'
)}
</p>
) : null}
</PopoverContent>
</Popover>
</div>
Expand Down
48 changes: 48 additions & 0 deletions src/renderer/src/components/settings/installed-font-list.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import { useSyncExternalStore } from 'react'
import { isWebClientLocation } from '@/lib/web-client-location'
import { isWindowsDesktopClient } from '@/lib/windows-path-access'

// One font list backs every font picker, so its availability is shared too.
let installedFontsUnavailable = false
const listeners = new Set<() => void>()

export function setInstalledFontsUnavailable(unavailable: boolean): void {
// Browsers never expose installed fonts to the web client, so there is no failure to report.
const next = unavailable && !isWebClientLocation()
if (installedFontsUnavailable === next) {
return
}
installedFontsUnavailable = next
for (const listener of listeners) {
listener()
}
}

function subscribe(listener: () => void): () => void {
listeners.add(listener)
return () => listeners.delete(listener)
}

function getInstalledFontsUnavailable(): boolean {
return installedFontsUnavailable
}

export function useInstalledFontsUnavailable(): boolean {
return useSyncExternalStore(subscribe, getInstalledFontsUnavailable)
}

// Chromium enumerates Windows fonts in-process; main's PowerShell fallback can be blocked by policy.
export async function listInstalledFontFamilies(): Promise<string[]> {
if (isWindowsDesktopClient() && window.queryLocalFonts) {
try {
const fonts = await window.queryLocalFonts()
const families = [...new Set(fonts.map((font) => font.family.trim()).filter(Boolean))]
if (families.length > 0) {
return families.sort((a, b) => a.localeCompare(b))
}
} catch (error) {
console.warn('[fonts] queryLocalFonts failed; falling back to the OS font list:', error)
}
}
return window.api.settings.listFonts()
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import type { SourceControlAiSettingsPatch } from '../../../../shared/source-con
import { useAppStore } from '../../store'
import { translate } from '@/i18n/i18n'
import { mergeFontSuggestions } from './SettingsConstants'
import { listInstalledFontFamilies, setInstalledFontsUnavailable } from './installed-font-list'
import type { SettingsStoreModel } from './use-settings-store-model'
import type { SettingsDeepLinkTargetWatch } from './settings-deep-link-target-watcher'
import {
Expand Down Expand Up @@ -145,22 +146,19 @@ export function useSettingsInteractionController(model: SettingsInteractionModel
return
}

installedFontsLoadPromiseRef.current = window.api.settings
.listFonts()
installedFontsLoadPromiseRef.current = listInstalledFontFamilies()
.then((fonts) => {
if (!settingsMountedRef.current) {
return
}
// Latch successful empty results too so font-less systems do not repeatedly list fonts.
// Latch empty results too so an unreadable font list is not re-requested on every focus.
installedFontsLoadedRef.current = true
if (fonts.length === 0) {
return
setInstalledFontsUnavailable(fonts.length === 0)
if (fonts.length > 0) {
setFontSuggestions((prev) => mergeFontSuggestions(fonts, prev))
}
setFontSuggestions((prev) => mergeFontSuggestions(fonts, prev))
})
.catch(() => {
// Fall back to curated cross-platform suggestions.
})
.catch(() => setInstalledFontsUnavailable(true))
.finally(() => {
installedFontsLoadPromiseRef.current = null
})
Expand Down
2 changes: 2 additions & 0 deletions src/renderer/src/env.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,8 @@ declare global {
__endLocalLayoutStreamE2E?: LocalLayoutStreamE2EEnd
/** E2E builds only: whether a paired server's layout frames, not the mirror, draw the workspace. */
__isFrameDrawnServerWorkspaceE2E?: (environmentId: string, worktreeId: string) => boolean
/** Chromium Local Font Access; not yet in TypeScript's DOM lib. */
queryLocalFonts?: () => Promise<{ family: string }[]>
}
}

Expand Down
3 changes: 3 additions & 0 deletions src/renderer/src/i18n/locales/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -13555,6 +13555,9 @@
"PluginSettingsSection": {
"reset": "Reset",
"title": "Settings"
},
"FontAutocomplete": {
"installedFontsUnavailable": "Couldn’t list installed fonts. Type any installed font name to use it."
}
},
"right": {
Expand Down
Loading