From 51f3c956ed156c858975b8affea5538da2f96efb Mon Sep 17 00:00:00 2001 From: Neil <4138956+nwparker@users.noreply.github.com> Date: Sat, 7 Nov 2026 02:08:35 -0800 Subject: [PATCH] feat(plugins): let plugins ship web fonts for the terminal, editor and interface (#39416) * feat(plugins): let plugins contribute web fonts to the font pickers Plugins declare font families under contributes.fonts (WOFF/WOFF2 only). Install checks each file's signature against its extension and caps file size, family count and plugin total; main never parses a font. Files are served over the plugin image scheme only while the plugin is enabled, typed and nosniff. The renderer registers each family under a name that carries the plugin key, so a plugin font cannot shadow an installed or built-in font, and it applies only once the user picks it. Disabling or uninstalling removes the faces; uninstalling also resets font settings that named them. Refs #38607 * fix(plugins): harden plugin fonts and re-measure editors when they load - Refuse WOFF/WOFF2-wrapped font collections by checking the flavor bytes. - Check dev folders' font files at discovery, not only at install. - Re-check family, weight and style from the plugin list in the renderer. - Track loaded families (case-insensitively) from document font loads, so the code editor re-measures and terminals, previews, the SSH terminal and the dashboard popout re-apply only when their own font changes. - Register plugin fonts in the dashboard popout window. - Give dev-folder font URLs their change count so edits reload. - Keep monospace fallbacks unless the chosen family is exactly that font. * fix(terminal): keep every fallback only for plugin font families System font choices keep their existing fallback list unchanged. * fix(plugins): leave the dashboard popout's plugin list alone; add the font row string Registering fonts there started the plugin auto-update watcher in a window with no toaster, which could consume update notices. Adds the new contribution-row string to the English catalog and the fonts list to the RPC test manifest. --- docs/reference/plugin-catalog.md | 2 +- docs/reference/plugin-manifest.md | 20 ++ .../plugins/orca-catalog.v2.schema.json | 1 + .../plugins/orca-plugin.v2.schema.json | 87 ++++++++ .../references/manifest.md | 16 ++ src/cli/bundled-skill-guides.ts | 16 ++ .../plugins/plugin-artifact-validation.ts | 11 + src/main/plugins/plugin-discovery.ts | 6 + src/main/plugins/plugin-font-files.test.ts | 86 ++++++++ src/main/plugins/plugin-font-files.ts | 63 ++++++ src/main/plugins/plugin-image-protocol.ts | 36 +++- src/main/plugins/plugin-image-scheme.ts | 3 +- src/main/plugins/plugin-list-projection.ts | 15 ++ src/main/plugins/plugin-removal-settings.ts | 8 +- .../rpc/methods/plugins/plugins.test.ts | 1 + src/main/startup/main-process-plugins.ts | 4 +- .../src/app-shell/use-document-appearance.ts | 2 + .../dashboard-popout/AgentTerminalPreview.tsx | 4 +- .../preview-terminal-options.ts | 3 +- .../PlainSshTerminalView.tsx | 4 +- .../plugins/page/PluginAddsSection.tsx | 7 +- .../plugin-contribution-row-labels.ts | 14 ++ .../presentation/plugin-contributions.ts | 7 + .../state/use-plugin-contribution-source.ts | 1 + .../appearance/fonts/font-suggestions.ts | 15 ++ .../settings/page/use-settings-store-model.ts | 14 +- ...TerminalSettingsPreview.lifecycle.test.tsx | 5 + .../appearance/TerminalSettingsPreview.tsx | 7 +- .../appearance/terminal-appearance.ts | 3 +- .../use-mounted-terminal-appearance.ts | 4 + .../mounting/terminal-pane-manager-options.ts | 5 +- src/renderer/src/i18n/locales/en.json | 3 +- src/renderer/src/lib/monaco-setup.ts | 5 +- src/renderer/src/lib/monospace-font-family.ts | 6 +- src/renderer/src/store/plugin-fonts.ts | 202 ++++++++++++++++++ src/shared/plugin-font-settings.ts | 30 +++ .../plugin-contribution-points.ts | 14 ++ .../plugin-contribution-summary.ts | 1 + .../contributions/plugin-font-contribution.ts | 163 ++++++++++++++ src/shared/plugins/images/plugin-image-url.ts | 7 +- .../installation/plugin-host-version.ts | 4 +- ...plugin-manifest-contribution-validation.ts | 8 + src/shared/plugins/plugin-list-entry.ts | 13 ++ 43 files changed, 893 insertions(+), 33 deletions(-) create mode 100644 src/main/plugins/plugin-font-files.test.ts create mode 100644 src/main/plugins/plugin-font-files.ts create mode 100644 src/renderer/src/store/plugin-fonts.ts create mode 100644 src/shared/plugin-font-settings.ts create mode 100644 src/shared/plugins/contributions/plugin-font-contribution.ts diff --git a/docs/reference/plugin-catalog.md b/docs/reference/plugin-catalog.md index 010a094dc62..ded9b142fb7 100644 --- a/docs/reference/plugin-catalog.md +++ b/docs/reference/plugin-catalog.md @@ -108,7 +108,7 @@ One thing the release adds to Orca. | Field | Type | Required | Since | Description | | --- | --- | --- | --- | --- | -| `kind` | `"panels"` \| `"commands"` \| `"events"` \| `"hooks"` \| `"languagePacks"` \| `"keybindings"` \| `"vmRecipes"` \| `"themes"` \| `"terminalThemes"` \| `"iconThemes"` \| `"syntaxes"` \| `"customEditors"` \| `"newFiles"` \| `"settings"` \| `"statusBarItems"` | yes | 1.4.245 | Contribution point. Example: `"themes"` | +| `kind` | `"panels"` \| `"commands"` \| `"events"` \| `"hooks"` \| `"languagePacks"` \| `"keybindings"` \| `"vmRecipes"` \| `"themes"` \| `"terminalThemes"` \| `"iconThemes"` \| `"fonts"` \| `"syntaxes"` \| `"customEditors"` \| `"newFiles"` \| `"settings"` \| `"statusBarItems"` | yes | 1.4.245 | Contribution point. Example: `"themes"` | | `name` | string | yes | 1.4.245 | What the item is called in Orca. Example: `"Dusk"` | | `detail` | string | no | 1.4.245 | Extra context, such as file extensions. | diff --git a/docs/reference/plugin-manifest.md b/docs/reference/plugin-manifest.md index 31c4c4c41ba..dd085638f00 100644 --- a/docs/reference/plugin-manifest.md +++ b/docs/reference/plugin-manifest.md @@ -40,6 +40,7 @@ Add `"$schema": "https://raw.githubusercontent.com/stablyai/orca/main/docs/schem | `contributes.themes` | [ThemeContribution](#themecontribution)[] | no | 1.4.245 | App color themes. At most 64. | | `contributes.terminalThemes` | [ThemeContribution](#themecontribution)[] | no | 1.4.245 | Terminal ANSI palettes. At most 64. | | `contributes.iconThemes` | [ThemeContribution](#themecontribution)[] | no | 1.4.245 | File icon themes. At most 32. | +| `contributes.fonts` | [FontContribution](#fontcontribution)[] | no | 1.4.253 | Font families for the terminal, editor and interface font pickers. At most 8. | | `contributes.syntaxes` | [SyntaxContribution](#syntaxcontribution)[] | no | 1.4.245 | Syntax highlighting for editor languages. At most 16. | | `contributes.customEditors` | [CustomEditorContribution](#customeditorcontribution)[] | no | 1.4.245 | Editors that open files of given types in the editor tab. At most 16. | | `contributes.newFiles` | [NewFileContribution](#newfilecontribution)[] | no | 1.4.245 | Untitled files the user can create from the + menu and the command palette. At most 16. | @@ -137,6 +138,25 @@ A titled theme file. | `title` | string | yes | 1.4.245 | Name shown in the theme picker. Example: `"Dusk"` | | `path` | string | yes | 1.4.245 | JSON theme file, at most 16 KiB. Relative to the plugin root; `..` segments and Windows device names such as `CON` are refused. Example: `"themes/dusk.json"` | +## FontContribution + +A font family the user can pick for the terminal, editor or interface. It applies only once picked. + +| Field | Type | Required | Since | Description | +| --- | --- | --- | --- | --- | +| `family` | string | yes | 1.4.253 | Family name shown in the font pickers. Orca adds the plugin id, so a plugin font never replaces an installed or built-in font of the same name. Example: `"Geist"` | +| `faces` | [FontFaceContribution](#fontfacecontribution)[] | yes | 1.4.253 | The family's files, at most 8. All of a plugin's font files together may be at most 8 MB. | + +## FontFaceContribution + +One file of a font family. + +| Field | Type | Required | Since | Description | +| --- | --- | --- | --- | --- | +| `path` | string | yes | 1.4.253 | WOFF or WOFF2 file, at most 2 MB; its first bytes must match its extension. TTF, OTF and font collections are refused. Relative to the plugin root; `..` segments and Windows device names such as `CON` are refused. Example: `"fonts/Geist-Variable.woff2"` | +| `weight` | string | no | 1.4.253 | CSS weight this file draws, or a range for a variable font. Defaults to `400`. Example: `"400"` | +| `style` | `"normal"` \| `"italic"` | no | 1.4.253 | Whether this file is the italic face. Defaults to `normal`. | + ## SyntaxContribution Syntax highlighting for one language. diff --git a/docs/schemas/plugins/orca-catalog.v2.schema.json b/docs/schemas/plugins/orca-catalog.v2.schema.json index 11d1fa9f9a5..7741b72b197 100644 --- a/docs/schemas/plugins/orca-catalog.v2.schema.json +++ b/docs/schemas/plugins/orca-catalog.v2.schema.json @@ -565,6 +565,7 @@ "themes", "terminalThemes", "iconThemes", + "fonts", "syntaxes", "customEditors", "newFiles", diff --git a/docs/schemas/plugins/orca-plugin.v2.schema.json b/docs/schemas/plugins/orca-plugin.v2.schema.json index 0f4532233dd..28b4a822243 100644 --- a/docs/schemas/plugins/orca-plugin.v2.schema.json +++ b/docs/schemas/plugins/orca-plugin.v2.schema.json @@ -285,6 +285,16 @@ "$ref": "#/$defs/ThemeContribution" } }, + "fonts": { + "default": [], + "description": "Font families for the terminal, editor and interface font pickers. At most 8.", + "x-orca-since": "1.4.253", + "maxItems": 8, + "type": "array", + "items": { + "$ref": "#/$defs/FontContribution" + } + }, "syntaxes": { "default": [], "description": "Syntax highlighting for editor languages. At most 16.", @@ -940,6 +950,83 @@ "additionalProperties": false, "description": "A titled theme file." }, + "FontContribution": { + "type": "object", + "properties": { + "family": { + "type": "string", + "pattern": "^[A-Za-z0-9](?:[A-Za-z0-9 _.-]{0,46}[A-Za-z0-9])?$", + "description": "Family name shown in the font pickers. Orca adds the plugin id, so a plugin font never replaces an installed or built-in font of the same name.", + "x-orca-since": "1.4.253", + "examples": [ + "Geist" + ] + }, + "faces": { + "minItems": 1, + "maxItems": 8, + "type": "array", + "items": { + "$ref": "#/$defs/FontFaceContribution" + }, + "description": "The family's files, at most 8. All of a plugin's font files together may be at most 8 MB.", + "x-orca-since": "1.4.253" + } + }, + "required": [ + "family", + "faces" + ], + "additionalProperties": false, + "description": "A font family the user can pick for the terminal, editor or interface. It applies only once picked." + }, + "FontFaceContribution": { + "type": "object", + "properties": { + "path": { + "type": "string", + "minLength": 1, + "maxLength": 1024, + "allOf": [ + { + "pattern": "^[^<>:\"|?*\\x00-\\x1f\\\\/]*[^<>:\"|?*\\x00-\\x1f\\\\/. ](?:[\\\\/][^<>:\"|?*\\x00-\\x1f\\\\/]*[^<>:\"|?*\\x00-\\x1f\\\\/. ])*$" + }, + { + "pattern": "\\.woff2?$" + } + ], + "description": "WOFF or WOFF2 file, at most 2 MB; its first bytes must match its extension. TTF, OTF and font collections are refused. Relative to the plugin root; `..` segments and Windows device names such as `CON` are refused.", + "x-orca-since": "1.4.253", + "examples": [ + "fonts/Geist-Variable.woff2" + ] + }, + "weight": { + "description": "CSS weight this file draws, or a range for a variable font. Defaults to `400`.", + "x-orca-since": "1.4.253", + "examples": [ + "400", + "100 900" + ], + "type": "string", + "pattern": "^(?:[1-9]\\d{0,2}|1000)(?: (?:[1-9]\\d{0,2}|1000))?$" + }, + "style": { + "description": "Whether this file is the italic face. Defaults to `normal`.", + "x-orca-since": "1.4.253", + "type": "string", + "enum": [ + "normal", + "italic" + ] + } + }, + "required": [ + "path" + ], + "additionalProperties": false, + "description": "One file of a font family." + }, "SyntaxContribution": { "type": "object", "properties": { diff --git a/skill-guides/orca-plugin-authoring/references/manifest.md b/skill-guides/orca-plugin-authoring/references/manifest.md index f3c7251ada9..350c4f02e91 100644 --- a/skill-guides/orca-plugin-authoring/references/manifest.md +++ b/skill-guides/orca-plugin-authoring/references/manifest.md @@ -43,6 +43,7 @@ - `themes` (ThemeContribution[], since 1.4.245): App color themes. At most 64. - `terminalThemes` (ThemeContribution[], since 1.4.245): Terminal ANSI palettes. At most 64. - `iconThemes` (ThemeContribution[], since 1.4.245): File icon themes. At most 32. +- `fonts` (FontContribution[], since 1.4.253): Font families for the terminal, editor and interface font pickers. At most 8. - `syntaxes` (SyntaxContribution[], since 1.4.245): Syntax highlighting for editor languages. At most 16. - `customEditors` (CustomEditorContribution[], since 1.4.245): Editors that open files of given types in the editor tab. At most 16. - `newFiles` (NewFileContribution[], since 1.4.245): Untitled files the user can create from the + menu and the command palette. At most 16. @@ -114,6 +115,21 @@ A titled theme file. - `title` (string, required, since 1.4.245): Name shown in the theme picker. - `path` (string, required, since 1.4.245): JSON theme file, at most 16 KiB. +## FontContribution + +A font family the user can pick for the terminal, editor or interface. It applies only once picked. + +- `family` (string, required, since 1.4.253): Family name shown in the font pickers. Orca adds the plugin id, so a plugin font never replaces an installed or built-in font of the same name. +- `faces` (FontFaceContribution[], required, since 1.4.253): The family's files, at most 8. All of a plugin's font files together may be at most 8 MB. + +## FontFaceContribution + +One file of a font family. + +- `path` (string, required, since 1.4.253): WOFF or WOFF2 file, at most 2 MB; its first bytes must match its extension. TTF, OTF and font collections are refused. +- `weight` (string, since 1.4.253): CSS weight this file draws, or a range for a variable font. Defaults to `400`. +- `style` ("normal" | "italic", since 1.4.253): Whether this file is the italic face. Defaults to `normal`. + ## SyntaxContribution Syntax highlighting for one language. diff --git a/src/cli/bundled-skill-guides.ts b/src/cli/bundled-skill-guides.ts index 7861ce08fa9..59593c177cd 100644 --- a/src/cli/bundled-skill-guides.ts +++ b/src/cli/bundled-skill-guides.ts @@ -3182,6 +3182,7 @@ const ORCA_PLUGIN_AUTHORING_MANIFEST_REFERENCE_MARKDOWN = [ "- `themes` (ThemeContribution[], since 1.4.245): App color themes. At most 64.", "- `terminalThemes` (ThemeContribution[], since 1.4.245): Terminal ANSI palettes. At most 64.", "- `iconThemes` (ThemeContribution[], since 1.4.245): File icon themes. At most 32.", + "- `fonts` (FontContribution[], since 1.4.253): Font families for the terminal, editor and interface font pickers. At most 8.", "- `syntaxes` (SyntaxContribution[], since 1.4.245): Syntax highlighting for editor languages. At most 16.", "- `customEditors` (CustomEditorContribution[], since 1.4.245): Editors that open files of given types in the editor tab. At most 16.", "- `newFiles` (NewFileContribution[], since 1.4.245): Untitled files the user can create from the + menu and the command palette. At most 16.", @@ -3253,6 +3254,21 @@ const ORCA_PLUGIN_AUTHORING_MANIFEST_REFERENCE_MARKDOWN = [ "- `title` (string, required, since 1.4.245): Name shown in the theme picker.", "- `path` (string, required, since 1.4.245): JSON theme file, at most 16 KiB.", "", + "## FontContribution", + "", + "A font family the user can pick for the terminal, editor or interface. It applies only once picked.", + "", + "- `family` (string, required, since 1.4.253): Family name shown in the font pickers. Orca adds the plugin id, so a plugin font never replaces an installed or built-in font of the same name.", + "- `faces` (FontFaceContribution[], required, since 1.4.253): The family's files, at most 8. All of a plugin's font files together may be at most 8 MB.", + "", + "## FontFaceContribution", + "", + "One file of a font family.", + "", + "- `path` (string, required, since 1.4.253): WOFF or WOFF2 file, at most 2 MB; its first bytes must match its extension. TTF, OTF and font collections are refused.", + "- `weight` (string, since 1.4.253): CSS weight this file draws, or a range for a variable font. Defaults to `400`.", + "- `style` (\"normal\" | \"italic\", since 1.4.253): Whether this file is the italic face. Defaults to `normal`.", + "", "## SyntaxContribution", "", "Syntax highlighting for one language.", diff --git a/src/main/plugins/plugin-artifact-validation.ts b/src/main/plugins/plugin-artifact-validation.ts index 5870d780a06..be139fa5549 100644 --- a/src/main/plugins/plugin-artifact-validation.ts +++ b/src/main/plugins/plugin-artifact-validation.ts @@ -9,6 +9,8 @@ import { parsePluginVmRecipeArtifact } from '../../shared/plugins/artifacts/plug import { PLUGIN_IMAGE_RULES } from '../../shared/plugins/images/plugin-image-fields' import { PLUGIN_NEW_FILE_TEMPLATE_MAX_BYTES } from '../../shared/plugins/contributions/plugin-new-file-contribution' import { validatePluginImageArtifacts } from './plugin-image-artifact-validation' +import { validatePluginFontArtifacts } from './plugin-font-files' +import { PLUGIN_FONT_FILE_MAX_BYTES } from '../../shared/plugins/contributions/plugin-font-contribution' import { PLUGIN_PANEL_ENTRY_MAX_BYTES } from '../../shared/plugins/frames/plugin-frame-entry-limits' import { PLUGIN_WORKER_ENTRY_MAX_BYTES, @@ -97,6 +99,11 @@ function declaredArtifactPaths(manifest: PluginManifest): DeclaredArtifact[] { ...c.iconThemes.flatMap((theme) => declaredFile(`icon theme "${theme.id}"`, theme.path, PLUGIN_ICON_THEME_MAX_BYTES) ), + ...c.fonts.flatMap((font) => + font.faces.flatMap((face) => + declaredFile(`font "${font.family}"`, face.path, PLUGIN_FONT_FILE_MAX_BYTES) + ) + ), ...c.syntaxes.flatMap((syntax) => [ ...declaredFile( `syntax "${syntax.id}" grammar`, @@ -199,6 +206,10 @@ export async function validatePluginInstallContent( if (!images.ok) { return images } + const fonts = await validatePluginFontArtifacts(rootDir, manifest) + if (!fonts.ok) { + return fonts + } const vmRecipeIds = new Set() for (const contribution of manifest.contributes.vmRecipes) { try { diff --git a/src/main/plugins/plugin-discovery.ts b/src/main/plugins/plugin-discovery.ts index 47ba05c1e34..7f6ca417d5d 100644 --- a/src/main/plugins/plugin-discovery.ts +++ b/src/main/plugins/plugin-discovery.ts @@ -23,6 +23,7 @@ import { requiresPluginContentApproval } from '../../shared/plugins/approval/plugin-consent-fingerprint' import { validateDeclaredPluginArtifacts } from './plugin-artifact-validation' +import { validatePluginFontArtifacts } from './plugin-font-files' import { readPluginManifestText } from './plugin-manifest-file' import { readPluginCurrentPointer } from './installation/plugin-current-pointer' import { hashPluginTree } from './plugin-content-hash' @@ -137,6 +138,11 @@ async function readManifestDir( isDev } } + // Why dev only: install already ran this on installed trees, which never change in place. + const fonts = isDev ? await validatePluginFontArtifacts(rootDir, manifest) : { ok: true as const } + if (!fonts.ok) { + return { pluginKey, rootDir, error: `invalid declared artifact: ${fonts.error}`, isDev } + } let consentContentIdentity: string | undefined if (installedContentHash && requiresPluginContentApproval(manifest)) { consentContentIdentity = installedContentHash diff --git a/src/main/plugins/plugin-font-files.test.ts b/src/main/plugins/plugin-font-files.test.ts new file mode 100644 index 00000000000..87110be84f6 --- /dev/null +++ b/src/main/plugins/plugin-font-files.test.ts @@ -0,0 +1,86 @@ +import { mkdtemp, rm, writeFile, mkdir } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { pluginManifestSchema } from '../../shared/plugins/manifest/plugin-manifest' +import { PLUGIN_FONTS_SINCE } from '../../shared/plugins/contributions/plugin-font-contribution' +import { pluginInstalledImageUrl } from '../../shared/plugins/images/plugin-image-url' +import { validatePluginInstallContent } from './plugin-artifact-validation' +import { createPluginImageRequestHandler } from './plugin-image-protocol' +import type { ValidDiscoveredPlugin } from './plugin-discovery' +import { PluginImageCache } from './plugin-image-cache' + +vi.mock('electron', () => ({ protocol: { handle: vi.fn() } })) + +const roots: string[] = [] +const WOFF2 = Buffer.from([0x77, 0x4f, 0x46, 0x32, 0, 1, 0, 0, 0, 0, 0, 0]) +const TTF = Buffer.from([0, 1, 0, 0, 0, 0x0a, 0x00, 0x80]) +const WOFF2_COLLECTION = Buffer.from([0x77, 0x4f, 0x46, 0x32, 0x74, 0x74, 0x63, 0x66, 0, 0, 0, 0]) + +async function fontPlugin(file: Buffer, path = 'fonts/mono.woff2') { + const root = await mkdtemp(join(tmpdir(), 'orca-plugin-fonts-')) + roots.push(root) + await mkdir(join(root, 'fonts'), { recursive: true }) + await writeFile(join(root, path), file) + const manifest = pluginManifestSchema.parse({ + manifestVersion: 2, + execution: 'data', + id: 'mono', + name: 'Mono', + version: '1.0.0', + engines: { orca: `>=${PLUGIN_FONTS_SINCE}` }, + contributes: { fonts: [{ family: 'Mono', faces: [{ path }] }] } + }) + return { root, manifest } +} + +afterEach(async () => { + await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true }))) +}) + +describe('plugin font files', () => { + it('accepts a WOFF2 file', async () => { + const good = await fontPlugin(WOFF2) + await expect(validatePluginInstallContent(good.root, good.manifest)).resolves.toEqual({ + ok: true + }) + }) + + it.each([ + ['a TrueType file renamed to .woff2', TTF], + ['a WOFF2-wrapped font collection', WOFF2_COLLECTION] + ])('refuses %s', async (_label, bytes) => { + const bad = await fontPlugin(bytes) + await expect(validatePluginInstallContent(bad.root, bad.manifest)).resolves.toEqual({ + ok: false, + error: 'font "Mono" fonts/mono.woff2: is not a WOFF or WOFF2 font matching its extension' + }) + }) + + it('serves a font only for an enabled plugin, typed and unsniffable', async () => { + const { root, manifest } = await fontPlugin(WOFF2) + const plugin: ValidDiscoveredPlugin = { + pluginKey: 'acme.mono', + rootDir: root, + manifest, + consentFingerprint: 'fingerprint', + isDev: false, + contentHash: 'a'.repeat(64) + } + let enabled = true + const handler = createPluginImageRequestHandler({ + cache: new PluginImageCache(root), + findValidPlugin: () => plugin, + findApprovedPlugin: () => (enabled ? plugin : null) + }) + const url = pluginInstalledImageUrl('acme.mono', 'a'.repeat(64), 'font-0-0') + const served = await handler(new Request(url)) + expect(served.status).toBe(200) + expect(served.headers.get('content-type')).toBe('font/woff2') + expect(served.headers.get('x-content-type-options')).toBe('nosniff') + expect(served.headers.get('access-control-allow-origin')).toBe('*') + expect(Buffer.from(await served.arrayBuffer())).toEqual(WOFF2) + enabled = false + expect((await handler(new Request(url))).status).toBe(404) + }) +}) diff --git a/src/main/plugins/plugin-font-files.ts b/src/main/plugins/plugin-font-files.ts new file mode 100644 index 00000000000..fda34351aab --- /dev/null +++ b/src/main/plugins/plugin-font-files.ts @@ -0,0 +1,63 @@ +import type { PluginManifest } from '../../shared/plugins/manifest/plugin-manifest' +import { + PLUGIN_FONT_FILE_MAX_BYTES, + PLUGIN_FONT_MIME, + PLUGIN_FONTS_TOTAL_MAX_BYTES, + parsePluginFontSlot, + pluginFontFormat +} from '../../shared/plugins/contributions/plugin-font-contribution' +import { readContainedPluginArtifactBytes } from './plugin-contained-artifact' + +export type CheckedPluginFont = { bytes: Buffer; mimeType: string } + +// Why main never parses a font: only the signature is checked here; the renderer's font loader +// sanitizes the file before anything reads its tables. +async function readCheckedFont(rootDir: string, path: string): Promise { + const bytes = await readContainedPluginArtifactBytes(rootDir, path, PLUGIN_FONT_FILE_MAX_BYTES) + const format = pluginFontFormat(path, bytes) + if (!format) { + throw new Error('is not a WOFF or WOFF2 font matching its extension') + } + return { bytes, mimeType: PLUGIN_FONT_MIME[format] } +} + +/** The font file a `font--` slot names, re-checked like at install; null when it no longer fits. */ +export async function readPluginFontSlot( + rootDir: string, + manifest: PluginManifest, + slot: string +): Promise { + const indexes = parsePluginFontSlot(slot) + const face = indexes + ? manifest.contributes.fonts[indexes.familyIndex]?.faces[indexes.faceIndex] + : undefined + return face ? readCheckedFont(rootDir, face.path).catch(() => null) : null +} + +/** Checks every declared font file's signature and the plugin's font total at the install boundary. */ +export async function validatePluginFontArtifacts( + rootDir: string, + manifest: PluginManifest +): Promise<{ ok: true } | { ok: false; error: string }> { + let total = 0 + const counted = new Set() + for (const font of manifest.contributes.fonts) { + for (const face of font.faces) { + if (counted.has(face.path)) { + continue + } + counted.add(face.path) + try { + total += (await readCheckedFont(rootDir, face.path)).bytes.byteLength + } catch (error) { + return { + ok: false, + error: `font "${font.family}" ${face.path}: ${error instanceof Error ? error.message : String(error)}` + } + } + } + } + return total > PLUGIN_FONTS_TOTAL_MAX_BYTES + ? { ok: false, error: `fonts total more than ${PLUGIN_FONTS_TOTAL_MAX_BYTES / 1024 / 1024} MB` } + : { ok: true } +} diff --git a/src/main/plugins/plugin-image-protocol.ts b/src/main/plugins/plugin-image-protocol.ts index 3d703a2a8b7..c367a11bbf9 100644 --- a/src/main/plugins/plugin-image-protocol.ts +++ b/src/main/plugins/plugin-image-protocol.ts @@ -8,10 +8,18 @@ import { readCheckedPluginImage, type CheckedPluginImage } from './plugin-image- import type { ValidDiscoveredPlugin } from './plugin-discovery' import { declaredPluginImages } from './plugin-image-artifact-validation' import type { PluginImageCache } from './plugin-image-cache' +import { readPluginFontSlot, type CheckedPluginFont } from './plugin-font-files' +import { parsePluginFontSlot } from '../../shared/plugins/contributions/plugin-font-contribution' export type PluginImageProtocolDependencies = { cache: PluginImageCache findValidPlugin: (pluginKey: string) => ValidDiscoveredPlugin | null + /** Enabled and consented; fonts are served only for these. */ + findApprovedPlugin: (pluginKey: string) => ValidDiscoveredPlugin | null +} + +function isCurrentContent(plugin: ValidDiscoveredPlugin, contentHash: string): boolean { + return contentHash === (plugin.isDev ? 'dev' : plugin.contentHash) } /** An installed plugin's declared image or theme background, re-checked on every read like at install. */ @@ -20,7 +28,7 @@ async function readInstalledImage( contentHash: string, slot: string ): Promise { - if (contentHash !== (plugin.isDev ? 'dev' : plugin.contentHash)) { + if (!isCurrentContent(plugin, contentHash)) { return null } const declared = declaredPluginImages(plugin.manifest).find( @@ -44,28 +52,38 @@ export function createPluginImageRequestHandler( } const reference = parsePluginImageUrl(request.url) try { - let image: CheckedPluginImage | null = null + let asset: CheckedPluginImage | CheckedPluginFont | null = null + const isFont = reference?.kind === 'installed' && parsePluginFontSlot(reference.slot) !== null if (reference?.kind === 'sha') { - image = await dependencies.cache.get(reference.sha256) + asset = await dependencies.cache.get(reference.sha256) + } else if (reference?.kind === 'installed' && isFont) { + const plugin = dependencies.findApprovedPlugin(reference.pluginKey) + asset = + plugin && isCurrentContent(plugin, reference.contentHash) + ? await readPluginFontSlot(plugin.rootDir, plugin.manifest, reference.slot) + : null } else if (reference?.kind === 'installed') { const plugin = dependencies.findValidPlugin(reference.pluginKey) - image = plugin + asset = plugin ? await readInstalledImage(plugin, reference.contentHash, reference.slot) : null } - if (!image) { + if (!asset) { return new Response(null, { status: 404 }) } - return new Response(request.method === 'HEAD' ? null : new Uint8Array(image.bytes), { + return new Response(request.method === 'HEAD' ? null : new Uint8Array(asset.bytes), { headers: { - 'Content-Type': image.mimeType, - 'Content-Length': String(image.bytes.byteLength), + 'Content-Type': asset.mimeType, + 'Content-Length': String(asset.bytes.byteLength), // Why immutable is safe: a hash or install hash names exact bytes; dev trees change in place. 'Cache-Control': reference?.kind === 'installed' && reference.contentHash === 'dev' ? 'no-store' : 'private, max-age=31536000, immutable', - 'X-Content-Type-Options': 'nosniff' + 'X-Content-Type-Options': 'nosniff', + // Why: web fonts load in CORS mode; only the default session handles this scheme, so + // plugin frames and browser tabs, which use their own sessions, still cannot reach it. + ...(isFont ? { 'Access-Control-Allow-Origin': '*' } : {}) } }) } catch { diff --git a/src/main/plugins/plugin-image-scheme.ts b/src/main/plugins/plugin-image-scheme.ts index 0af1cc35514..bf42a8fb359 100644 --- a/src/main/plugins/plugin-image-scheme.ts +++ b/src/main/plugins/plugin-image-scheme.ts @@ -4,5 +4,6 @@ import { PLUGIN_IMAGE_SCHEME } from '../../shared/plugins/images/plugin-image-ur * handler so startup does not load the plugin module graph. */ export const PLUGIN_IMAGE_CUSTOM_SCHEME: Electron.CustomScheme = { scheme: PLUGIN_IMAGE_SCHEME, - privileges: { standard: true, secure: true, stream: true } + // Why corsEnabled: plugin font files load in CORS mode, which a scheme must opt into. + privileges: { standard: true, secure: true, stream: true, corsEnabled: true } } diff --git a/src/main/plugins/plugin-list-projection.ts b/src/main/plugins/plugin-list-projection.ts index 7a925c2cdb5..d6659894c16 100644 --- a/src/main/plugins/plugin-list-projection.ts +++ b/src/main/plugins/plugin-list-projection.ts @@ -3,6 +3,7 @@ import { needsReconsent } from '../../shared/plugins/approval/plugin-consent-sta import { pluginPanelTabKey } from '../../shared/plugins/manifest/plugin-manifest' import type { PluginLockfile } from '../../shared/plugins/installation/plugin-install-lockfile' import { isInvalidDiscoveredPlugin, type DiscoveredPlugin } from './plugin-discovery' +import { pluginFontSlot } from '../../shared/plugins/contributions/plugin-font-contribution' import { pluginInstalledImageUrl, type PluginHostImages @@ -207,6 +208,20 @@ export async function buildPluginList( extension: newFile.extension, ...contributionIcon(`new-file-${index}`, newFile.icon) })), + fonts: plugin.manifest.contributes.fonts.map((font, familyIndex) => ({ + family: font.family, + faces: font.faces.map((face, faceIndex) => ({ + // Why the change count for dev folders: their URL is otherwise fixed, so an edited + // font would keep its loaded face. + url: `${pluginInstalledImageUrl( + plugin.pluginKey, + plugin.contentHash ?? 'dev', + pluginFontSlot(familyIndex, faceIndex) + )}${plugin.isDev ? `?v=${plugin.devChangeCount ?? 0}` : ''}`, + weight: face.weight ?? '400', + style: face.style ?? 'normal' + })) + })), commands: service.contentPacks.commands.preview(plugin.pluginKey).map((command) => ({ id: command.id, title: command.title, diff --git a/src/main/plugins/plugin-removal-settings.ts b/src/main/plugins/plugin-removal-settings.ts index 8c530806e89..e7518105d03 100644 --- a/src/main/plugins/plugin-removal-settings.ts +++ b/src/main/plugins/plugin-removal-settings.ts @@ -1,9 +1,10 @@ import { pluginThemeSettingsAfterRemoval } from '../../shared/plugin-theme-settings' +import { pluginFontSettingsAfterRemoval } from '../../shared/plugin-font-settings' import { normalizePluginIdList } from '../../shared/plugins/approval/plugin-consent-state' import type { Store } from '../persistence/loading-store/store' /** - * Forgets a removed plugin's consent, disabled flag, allowed external hosts and theme choices. + * Forgets a removed plugin's consent, disabled flag, allowed external hosts, theme and font choices. * `keepDisabled`: Orca republishes a copy it ships on the next launch; that copy comes back off. */ export function clearRemovedPluginSettings( @@ -25,9 +26,10 @@ export function clearRemovedPluginSettings( pluginConsents: consents, disabledPlugins, pluginExternalHostGrants, - ...pluginThemeSettingsAfterRemoval(settings, pluginKey) + ...pluginThemeSettingsAfterRemoval(settings, pluginKey), + ...pluginFontSettingsAfterRemoval(settings, pluginKey) }, - // Why no origin: the uninstalling window must also drop the plugin's theme choices. + // Why no origin: the uninstalling window must also drop the plugin's theme and font choices. { notifyListeners: true } ) } diff --git a/src/main/runtime/rpc/methods/plugins/plugins.test.ts b/src/main/runtime/rpc/methods/plugins/plugins.test.ts index 25bdfe480d7..2a0d91ee3ff 100644 --- a/src/main/runtime/rpc/methods/plugins/plugins.test.ts +++ b/src/main/runtime/rpc/methods/plugins/plugins.test.ts @@ -48,6 +48,7 @@ describe('plugin approval over RPC', () => { themes: [], terminalThemes: [], iconThemes: [], + fonts: [], syntaxes: [], customEditors: [], newFiles: [], diff --git a/src/main/startup/main-process-plugins.ts b/src/main/startup/main-process-plugins.ts index 4be52d336fd..c8dbbfacf28 100644 --- a/src/main/startup/main-process-plugins.ts +++ b/src/main/startup/main-process-plugins.ts @@ -180,7 +180,9 @@ export async function initializeMainProcessPlugins(runtime: OrcaRuntimeService): } installPluginImageProtocolHandler({ cache: pluginImageCache, - findValidPlugin: (pluginKey) => state.pluginService?.findValidPlugin(pluginKey) ?? null + findValidPlugin: (pluginKey) => state.pluginService?.findValidPlugin(pluginKey) ?? null, + findApprovedPlugin: (pluginKey) => + state.pluginService?.findApprovedPlugin(pluginKey, true) ?? null }) const bundledPluginBootstrap = new PluginBundledBootstrapCoordinator({ root: bundledPluginRoot, diff --git a/src/renderer/src/app-shell/use-document-appearance.ts b/src/renderer/src/app-shell/use-document-appearance.ts index 7e13848183f..87102757d91 100644 --- a/src/renderer/src/app-shell/use-document-appearance.ts +++ b/src/renderer/src/app-shell/use-document-appearance.ts @@ -28,6 +28,7 @@ import { usePluginThemes } from '../store/plugin-themes' import { usePluginIconThemeActivation } from '../store/plugin-icon-themes' +import { usePluginFontRegistration } from '../store/plugin-fonts' import { scheduleRuntimeGraphSync } from '../runtime/sync-runtime-graph' import { useAppStore } from '../store' import { useDocumentDarkTheme, useSettingsDarkTheme } from '@/hooks/use-document-dark-theme' @@ -92,6 +93,7 @@ export function useDocumentAppearance(): void { const codeFontSmoothing = useAppStore((s) => s.settings?.codeFontSmoothing) const editorFontFamily = useAppStore((s) => s.settings?.editorFontFamily) usePluginIconThemeActivation(useAppStore((s) => s.settings?.pluginIconTheme)) + usePluginFontRegistration() const reduceEffects = useReduceVisualEffects(useAppStore((s) => s.settings?.reduceVisualEffects)) const surfaceOpacity = useAppStore((s) => s.settings?.terminalBackgroundOpacity ?? 1) // Why re-parse: the theme list keeps the registration as received, and a newer host may send diff --git a/src/renderer/src/components/dashboard-popout/AgentTerminalPreview.tsx b/src/renderer/src/components/dashboard-popout/AgentTerminalPreview.tsx index e72e06ce206..15d5799095b 100644 --- a/src/renderer/src/components/dashboard-popout/AgentTerminalPreview.tsx +++ b/src/renderer/src/components/dashboard-popout/AgentTerminalPreview.tsx @@ -18,6 +18,7 @@ import { terminalPreviewUnavailableMessage } from './terminal-preview-unavailabl import { resolveEffectiveTerminalAppearance } from '@/lib/terminal-theme' import { cn } from '@/lib/utils' import { useAppStore } from '@/store' +import { usePluginFontReady } from '@/store/plugin-fonts' import { createPreviewGridClaim } from './preview-grid-claim' import { createPreviewBoxFit } from './preview-terminal-box-fit' import { @@ -69,6 +70,7 @@ export function AgentTerminalPreview({ const linkSourceRef = useRef(linkSource) const browserForegroundRef = useRef(onBrowserForeground) const settings = useAppStore((state) => state.settings) + const terminalFontReady = usePluginFontReady(settings?.terminalFontFamily) const systemPrefersDark = useSystemPrefersDark() const macOptionAsAlt = useEffectiveMacOptionAsAlt(settings?.terminalMacOptionAsAlt) // Read live settings without terminal remount, PTY reconnect or snapshot repaint. @@ -358,7 +360,7 @@ export function AgentTerminalPreview({ buildPreviewAppearanceOptions(settings, macOptionAsAlt === 'true') ) syncPreviewTerminalLigatures(terminal, settings) - }, [settings, macOptionAsAlt]) + }, [settings, terminalFontReady, macOptionAsAlt]) return ( // Fix the box to the viewport so snapshot geometry cannot resize the dialog; fit/clip the true PTY frame at its cursor end. diff --git a/src/renderer/src/components/dashboard-popout/preview-terminal-options.ts b/src/renderer/src/components/dashboard-popout/preview-terminal-options.ts index 4a7b3bfbbe7..1e23a536a03 100644 --- a/src/renderer/src/components/dashboard-popout/preview-terminal-options.ts +++ b/src/renderer/src/components/dashboard-popout/preview-terminal-options.ts @@ -12,6 +12,7 @@ import { } from '@/lib/pane-manager/pane-terminal-options' import { buildLocalConptyTerminalOptions } from '@/lib/pane-manager/windows-pty-compatibility' import { buildFontFamily } from '@/lib/monospace-font-family' +import { pluginFontFamilyWhenLoaded } from '@/store/plugin-fonts' import { resolveTerminalMinimumContrastRatio } from '../../../../shared/terminal-themes/terminal-contrast-correction' /** Options a live settings change can write onto an open preview terminal. */ @@ -26,7 +27,7 @@ export function buildPreviewAppearanceOptions( ) return { fontSize: settings?.terminalFontSize ?? 14, - fontFamily: buildFontFamily(settings?.terminalFontFamily ?? ''), + fontFamily: buildFontFamily(pluginFontFamilyWhenLoaded(settings?.terminalFontFamily ?? '')), fontWeight: fontWeights.fontWeight, fontWeightBold: fontWeights.fontWeightBold, cursorStyle, diff --git a/src/renderer/src/components/plain-ssh-terminal/PlainSshTerminalView.tsx b/src/renderer/src/components/plain-ssh-terminal/PlainSshTerminalView.tsx index e21e03a08d2..86eb054a52d 100644 --- a/src/renderer/src/components/plain-ssh-terminal/PlainSshTerminalView.tsx +++ b/src/renderer/src/components/plain-ssh-terminal/PlainSshTerminalView.tsx @@ -21,6 +21,7 @@ import { } from '@/components/dashboard-popout/preview-terminal-options' import { openStandaloneTerminal } from '@/components/standalone-terminal/open-standalone-terminal' import { removePlainSshPanel } from '@/ssh/plain-ssh-terminal-panels' +import { usePluginFontReady } from '@/store/plugin-fonts' export type PlainSshTerminalPhase = | { kind: 'opening' } @@ -90,6 +91,7 @@ export function PlainSshTerminalView({ const terminalRef = useRef(null) const fitRef = useRef(null) const settings = useAppStore((s) => s.settings) + const terminalFontReady = usePluginFontReady(settings?.terminalFontFamily) const systemPrefersDark = useSystemPrefersDark() const macOptionAsAlt = useEffectiveMacOptionAsAlt(settings?.terminalMacOptionAsAlt) // Why refs: keys and appearance read live values; a remount would hang up the SSH session. @@ -302,7 +304,7 @@ export function PlainSshTerminalView({ if (!hidden && container && container.offsetWidth > 0 && container.offsetHeight > 0) { fitRef.current?.fit() } - }, [settings, systemPrefersDark, macOptionAsAlt, hidden]) + }, [settings, terminalFontReady, systemPrefersDark, macOptionAsAlt, hidden]) useEffect(() => { if (!hidden) { diff --git a/src/renderer/src/components/plugins/page/PluginAddsSection.tsx b/src/renderer/src/components/plugins/page/PluginAddsSection.tsx index aaa8ce3f161..60ef80f3f30 100644 --- a/src/renderer/src/components/plugins/page/PluginAddsSection.tsx +++ b/src/renderer/src/components/plugins/page/PluginAddsSection.tsx @@ -12,7 +12,8 @@ import { PanelRight, PenTool, Server, - SquareTerminal + SquareTerminal, + Type } from 'lucide-react' import type { PluginHostListEntry, @@ -101,6 +102,7 @@ const CONTRIBUTION_ICON: Record = { themes: , terminalThemes: , iconThemes: , + fonts: , syntaxes: , languagePacks: , panels: , @@ -253,10 +255,11 @@ function useContributionRowActions( } case 'themes': case 'terminalThemes': + case 'fonts': case 'customEditors': case 'vmRecipes': case 'statusBarItems': - // Themes have "Use now" above the list; editors open from their new files; recipes have nothing to try here. + // Themes have "Use now" above; fonts are picked in Settings; the rest has nothing to try here. return null } } diff --git a/src/renderer/src/components/plugins/presentation/plugin-contribution-row-labels.ts b/src/renderer/src/components/plugins/presentation/plugin-contribution-row-labels.ts index 125f39a46e0..745dddb5709 100644 --- a/src/renderer/src/components/plugins/presentation/plugin-contribution-row-labels.ts +++ b/src/renderer/src/components/plugins/presentation/plugin-contribution-row-labels.ts @@ -31,3 +31,17 @@ export function statusBarContributionRows(titles: readonly string[]): PluginCont tone: 'default' })) } + +export function fontContributionRows(families: readonly string[]): PluginContribution[] { + const detail = translate( + 'auto.components.settings.pluginContributions.font', + 'Font for the terminal, editor or interface' + ) + return families.map((title, index) => ({ + key: `fonts:${index}`, + kind: 'fonts', + title, + detail, + tone: 'default' + })) +} diff --git a/src/renderer/src/components/plugins/presentation/plugin-contributions.ts b/src/renderer/src/components/plugins/presentation/plugin-contributions.ts index bd43e43fcae..e2005562a6a 100644 --- a/src/renderer/src/components/plugins/presentation/plugin-contributions.ts +++ b/src/renderer/src/components/plugins/presentation/plugin-contributions.ts @@ -11,6 +11,7 @@ import { languageDisplayName } from '@/i18n/ui-intl-formatters' import { customEditorTakeover } from './plugin-custom-editor-takeover' import { fileList } from './plugin-contribution-file-list' import { + fontContributionRows, statusBarContributionRows, statusBarItemTitles, withMode @@ -37,6 +38,8 @@ export type PluginContributionSource = { themes: readonly { id: string; label: string; base?: 'light' | 'dark' }[] terminalThemes: readonly { id: string; label: string; mode?: 'light' | 'dark' | 'unknown' }[] iconThemes: readonly { id: string; label: string }[] + /** Family names as the manifest writes them. */ + fonts: readonly string[] syntaxes: readonly { id: string label: string @@ -63,6 +66,7 @@ export const EMPTY_CONTRIBUTION_SOURCE: PluginContributionSource = { themes: [], terminalThemes: [], iconThemes: [], + fonts: [], syntaxes: [], languagePacks: [], panels: [], @@ -93,6 +97,7 @@ export function manifestContributionSource(manifest: PluginManifest): PluginCont themes: contributes.themes.map(titled), terminalThemes: contributes.terminalThemes.map(titled), iconThemes: contributes.iconThemes.map(titled), + fonts: contributes.fonts.map((font) => font.family), syntaxes: contributes.syntaxes.map(titled), languagePacks: contributes.languagePacks, panels: contributes.panels.map((panel) => panel.title), @@ -127,6 +132,7 @@ export function summaryContributionSource( mode: base(item.name) })), iconThemes: of('iconThemes').map((item) => ({ id: item.name, label: item.name })), + fonts: of('fonts').map((item) => item.name), syntaxes: of('syntaxes').map((item) => ({ id: item.name, label: item.name, @@ -218,6 +224,7 @@ export function describePluginContributions( tone: 'default' }) } + rows.push(...fontContributionRows(source.fonts)) for (const syntax of source.syntaxes) { const files = fileList(syntax.extensions, syntax.filenames) const label = translate( diff --git a/src/renderer/src/components/plugins/state/use-plugin-contribution-source.ts b/src/renderer/src/components/plugins/state/use-plugin-contribution-source.ts index dc347b1f6ff..784d0952e60 100644 --- a/src/renderer/src/components/plugins/state/use-plugin-contribution-source.ts +++ b/src/renderer/src/components/plugins/state/use-plugin-contribution-source.ts @@ -42,6 +42,7 @@ function useInstalledPluginContributionSource( themes: ours(appThemes), terminalThemes: ours(terminalThemes), iconThemes: ours(iconThemes), + fonts: plugin.fonts?.map((font) => font.family) ?? [], syntaxes: ours(syntaxes).map((syntax) => ({ ...syntax, failed: Boolean(failures[pluginSyntaxRevisionKey(syntax)]) diff --git a/src/renderer/src/components/settings/appearance/fonts/font-suggestions.ts b/src/renderer/src/components/settings/appearance/fonts/font-suggestions.ts index 2ed5472fb39..c59cc78c41b 100644 --- a/src/renderer/src/components/settings/appearance/fonts/font-suggestions.ts +++ b/src/renderer/src/components/settings/appearance/fonts/font-suggestions.ts @@ -8,6 +8,21 @@ export function mergeFontSuggestions( return Array.from(new Set([DEFAULT_APP_FONT_FAMILY, ...systemFonts, ...previousFonts])) } +/** Plugin families right after the default font, ahead of the installed ones. */ +export function withPluginFontSuggestions( + suggestions: readonly string[], + pluginFamilies: readonly string[] +): string[] { + if (pluginFamilies.length === 0) { + return [...suggestions] + } + const [first, ...rest] = suggestions + const head = first === DEFAULT_APP_FONT_FAMILY ? [first] : [] + return Array.from( + new Set([...head, ...pluginFamilies, ...(head.length > 0 ? rest : suggestions)]) + ) +} + export function getFallbackTerminalFonts(): string[] { const nav = typeof navigator !== 'undefined' diff --git a/src/renderer/src/components/settings/page/use-settings-store-model.ts b/src/renderer/src/components/settings/page/use-settings-store-model.ts index b27a7b6edef..f43d1e0be0f 100644 --- a/src/renderer/src/components/settings/page/use-settings-store-model.ts +++ b/src/renderer/src/components/settings/page/use-settings-store-model.ts @@ -4,6 +4,7 @@ import type { ProjectHostSetup } from '../../../../../shared/project-types' import { DEFAULT_APP_FONT_FAMILY } from '../../../../../shared/constants' import { useAppStore } from '../../../store/index' import { useProjectHostSetupProjection } from '@/store/selectors' +import { usePluginFontFamilies } from '@/store/plugin-fonts' import { useSystemPrefersDark } from '@/hooks/theme/use-system-prefers-dark' import { isMacUserAgent, isWindowsUserAgent } from '@/lib/user-agent-platform' import { useConfirmationDialog } from '@/components/confirmation-dialog-context' @@ -23,7 +24,8 @@ import { useLinearProviderConnected } from '@/hooks/useLinearProviderConnected' import { useSkillFreshness } from '@/hooks/useSkillFreshness' import { getFallbackTerminalFonts, - mergeFontSuggestions + mergeFontSuggestions, + withPluginFontSuggestions } from '../appearance/fonts/font-suggestions' import { useTerminalConfigImport } from '../terminal/configuration/useTerminalConfigImport' import { useWarpThemeImport } from '../terminal/themes/useWarpThemeImport' @@ -139,9 +141,15 @@ export function useSettingsStoreModel() { // Keep import state above sections so remounts cannot close the modal. const terminalConfigImport = useTerminalConfigImport(updateSettings, settings) const warpThemes = useWarpThemeImport(updateSettings, settings) - const [fontSuggestions, setFontSuggestions] = useState( + const [installedFontSuggestions, setInstalledFontSuggestions] = useState( mergeFontSuggestions([], getFallbackTerminalFonts()) ) + const pluginFontFamilies = usePluginFontFamilies() + // Why after the default: plugin fonts are few and would otherwise sink into the installed list. + const fontSuggestions = useMemo( + () => withPluginFontSuggestions(installedFontSuggestions, pluginFontFamilies), + [installedFontSuggestions, pluginFontFamilies] + ) const terminalFontSuggestions = useMemo( () => fontSuggestions.filter((font) => font !== DEFAULT_APP_FONT_FAMILY), [fontSuggestions] @@ -243,7 +251,7 @@ export function useSettingsStoreModel() { terminalConfigImport, warpThemes, fontSuggestions, - setFontSuggestions, + setFontSuggestions: setInstalledFontSuggestions, terminalFontSuggestions, activeSectionId, setActiveSectionId, diff --git a/src/renderer/src/components/settings/terminal/appearance/TerminalSettingsPreview.lifecycle.test.tsx b/src/renderer/src/components/settings/terminal/appearance/TerminalSettingsPreview.lifecycle.test.tsx index a79215379c6..de65c670cd2 100644 --- a/src/renderer/src/components/settings/terminal/appearance/TerminalSettingsPreview.lifecycle.test.tsx +++ b/src/renderer/src/components/settings/terminal/appearance/TerminalSettingsPreview.lifecycle.test.tsx @@ -115,6 +115,11 @@ vi.mock('@/components/ui/card', () => ({ CardTitle: 'CardTitle' })) +vi.mock('@/store/plugin-fonts', () => ({ + pluginFontFamilyWhenLoaded: (fontFamily: string) => fontFamily, + usePluginFontReady: () => true +})) + vi.mock('@/lib/pane-manager/pane-terminal-options', () => ({ buildDefaultTerminalOptions: () => ({ scrollback: 0 }) })) diff --git a/src/renderer/src/components/settings/terminal/appearance/TerminalSettingsPreview.tsx b/src/renderer/src/components/settings/terminal/appearance/TerminalSettingsPreview.tsx index 657429bb833..ad939d0dab9 100644 --- a/src/renderer/src/components/settings/terminal/appearance/TerminalSettingsPreview.tsx +++ b/src/renderer/src/components/settings/terminal/appearance/TerminalSettingsPreview.tsx @@ -6,6 +6,7 @@ import '@xterm/xterm/css/xterm.css' import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card' import { buildDefaultTerminalOptions } from '@/lib/pane-manager/pane-terminal-options' import { buildFontFamily } from '@/lib/monospace-font-family' +import { pluginFontFamilyWhenLoaded, usePluginFontReady } from '@/store/plugin-fonts' import { composeActiveTerminalTheme } from '@/components/terminal-pane/appearance/terminal-appearance' import { clampNumber, resolveEffectiveTerminalAppearance } from '@/lib/terminal-theme' import { resolveTerminalMinimumContrastRatio } from '../../../../../../shared/terminal-themes/terminal-contrast-correction' @@ -65,6 +66,7 @@ export function TerminalSettingsPreview({ const skipInitialThemeRewriteRef = useRef(false) const effectiveFontFamily = previewFontFamily || settings.terminalFontFamily + const fontReady = usePluginFontReady(effectiveFontFamily) const terminalLineHeight = normalizeTerminalLineHeight(settings.terminalLineHeight) // Seed from app theme once; preview toggles remain independent afterward. @@ -127,7 +129,7 @@ export function TerminalSettingsPreview({ cursorStyle: settings.terminalCursorStyle, cursorBlink: settings.terminalCursorBlink, fontSize: settings.terminalFontSize, - fontFamily: buildFontFamily(effectiveFontFamily), + fontFamily: buildFontFamily(pluginFontFamilyWhenLoaded(effectiveFontFamily)), fontWeight: weights.fontWeight, fontWeightBold: weights.fontWeightBold, lineHeight: terminalLineHeight, @@ -173,7 +175,7 @@ export function TerminalSettingsPreview({ settings.terminalFontWeightBold ) terminal.options.fontSize = settings.terminalFontSize - terminal.options.fontFamily = buildFontFamily(effectiveFontFamily) + terminal.options.fontFamily = buildFontFamily(pluginFontFamilyWhenLoaded(effectiveFontFamily)) terminal.options.fontWeight = weights.fontWeight terminal.options.fontWeightBold = weights.fontWeightBold terminal.options.lineHeight = terminalLineHeight @@ -185,6 +187,7 @@ export function TerminalSettingsPreview({ settings.terminalFontSize, settings.terminalFontWeightBold, effectiveFontFamily, + fontReady, settings.terminalFontWeight, terminalLineHeight, settings.terminalCursorStyle, diff --git a/src/renderer/src/components/terminal-pane/appearance/terminal-appearance.ts b/src/renderer/src/components/terminal-pane/appearance/terminal-appearance.ts index 3c3d03bd436..10be484afea 100644 --- a/src/renderer/src/components/terminal-pane/appearance/terminal-appearance.ts +++ b/src/renderer/src/components/terminal-pane/appearance/terminal-appearance.ts @@ -5,6 +5,7 @@ import { resolveTerminalFontWeights } from '../../../../../shared/terminal/appea import { resolveTerminalLigaturesEnabled } from '../../../../../shared/terminal/appearance/terminal-ligatures' import { resolvePaneStyleOptions, resolveEffectiveTerminalAppearance } from '@/lib/terminal-theme' import { buildFontFamily } from '@/lib/monospace-font-family' +import { pluginFontFamilyWhenLoaded } from '@/store/plugin-fonts' import '@/lib/pane-manager/pane-tree-ops' import { safeFit, safeFitAndThen } from '@/lib/pane-manager/pane-fit' @@ -216,7 +217,7 @@ export function applyTerminalAppearance( const paneSize = getTerminalFontSizeOverride(pane.leafId) const metricOptions = { fontSize: paneSize ?? settings.terminalFontSize, - fontFamily: buildFontFamily(settings.terminalFontFamily), + fontFamily: buildFontFamily(pluginFontFamilyWhenLoaded(settings.terminalFontFamily)), fontWeight: terminalFontWeights.fontWeight, fontWeightBold: terminalFontWeights.fontWeightBold, lineHeight: normalizeTerminalLineHeight(settings.terminalLineHeight) diff --git a/src/renderer/src/components/terminal-pane/appearance/use-mounted-terminal-appearance.ts b/src/renderer/src/components/terminal-pane/appearance/use-mounted-terminal-appearance.ts index 4fd49968adc..7d039ab8ebd 100644 --- a/src/renderer/src/components/terminal-pane/appearance/use-mounted-terminal-appearance.ts +++ b/src/renderer/src/components/terminal-pane/appearance/use-mounted-terminal-appearance.ts @@ -1,6 +1,7 @@ import { useEffect } from 'react' import { applyTerminalAppearance } from './terminal-appearance' import { useThemeBackgroundStore } from '@/store/theme-background' +import { usePluginFontReady } from '@/store/plugin-fonts' import type { UseTerminalPaneLifecycleDeps } from '../mounting/terminal-pane-lifecycle-types' import type { TerminalPaneLifecycleRefs } from '../mounting/use-terminal-pane-lifecycle-refs' @@ -21,6 +22,8 @@ export function useMountedTerminalAppearance( ): void { // Why: a theme image arrives after plugin themes load, so the single-paint switch must re-run then. const themeBackgroundActive = useThemeBackgroundStore((state) => state.active) + // Why: a plugin terminal font joins the font list only once it loads, so cells re-measure then. + const terminalFontReady = usePluginFontReady(deps.settings?.terminalFontFamily) useEffect(() => { const manager = deps.managerRef.current const currentSettings = deps.settingsRef.current @@ -39,6 +42,7 @@ export function useMountedTerminalAppearance( }, [ deps.settings, themeBackgroundActive, + terminalFontReady, deps.systemPrefersDark, deps.effectiveMacOptionAsAlt, deps.managerRef, diff --git a/src/renderer/src/components/terminal-pane/mounting/terminal-pane-manager-options.ts b/src/renderer/src/components/terminal-pane/mounting/terminal-pane-manager-options.ts index 75442d90a65..9e359b3187f 100644 --- a/src/renderer/src/components/terminal-pane/mounting/terminal-pane-manager-options.ts +++ b/src/renderer/src/components/terminal-pane/mounting/terminal-pane-manager-options.ts @@ -14,6 +14,7 @@ import { resolveTerminalScrollOnUserInput } from '@/lib/pane-manager/pane-terminal-options' import { buildFontFamily } from '@/lib/monospace-font-family' +import { pluginFontFamilyWhenLoaded } from '@/store/plugin-fonts' import { buildWindowsPtyCompatibilityOptions } from '@/lib/pane-manager/windows-pty-compatibility' import { buildTerminalKeyboardProtocolOptions } from '@/lib/pane-manager/terminal-keyboard-protocol' import { resolvePaneKeyboardProtocolAgent } from '../input/keyboard/terminal-keyboard-protocol-pane-agent' @@ -149,7 +150,9 @@ export function createTerminalPaneManagerOptions( ...buildWindowsPtyCompatibilityOptions(ptyBackendContext), ...buildTerminalKeyboardProtocolOptions(ptyBackendContext), fontSize: currentSettings?.terminalFontSize ?? 14, - fontFamily: buildFontFamily(currentSettings?.terminalFontFamily ?? ''), + fontFamily: buildFontFamily( + pluginFontFamilyWhenLoaded(currentSettings?.terminalFontFamily ?? '') + ), fontWeight: terminalFontWeights.fontWeight, fontWeightBold: terminalFontWeights.fontWeightBold, scrollback: normalizeDesktopTerminalScrollbackRows(currentSettings?.terminalScrollbackRows), diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index d3449ef4dcf..851a7e63654 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -13569,7 +13569,8 @@ "newFileMenu": "Adds to the + menu", "editorReplacesViewer": "Opens {{value0}} instead of Orca’s viewer", "editorMayReplaceViewer": "May open {{value0}} instead of Orca’s viewer", - "statusBar": "Status bar" + "statusBar": "Status bar", + "font": "Font for the terminal, editor or interface" }, "PluginCardAction": { "installed": "Installed", diff --git a/src/renderer/src/lib/monaco-setup.ts b/src/renderer/src/lib/monaco-setup.ts index 160f7ddd9ee..9622b7bd010 100644 --- a/src/renderer/src/lib/monaco-setup.ts +++ b/src/renderer/src/lib/monaco-setup.ts @@ -31,6 +31,7 @@ import { installMonacoPeekReferencesPreviewOptions } from './monaco-peek-preview import { installMonacoContextMenuPaste } from '@/components/editor/install-monaco-context-menu-paste' import { runMonacoSetupSteps } from './monaco-setup-steps' import { installMonacoTsWorkerIdleStop } from './monaco-ts-worker-idle-stop' +import { onPluginFontLoadsChanged } from '@/store/plugin-fonts' globalThis.MonacoEnvironment = { getWorker(_workerId, label) { @@ -96,7 +97,9 @@ runMonacoSetupSteps([ ['peek references preview options', installMonacoPeekReferencesPreviewOptions], // Sandboxed navigator.clipboard blocks Monaco Paste; use trusted IPC as native Cmd+V does. ['context-menu paste', () => installMonacoContextMenuPaste(monaco)], - ['TS worker idle stop', () => installMonacoTsWorkerIdleStop(monaco)] + ['TS worker idle stop', () => installMonacoTsWorkerIdleStop(monaco)], + // Monaco caches glyph widths, so a plugin font that loads after first paint must re-measure. + ['plugin font remeasure', () => onPluginFontLoadsChanged(() => monaco.editor.remeasureFonts())] ]) loader.config({ monaco }) diff --git a/src/renderer/src/lib/monospace-font-family.ts b/src/renderer/src/lib/monospace-font-family.ts index 930cf0b069e..2c10df0700d 100644 --- a/src/renderer/src/lib/monospace-font-family.ts +++ b/src/renderer/src/lib/monospace-font-family.ts @@ -1,3 +1,5 @@ +import { isPluginFontFamilyName } from '../../../shared/plugins/contributions/plugin-font-contribution' + export const BUNDLED_SYMBOLS_FONT_FAMILY = 'Orca Nerd Font Symbols' // Cross-platform monospace chain: browsers skip fonts absent on the current OS, so listing all is safe. @@ -22,9 +24,11 @@ export function buildFontFamily(fontFamily: string): string { const trimmed = fontFamily.trim() const parts = trimmed ? [`"${trimmed}"`] : [] const lowerParts = parts.map((p) => p.toLowerCase()) + // Why: a plugin family such as "Menlo (acme.fonts)" is never a fallback, so it must keep all of them. + const isPluginFamily = isPluginFontFamilyName(trimmed) for (const fallback of FALLBACK_FONTS) { const lower = fallback.toLowerCase() - if (!lowerParts.some((p) => p.includes(lower))) { + if (isPluginFamily || !lowerParts.some((p) => p.includes(lower))) { // Generic keywords like "monospace" are unquoted; named fonts are quoted. parts.push(fallback === 'monospace' ? fallback : `"${fallback}"`) } diff --git a/src/renderer/src/store/plugin-fonts.ts b/src/renderer/src/store/plugin-fonts.ts new file mode 100644 index 00000000000..824d60687d2 --- /dev/null +++ b/src/renderer/src/store/plugin-fonts.ts @@ -0,0 +1,202 @@ +import { useEffect } from 'react' +import { create } from 'zustand' +import type { PluginHostListEntry } from '../../../preload/api-types' +import { + isPluginFontFamilyLabel, + isPluginFontFamilyName, + isPluginFontWeight, + parsePluginFontSlot, + pluginFontFamilyName +} from '../../../shared/plugins/contributions/plugin-font-contribution' +import { parsePluginImageUrl } from '../../../shared/plugins/images/plugin-image-url' +import { isWebClientLocation } from '@/lib/web-client-location' +import { isLivePlugin, usePluginListDerived } from './plugin-panels' + +type PluginFontFace = { url: string; weight: string; style: 'normal' | 'italic' } + +/** A font family from an enabled plugin, under the name Orca registers it as. */ +export type ActivePluginFont = { family: string; faces: PluginFontFace[] } + +/** Only URLs main serves for this plugin's own font slots, with the manifest's own rules. */ +function isServedFace(face: PluginFontFace, pluginKey: string): boolean { + const reference = parsePluginImageUrl(face.url) + return ( + reference?.kind === 'installed' && + reference.pluginKey === pluginKey && + parsePluginFontSlot(reference.slot) !== null && + isPluginFontWeight(face.weight) && + (face.style === 'normal' || face.style === 'italic') + ) +} + +export function collectActivePluginFonts( + plugins: readonly PluginHostListEntry[] +): ActivePluginFont[] { + // Why desktop only: a web client cannot load the scheme main serves fonts from. + if (isWebClientLocation()) { + return [] + } + return plugins.filter(isLivePlugin).flatMap((plugin) => + (plugin.fonts ?? []).flatMap((font) => { + const faces = font.faces.filter((face) => isServedFace(face, plugin.pluginKey)) + return isPluginFontFamilyLabel(font.family) && faces.length > 0 + ? [{ family: pluginFontFamilyName(plugin.pluginKey, font.family), faces }] + : [] + }) + ) +} + +const collectFamilies = (plugins: readonly PluginHostListEntry[]): string[] => + collectActivePluginFonts(plugins).map((font) => font.family) + +/** Families of enabled plugins' fonts, for the font pickers. */ +export function usePluginFontFamilies(): string[] { + return usePluginListDerived(collectFamilies) +} + +// Why a store: xterm and the code editor measure glyphs once per font change, so both re-measure +// when a plugin family finishes loading. Keys are lowercase, as CSS matches families. +export const usePluginFontLoadStore = create<{ loaded: ReadonlySet }>()(() => ({ + loaded: new Set() +})) + +const familyKey = (fontFamily: string): string => fontFamily.trim().toLowerCase() +const registered = new Map() +const familyByFace = new WeakMap() +const wantedFamilies = new Set() +let watchingLoads = false + +function setFamilyLoaded(family: string, loaded: boolean): void { + const current = usePluginFontLoadStore.getState().loaded + if (current.has(family) === loaded) { + return + } + const next = new Set(current) + if (loaded) { + next.add(family) + } else { + next.delete(family) + } + usePluginFontLoadStore.setState({ loaded: next }) +} + +// Why the document event: a face also loads when the editor or interface first draws with it. +function watchFontLoads(): void { + if (watchingLoads) { + return + } + watchingLoads = true + document.fonts.addEventListener('loadingdone', (event) => { + for (const face of event.fontfaces) { + const family = familyByFace.get(face) + if (family && facesOf(family).includes(face)) { + setFamilyLoaded(family, true) + } + } + }) +} + +function facesOf(family: string): FontFace[] { + return [...registered.values()].filter((entry) => entry.family === family).map((e) => e.face) +} + +function loadFamily(family: string): void { + const faces = facesOf(family) + void Promise.allSettled(faces.map((face) => face.load())).then((results) => { + if (results.some((result) => result.status === 'fulfilled')) { + if (facesOf(family).some((face) => faces.includes(face))) { + setFamilyLoaded(family, true) + } + } else if (faces.length > 0) { + // The renderer's font sanitizer refused the files; the setting keeps its fallback. + console.warn(`[plugins] font "${family}" failed to load`) + } + }) +} + +/** Registers enabled plugins' faces and removes those of disabled or uninstalled ones. Faces + * load only when text uses them, so registering costs nothing until a font is picked. */ +export function syncPluginFontFaces(fonts: readonly ActivePluginFont[]): void { + if (typeof document === 'undefined' || !document.fonts) { + return + } + const next = new Map() + for (const font of fonts) { + for (const face of font.faces) { + const key = [font.family, face.url, face.weight, face.style].join('\u0000') + next.set(key, { family: familyKey(font.family), name: font.family, face }) + } + } + const changedFamilies = new Set() + for (const [key, entry] of registered) { + if (!next.has(key)) { + document.fonts.delete(entry.face) + registered.delete(key) + changedFamilies.add(entry.family) + } + } + for (const [key, { family, name, face }] of next) { + if (registered.has(key)) { + continue + } + watchFontLoads() + // Why a quoted URL: it is a CSS string, so no URL can break out of it. The family is taken + // literally, never parsed as CSS. + const fontFace = new FontFace(name, `url(${JSON.stringify(face.url)})`, { + weight: face.weight, + style: face.style, + display: 'swap' + }) + document.fonts.add(fontFace) + registered.set(key, { family, face: fontFace }) + familyByFace.set(fontFace, family) + changedFamilies.add(family) + } + for (const family of changedFamilies) { + const loaded = facesOf(family).some((face) => face.status === 'loaded') + setFamilyLoaded(family, loaded) + if (!loaded && wantedFamilies.has(family)) { + loadFamily(family) + } + } +} + +/** `fontFamily` once it is safe to measure: a plugin family that has not loaded yet is left out + * (and starts loading), so a terminal never sizes its cells with a fallback's metrics. */ +export function pluginFontFamilyWhenLoaded(fontFamily: string): string { + if (!isPluginFontFamilyName(fontFamily)) { + return fontFamily + } + const family = familyKey(fontFamily) + if (usePluginFontLoadStore.getState().loaded.has(family)) { + return fontFamily + } + if (!wantedFamilies.has(family)) { + wantedFamilies.add(family) + loadFamily(family) + } + return '' +} + +/** Changes when `fontFamily`, if it is a plugin family, loads or goes away; constant otherwise. */ +export function usePluginFontReady(fontFamily: string | undefined): boolean { + return usePluginFontLoadStore( + (state) => + !fontFamily || !isPluginFontFamilyName(fontFamily) || state.loaded.has(familyKey(fontFamily)) + ) +} + +/** Calls `listener` whenever a plugin family loads or goes away. */ +export function onPluginFontLoadsChanged(listener: () => void): () => void { + return usePluginFontLoadStore.subscribe((state, previous) => { + if (state.loaded !== previous.loaded) { + listener() + } + }) +} + +/** Keeps the document's plugin font faces in step with the enabled plugins. */ +export function usePluginFontRegistration(): void { + const fonts = usePluginListDerived(collectActivePluginFonts) + useEffect(() => syncPluginFontFaces(fonts), [fonts]) +} diff --git a/src/shared/plugin-font-settings.ts b/src/shared/plugin-font-settings.ts new file mode 100644 index 00000000000..032a1d6198f --- /dev/null +++ b/src/shared/plugin-font-settings.ts @@ -0,0 +1,30 @@ +import type { GlobalSettings } from './global-settings-types' +import { DEFAULT_APP_FONT_FAMILY } from './constants' +import { isPluginFontFamilyOf } from './plugins/contributions/plugin-font-contribution' +import { defaultTerminalFontFamily } from './terminal/appearance/terminal-platform-defaults' + +/** Font choices that named a removed plugin's family go back to their defaults. */ +export function pluginFontSettingsAfterRemoval( + settings: Pick< + GlobalSettings, + 'appFontFamily' | 'terminalFontFamily' | 'editorFontFamily' | 'nativeChatAppearance' + >, + pluginKey: string +): Partial { + const update: Partial = {} + if (isPluginFontFamilyOf(settings.appFontFamily, pluginKey)) { + update.appFontFamily = DEFAULT_APP_FONT_FAMILY + } + if (isPluginFontFamilyOf(settings.terminalFontFamily, pluginKey)) { + update.terminalFontFamily = defaultTerminalFontFamily() + } + if (isPluginFontFamilyOf(settings.editorFontFamily, pluginKey)) { + update.editorFontFamily = '' + } + const chat = settings.nativeChatAppearance + if (chat && isPluginFontFamilyOf(chat.fontFamily, pluginKey)) { + const { fontFamily: _removed, ...rest } = chat + update.nativeChatAppearance = rest + } + return update +} diff --git a/src/shared/plugins/contributions/plugin-contribution-points.ts b/src/shared/plugins/contributions/plugin-contribution-points.ts index aba0155e67e..0f34d6ef0fb 100644 --- a/src/shared/plugins/contributions/plugin-contribution-points.ts +++ b/src/shared/plugins/contributions/plugin-contribution-points.ts @@ -23,6 +23,11 @@ import { pluginEventContributionSchema } from './plugin-event-contribution' import { PLUGIN_HOOK_LIMIT, pluginHookContributionSchema } from './plugin-hook-contribution' +import { + PLUGIN_FONT_LIMIT, + PLUGIN_FONTS_SINCE, + pluginFontContributionSchema +} from './plugin-font-contribution' import type { PluginExecutionProfile } from './plugin-execution-profile' import { PLUGIN_CUSTOM_EDITOR_LIMIT, @@ -62,6 +67,7 @@ export const PLUGIN_CONTRIBUTION_POINTS = [ 'themes', 'terminalThemes', 'iconThemes', + 'fonts', 'syntaxes', 'customEditors', 'newFiles', @@ -193,6 +199,12 @@ export const pluginContributesFields = { 'File icon themes.', NEXT ), + fonts: contributionList( + pluginFontContributionSchema, + PLUGIN_FONT_LIMIT, + 'Font families for the terminal, editor and interface font pickers.', + PLUGIN_FONTS_SINCE + ), syntaxes: contributionList( pluginSyntaxContributionSchema, PLUGIN_SYNTAX_LIMIT, @@ -261,6 +273,8 @@ export const PLUGIN_CONTRIBUTION_POINT_POLICY: Record< themes: { execution: 'data', catalogType: 'app-theme', bindsContent: false }, terminalThemes: { execution: 'data', catalogType: 'terminal-theme', bindsContent: false }, iconThemes: { execution: 'data', catalogType: 'icon-theme', bindsContent: false }, + // Why no catalog type: older catalogs would drop a release naming one, and a font is inert data. + fonts: { execution: 'data', catalogType: null, bindsContent: false }, syntaxes: { execution: 'data', catalogType: 'syntax', bindsContent: false }, customEditors: { execution: 'sandboxed-ui', catalogType: 'editor', bindsContent: false }, // Why data and no catalog type: a template is inert text that seeds a file the user asked for; diff --git a/src/shared/plugins/contributions/plugin-contribution-summary.ts b/src/shared/plugins/contributions/plugin-contribution-summary.ts index ef8d30d8623..dcce645775b 100644 --- a/src/shared/plugins/contributions/plugin-contribution-summary.ts +++ b/src/shared/plugins/contributions/plugin-contribution-summary.ts @@ -83,6 +83,7 @@ export function pluginContributionSummary( ...named('themes', c.themes, (theme) => theme.title), ...named('terminalThemes', c.terminalThemes, (theme) => theme.title), ...named('iconThemes', c.iconThemes, (theme) => theme.title), + ...named('fonts', c.fonts, (font) => font.family), ...named('syntaxes', c.syntaxes, (syntax) => syntax.title, fileMatchDetail), ...named('customEditors', c.customEditors, (editor) => editor.title, fileMatchDetail), ...named( diff --git a/src/shared/plugins/contributions/plugin-font-contribution.ts b/src/shared/plugins/contributions/plugin-font-contribution.ts new file mode 100644 index 00000000000..932f41a8b96 --- /dev/null +++ b/src/shared/plugins/contributions/plugin-font-contribution.ts @@ -0,0 +1,163 @@ +import { z } from 'zod' +import { pluginRelativePathSchema } from '../manifest/plugin-manifest-fields' +import { pluginFieldDoc, pluginPathFieldDoc } from '../manifest/plugin-schema-field-docs' + +/** First release that registers `contributes.fonts`. */ +export const PLUGIN_FONTS_SINCE = '1.4.253' +const SINCE = PLUGIN_FONTS_SINCE + +// Why these caps: a family is regular/bold/italic/bold-italic, or one or two variable files; a +// Latin WOFF2 face is 20-300 KB and a symbol-patched monospace face about 1.2 MB. +export const PLUGIN_FONT_LIMIT = 8 +export const PLUGIN_FONT_FACE_LIMIT = 8 +export const PLUGIN_FONT_FILE_MAX_BYTES = 2 * 1024 * 1024 +export const PLUGIN_FONTS_TOTAL_MAX_BYTES = 8 * 1024 * 1024 + +export type PluginFontFormat = 'woff' | 'woff2' + +export const PLUGIN_FONT_MIME: Record = { + woff: 'font/woff', + woff2: 'font/woff2' +} + +// Why WOFF only: they are the web formats, and the renderer's font loader sanitizes every web +// font before parsing. TTF, OTF and collections add nothing a plugin cannot convert to WOFF2. +const FONT_SIGNATURES: Record = { + woff: [0x77, 0x4f, 0x46, 0x46], // wOFF + woff2: [0x77, 0x4f, 0x46, 0x32] // wOF2 +} +// The wrapped font's flavor (bytes 4-7): TrueType or CFF. A collection (`ttcf`) is refused. +const FONT_FLAVORS: readonly (readonly number[])[] = [ + [0x00, 0x01, 0x00, 0x00], + [0x4f, 0x54, 0x54, 0x4f], // OTTO + [0x74, 0x72, 0x75, 0x65] // true +] + +/** The format a file's extension claims, or null when it is not a web font. */ +function claimedFontFormat(path: string): PluginFontFormat | null { + const lower = path.toLowerCase() + return lower.endsWith('.woff2') ? 'woff2' : lower.endsWith('.woff') ? 'woff' : null +} + +/** Its format when the extension, signature and flavor agree; nothing past byte 8 is read. */ +export function pluginFontFormat(path: string, bytes: Uint8Array): PluginFontFormat | null { + const format = claimedFontFormat(path) + const flavorOk = FONT_FLAVORS.some((flavor) => + flavor.every((value, index) => bytes[4 + index] === value) + ) + return format && + flavorOk && + FONT_SIGNATURES[format].every((value, index) => bytes[index] === value) + ? format + : null +} + +// Why ASCII and no quotes, commas or parentheses: the name lands inside a quoted CSS font-family +// list, and look-alike letters must not pass for an installed font in the picker. +const FONT_FAMILY_RE = /^[A-Za-z0-9](?:[A-Za-z0-9 _.-]{0,46}[A-Za-z0-9])?$/ +const FONT_WEIGHT_RE = /^(?:[1-9]\d{0,2}|1000)(?: (?:[1-9]\d{0,2}|1000))?$/ + +const pluginFontFaceSchema = z + .object({ + path: pluginRelativePathSchema + .regex(/\.woff2?$/i, 'must be a .woff or .woff2 file') + .meta( + pluginPathFieldDoc( + `WOFF or WOFF2 file, at most ${PLUGIN_FONT_FILE_MAX_BYTES / 1024 / 1024} MB; its first bytes must match its extension. TTF, OTF and font collections are refused.`, + SINCE, + ['fonts/Geist-Variable.woff2'] + ) + ), + weight: z + .string() + .regex(FONT_WEIGHT_RE, 'must be a weight from 1 to 1000, or a range such as "100 900"') + .refine((value) => { + const [low, high = low] = value.split(' ').map(Number) + return low <= high + }, 'must list the lower weight first') + .optional() + .meta( + pluginFieldDoc( + 'CSS weight this file draws, or a range for a variable font. Defaults to `400`.', + SINCE, + ['400', '100 900'] + ) + ), + style: z + .enum(['normal', 'italic']) + .optional() + .meta(pluginFieldDoc('Whether this file is the italic face. Defaults to `normal`.', SINCE)) + }) + .strict() + .meta({ id: 'FontFaceContribution', description: 'One file of a font family.' }) + +export const pluginFontContributionSchema = z + .object({ + family: z + .string() + .regex( + FONT_FAMILY_RE, + 'must be 1-48 ASCII letters, digits, spaces, dots, dashes or underscores' + ) + .meta( + pluginFieldDoc( + 'Family name shown in the font pickers. Orca adds the plugin id, so a plugin font never replaces an installed or built-in font of the same name.', + SINCE, + ['Geist'] + ) + ), + faces: z + .array(pluginFontFaceSchema) + .min(1) + .max(PLUGIN_FONT_FACE_LIMIT) + .meta( + pluginFieldDoc( + `The family's files, at most ${PLUGIN_FONT_FACE_LIMIT}. All of a plugin's font files together may be at most ${PLUGIN_FONTS_TOTAL_MAX_BYTES / 1024 / 1024} MB.`, + SINCE + ) + ) + }) + .strict() + .meta({ + id: 'FontContribution', + description: + 'A font family the user can pick for the terminal, editor or interface. It applies only once picked.' + }) + +export type PluginFontContribution = z.infer + +/** For clients re-checking a host's list: the same rules the manifest enforces. */ +export function isPluginFontFamilyLabel(family: string): boolean { + return FONT_FAMILY_RE.test(family) +} + +export function isPluginFontWeight(weight: string): boolean { + return FONT_WEIGHT_RE.test(weight) +} + +/** The CSS family Orca registers: the plugin key keeps it from matching any other font. */ +export function pluginFontFamilyName(pluginKey: string, family: string): string { + return `${family} (${pluginKey})` +} + +/** True when `fontFamily` is a family the plugin registers, so its removal can reset the choice. */ +export function isPluginFontFamilyOf(fontFamily: string | undefined, pluginKey: string): boolean { + return fontFamily?.trim().toLowerCase().endsWith(` (${pluginKey})`) === true +} + +/** True when `fontFamily` has the shape `pluginFontFamilyName` gives, whichever plugin it names. */ +export function isPluginFontFamilyName(fontFamily: string): boolean { + return / \([a-z0-9-]+\.[a-z0-9-]+\)$/i.test(fontFamily.trim()) +} + +/** The image-protocol slot of one font file: `font--`. */ +export function pluginFontSlot(familyIndex: number, faceIndex: number): string { + return `font-${familyIndex}-${faceIndex}` +} + +export function parsePluginFontSlot( + slot: string +): { familyIndex: number; faceIndex: number } | null { + const match = /^font-(\d)-(\d)$/.exec(slot) + return match ? { familyIndex: Number(match[1]), faceIndex: Number(match[2]) } : null +} diff --git a/src/shared/plugins/images/plugin-image-url.ts b/src/shared/plugins/images/plugin-image-url.ts index d44e0c1a21b..2a8b5d2a272 100644 --- a/src/shared/plugins/images/plugin-image-url.ts +++ b/src/shared/plugins/images/plugin-image-url.ts @@ -21,7 +21,8 @@ export function pluginShaImageUrl(sha256: string): string { } /** `slot` is `icon`, `cover`, `screenshot-`, a contribution's icon: `editor-` - * (custom editors) or `new-file-` (new files), or an app theme's background: `theme-`. */ + * (custom editors) or `new-file-` (new files), an app theme's background: `theme-`, + * or a font file: `font--`. */ export function pluginInstalledImageUrl( pluginKey: string, contentHash: string, @@ -52,7 +53,9 @@ export function parsePluginImageUrl(url: string): PluginImageReference | null { contentHash && slot && /^(?:[0-9a-f]{64}|[0-9a-f]{32}|dev)$/.test(contentHash) && - /^(?:icon|cover|(?:screenshot|editor|new-file)-\d{1,2}|theme-(?:0|[1-9]\d{0,2}))$/.test(slot) + /^(?:icon|cover|(?:screenshot|editor|new-file)-\d{1,2}|theme-(?:0|[1-9]\d{0,2})|font-\d-\d)$/.test( + slot + ) ) { return { kind: 'installed', pluginKey: decodeURIComponent(key), contentHash, slot } } diff --git a/src/shared/plugins/installation/plugin-host-version.ts b/src/shared/plugins/installation/plugin-host-version.ts index f422f32b906..602b24b23da 100644 --- a/src/shared/plugins/installation/plugin-host-version.ts +++ b/src/shared/plugins/installation/plugin-host-version.ts @@ -13,6 +13,7 @@ import { import { PLUGIN_STATUS_BAR_SINCE } from '../contributions/plugin-status-bar-item-contribution' import { PLUGIN_COMMAND_REPLACES_SINCE } from '../contributions/plugin-command-contribution' import { PLUGIN_APPEARANCE_SINCE } from '../workers/plugin-host-api-appearance' +import { PLUGIN_FONTS_SINCE } from '../contributions/plugin-font-contribution' /** The newest "since" this build's schemas cite: everything up to it is readable here. */ export const PLUGIN_SCHEMA_NEWEST_SINCE = [ @@ -28,7 +29,8 @@ export const PLUGIN_SCHEMA_NEWEST_SINCE = [ PLUGIN_HOOKS_SINCE, PLUGIN_HOST_ACTIONS_SINCE, PLUGIN_COMMAND_REPLACES_SINCE, - PLUGIN_APPEARANCE_SINCE + PLUGIN_APPEARANCE_SINCE, + PLUGIN_FONTS_SINCE ].reduce((newest, version) => (satisfiesOrcaEngineRange(version, `>=${newest}`) ? version : newest)) /** diff --git a/src/shared/plugins/manifest/plugin-manifest-contribution-validation.ts b/src/shared/plugins/manifest/plugin-manifest-contribution-validation.ts index fb696393aaa..d640c514b1c 100644 --- a/src/shared/plugins/manifest/plugin-manifest-contribution-validation.ts +++ b/src/shared/plugins/manifest/plugin-manifest-contribution-validation.ts @@ -28,6 +28,7 @@ type ContributionValidationManifest = { themes: IdentifiedContribution[] terminalThemes: IdentifiedContribution[] iconThemes: IdentifiedContribution[] + fonts: { family: string }[] syntaxes: (IdentifiedContribution & PluginFileMatch & { scopeName: string })[] customEditors: (IdentifiedContribution & PluginFileMatch)[] newFiles: IdentifiedContribution[] @@ -117,6 +118,13 @@ export function validatePluginManifestContributions( 'language pack locale', ctx ) + rejectDuplicateValues( + manifest.contributes.fonts.map((font) => font.family.toLowerCase()), + String, + 'fonts', + 'font family', + ctx + ) rejectDuplicateValues( manifest.contributes.settings.map((setting) => setting.key), String, diff --git a/src/shared/plugins/plugin-list-entry.ts b/src/shared/plugins/plugin-list-entry.ts index 36f12a993d6..d08d48106d8 100644 --- a/src/shared/plugins/plugin-list-entry.ts +++ b/src/shared/plugins/plugin-list-entry.ts @@ -47,6 +47,17 @@ export type PluginHostNewFile = { icon?: string } +export type PluginHostFont = { + /** The manifest's family name; clients register it as `pluginFontFamilyName`. */ + family: string + faces: { + /** orca-plugin-image URL main serves while the plugin is enabled. */ + url: string + weight: string + style: 'normal' | 'italic' + }[] +} + export type PluginHostListEntry = { pluginKey: string consentFingerprint: string | null @@ -80,6 +91,8 @@ export type PluginHostListEntry = { customEditors?: PluginHostCustomEditor[] /** Absent on hosts that predate new-file templates. */ newFiles?: PluginHostNewFile[] + /** Absent on hosts that predate plugin fonts. */ + fonts?: PluginHostFont[] commands: { id: string title: string