From f11cd361a714463ca4891127f2263f820b85cd7d Mon Sep 17 00:00:00 2001 From: Vadim Lazuk Date: Wed, 11 Nov 2026 16:23:38 +0300 Subject: [PATCH] fix(color-scheme): import .xml scheme files and tolerate real-world IDEA variants (#2731) The import chooser only offered .icls, so schemes distributed as .xml (Material Theme UI) could not be picked. It now offers .xml too, and the parser accepts a BOM, an encoding declaration, a DOCTYPE, a scheme wrapped in a settings export and a scheme without a name (named after its file); a rejected file shows the reason. Fixes #2714 Co-authored-by: Inf1mum <8135225+Inf1mum@users.noreply.github.com> --- .../settings/__tests__/colorScheme.test.tsx | 32 ++++++- .../settings/pages/editor/colorScheme.tsx | 19 ++-- .../__fixtures__/colorSchemes/bom-utf8.icls | 7 ++ .../colorSchemes/declared-encoding.icls | 9 ++ .../colorSchemes/material-darker.xml | 89 +++++++++++++++++++ .../colorSchemes/one-dark-wrapped.xml | 11 +++ src/platform/icls.test.ts | 74 ++++++++++++--- src/platform/icls.ts | 51 ++++++++--- 8 files changed, 261 insertions(+), 31 deletions(-) create mode 100644 src/platform/__fixtures__/colorSchemes/bom-utf8.icls create mode 100644 src/platform/__fixtures__/colorSchemes/declared-encoding.icls create mode 100644 src/platform/__fixtures__/colorSchemes/material-darker.xml create mode 100644 src/platform/__fixtures__/colorSchemes/one-dark-wrapped.xml diff --git a/src/features/settings/__tests__/colorScheme.test.tsx b/src/features/settings/__tests__/colorScheme.test.tsx index 749a93343..af4116498 100644 --- a/src/features/settings/__tests__/colorScheme.test.tsx +++ b/src/features/settings/__tests__/colorScheme.test.tsx @@ -116,9 +116,39 @@ describe("scheme actions", () => { it("shows a malformed-file error without staging any changes", async () => { mocks.read.mockResolvedValueOnce({ status: "ok", data: '' }); await run("import"); - await waitFor(() => expect(mocks.error).toHaveBeenCalledWith("Color Scheme", "Invalid .icls color scheme")); + await waitFor(() => + expect(mocks.error).toHaveBeenCalledWith("Import Scheme", expect.stringContaining("Invalid .icls color scheme")), + ); expect(useSettingsDialog.getState().staged).toEqual({}); }); + + it("offers .xml scheme files in the chooser and imports one (#2714)", async () => { + mocks.open.mockResolvedValueOnce("/downloads/Material Darker.xml"); + mocks.read.mockResolvedValueOnce({ + status: "ok", + data: readFileSync("src/platform/__fixtures__/colorSchemes/material-darker.xml", "utf8"), + }); + await run("import"); + expect(mocks.open).toHaveBeenCalledWith({ + multiple: false, + filters: [{ name: "IntelliJ Color Scheme", extensions: ["icls", "xml"] }], + }); + expect(value("colorScheme")).toMatch(/^custom-/); + expect(screen.getByRole("status")).toHaveTextContent("Applied 12 values; skipped 3"); + const schemes = value("customSchemes") as Record; + expect(Object.values(schemes).some((s) => s.name === "Material Darker")).toBe(true); + }); + + it("names a scheme without a name attribute after its file (#2714)", async () => { + mocks.open.mockResolvedValueOnce("/downloads/one-dark-wrapped.xml"); + mocks.read.mockResolvedValueOnce({ + status: "ok", + data: readFileSync("src/platform/__fixtures__/colorSchemes/one-dark-wrapped.xml", "utf8"), + }); + await run("import"); + const schemes = value("customSchemes") as Record; + expect(Object.values(schemes).some((s) => s.name === "one-dark-wrapped")).toBe(true); + }); }); describe("doc comment scheme attributes", () => { diff --git a/src/features/settings/pages/editor/colorScheme.tsx b/src/features/settings/pages/editor/colorScheme.tsx index 092e6d6bb..0dbd2d0f1 100644 --- a/src/features/settings/pages/editor/colorScheme.tsx +++ b/src/features/settings/pages/editor/colorScheme.tsx @@ -28,7 +28,7 @@ import styles from "./Editor.module.css"; import { executeAction, registerActions } from "@/platform/actions"; import { call, commands } from "@/platform/ipc"; import { ask, confirm, showError } from "@/workbench/messages"; -import { parseIcls, importScheme, deleteScheme, exportIcls } from "@/platform/icls"; +import { parseIcls, SchemeParseError, importScheme, deleteScheme, exportIcls } from "@/platform/icls"; import { tx, useTx } from "@/platform/i18n"; import { selectPage } from "../../model/staging"; @@ -1158,10 +1158,17 @@ function ColorSchemePage({ scopes, landing }: { scopes: readonly string[]; landi file ?? (await open({ multiple: false, - filters: [{ name: tx("IntelliJ Color Scheme"), extensions: ["icls"] }], + // IDEA schemes ship as .icls, but the ones people download are frequently .xml. + filters: [{ name: tx("IntelliJ Color Scheme"), extensions: ["icls", "xml"] }], })); if (!path) return; - const parsed = parseIcls(await call(commands.fsReadText(path))); + // A scheme element without a name is named after its file, as IntelliJ does. + const fallbackName = + path + .split(/[\\/]/) + .at(-1) + ?.replace(/\.[^.]+$/, "") || "Imported scheme"; + const parsed = parseIcls(await call(commands.fsReadText(path)), fallbackName); let overwrite = false; if (schemes.some((s) => s.name === parsed.scheme.name)) { const canOverwrite = Object.values(customs).some((s) => s.name === parsed.scheme.name); @@ -1232,9 +1239,9 @@ function ColorSchemePage({ scopes, landing }: { scopes: readonly string[]; landi await handlers.current[name]!(typeof arg === "string" ? arg : undefined); } catch (error) { await showError( - tx("Color Scheme"), - error instanceof Error && error.message === "Invalid .icls color scheme" - ? tx("Invalid .icls color scheme") + tx("Import Scheme"), + error instanceof SchemeParseError + ? `${tx("Invalid .icls color scheme")}: ${error.message}` : String(error), ); } finally { diff --git a/src/platform/__fixtures__/colorSchemes/bom-utf8.icls b/src/platform/__fixtures__/colorSchemes/bom-utf8.icls new file mode 100644 index 000000000..e0cd8ffc4 --- /dev/null +++ b/src/platform/__fixtures__/colorSchemes/bom-utf8.icls @@ -0,0 +1,7 @@ + + + + + + + diff --git a/src/platform/__fixtures__/colorSchemes/declared-encoding.icls b/src/platform/__fixtures__/colorSchemes/declared-encoding.icls new file mode 100644 index 000000000..567b6d3ff --- /dev/null +++ b/src/platform/__fixtures__/colorSchemes/declared-encoding.icls @@ -0,0 +1,9 @@ + + + + + + + + diff --git a/src/platform/__fixtures__/colorSchemes/material-darker.xml b/src/platform/__fixtures__/colorSchemes/material-darker.xml new file mode 100644 index 000000000..fef5ca80a --- /dev/null +++ b/src/platform/__fixtures__/colorSchemes/material-darker.xml @@ -0,0 +1,89 @@ + + + + diff --git a/src/platform/__fixtures__/colorSchemes/one-dark-wrapped.xml b/src/platform/__fixtures__/colorSchemes/one-dark-wrapped.xml new file mode 100644 index 000000000..83f1831d5 --- /dev/null +++ b/src/platform/__fixtures__/colorSchemes/one-dark-wrapped.xml @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/src/platform/icls.test.ts b/src/platform/icls.test.ts index e863760fa..c16121dbd 100644 --- a/src/platform/icls.test.ts +++ b/src/platform/icls.test.ts @@ -9,14 +9,15 @@ import { SCHEMES, schemeCss, } from "./colorScheme"; -import { deleteScheme, exportIcls, importScheme, parseIcls } from "./icls"; +import { deleteScheme, exportIcls, importScheme, parseIcls, SchemeParseError } from "./icls"; import { validateSettings } from "@/features/settings/model/schema"; import { colorSchemeItems } from "@/workbench/quickSwitch"; import { useProject } from "./project"; import type { Settings } from "./ipc"; import { isClientSetting } from "./clientSettings"; -const fixture = (name: string) => readFileSync(`src/platform/__fixtures__/colorSchemes/${name}.icls`, "utf8"); +const fixture = (name: string, ext = "icls") => + readFileSync(`src/platform/__fixtures__/colorSchemes/${name}.${ext}`, "utf8"); beforeAll(() => _setSchemeSource(readFileSync("src/styles/tokens.css", "utf8"))); describe(".icls schemes", () => { @@ -177,18 +178,65 @@ describe(".icls schemes", () => { expect([sign.applied, sign.skipped]).toEqual([1, 2]); }); + it.each(["", "', "", ''])( + "rejects malformed or non-scheme XML without mutating schemes: %s", + (xml) => { + const customs = importScheme({}, parseIcls(fixture("forest")).scheme).customs; + const before = structuredClone(customs); + expect(() => parseIcls(xml)).toThrow(SchemeParseError); + expect(customs).toEqual(before); + }, + ); + + it("names what is wrong with a rejected file", () => { + expect(() => parseIcls("")).toThrow(/not valid XML/); + try { + parseIcls(''); + expect.unreachable(); + } catch (error) { + expect(error).toBeInstanceOf(SchemeParseError); + expect((error as Error).message).toMatch(/ element/); + } + }); + + it("imports a real-world .xml scheme from Material Theme UI (#2714)", () => { + const { scheme, applied, skipped } = parseIcls(fixture("material-darker", "xml")); + expect(scheme.name).toBe("Material Darker"); + expect(scheme.parent).toBe("dark"); + expect(scheme.attributes.keyword).toEqual({ foreground: "#c792ea", bold: false, italic: true }); + expect(scheme.attributes.string?.foreground).toBe("#c3e88d"); + expect(scheme.attributes.lineComment).toEqual({ foreground: "#616161", bold: false, italic: true }); + expect(scheme.attributes.text).toEqual({ foreground: "#eeffff", background: "#212121" }); + expect(scheme.attributes.caret?.foreground).toBe("#ffcc00"); + expect(scheme.attributes.gutter?.background).toBe("#212121"); + expect(scheme.attributes.lineNumber?.foreground).toBe("#424242"); + expect(scheme.attributes.selection?.background).toBe("#353535"); + expect([applied, skipped]).toEqual([12, 3]); + }); + it.each([ - "", - "', - "", - '', - ']>', - ])("rejects malformed XML without mutating schemes: %s", (xml) => { - const customs = importScheme({}, parseIcls(fixture("forest")).scheme).customs; - const before = structuredClone(customs); - expect(() => parseIcls(xml)).toThrow("Invalid .icls color scheme"); - expect(customs).toEqual(before); + ["bom-utf8", "Bom Light"], + ["declared-encoding", "Café Solar"], + ] as const)("accepts the BOM and encoding-declaration variants of a scheme: %s", (name, schemeName) => { + const { scheme } = parseIcls(fixture(name)); + expect(scheme.name).toBe(schemeName); + expect(scheme.attributes.keyword?.foreground).toBe(name === "bom-utf8" ? "#1122ff" : "#cc7832"); + // Byte-order and encoding marks do not change what a scheme says. + expect(parseIcls(`\uFEFF${fixture(name)}`).scheme).toEqual(scheme); + }); + + it("unwraps a scheme element from its settings export and names a scheme after its file (#2714)", () => { + const { scheme } = parseIcls(fixture("one-dark-wrapped", "xml")); + expect(scheme.name).toBe("Imported scheme"); + expect(scheme.attributes.keyword).toEqual({ foreground: "#c678dd", bold: true, italic: false }); + expect(scheme.attributes.text).toEqual({ foreground: "#abb2bf", background: "#282c34" }); + expect(parseIcls(fixture("one-dark-wrapped", "xml"), "One Dark").scheme.name).toBe("One Dark"); + }); + + it("accepts a DOCTYPE prolog, which XML allows and old exporters emit (#2714)", () => { + const { scheme } = parseIcls(''); + expect(scheme.name).toBe("D"); + expect(() => parseIcls(']>')).not.toThrow(); }); it.each([ diff --git a/src/platform/icls.ts b/src/platform/icls.ts index 60b0b9583..66c5d6feb 100644 --- a/src/platform/icls.ts +++ b/src/platform/icls.ts @@ -274,16 +274,45 @@ function attributeEntries(section: Element): Element[] { return entries.filter((e) => e.getAttribute("name") !== "DEFAULT_BLOCK_COMMENT"); } -export function parseIcls(xml: string): { scheme: CustomColorScheme; applied: number; skipped: number } { - const doc = new DOMParser().parseFromString(xml, "application/xml"); - const root = doc.documentElement; - if ( - doc.querySelector("parsererror") || - doc.doctype || - root.tagName !== "scheme" || - !root.getAttribute("name")?.trim() - ) - throw new Error("Invalid .icls color scheme"); +/** A scheme file that is not an IntelliJ color scheme; `message` says what is wrong with it. */ +export class SchemeParseError extends Error { + constructor(message: string) { + super(message); + this.name = "SchemeParseError"; + } +} + +/** + * The variants real IDEA scheme files come in: a BOM, an `encoding=` declaration + * (both describe the file's bytes, while this text has already been decoded), and + * a DOCTYPE prolog. None of them change the scheme, so drop the first two. + */ +const prepareIclsXml = (xml: string) => + xml + .replace(/^\uFEFF+/, "") + .replace(/^\s*<\?xml\s[^>]*\?>(\r\n|\r|\n)?/i, "") + .replace(/^\s*(\r\n|\r|\n)?/, ""); + +const parserDetail = (doc: Document): string => { + const detail = (doc.querySelector("parsererror")?.textContent ?? "").replace(/\s+/g, " ").trim(); + return detail.length ? detail.slice(0, 200) : "no scheme element found"; +}; + +export function parseIcls( + xml: string, + fallbackName = "Imported scheme", +): { scheme: CustomColorScheme; applied: number; skipped: number } { + const doc = new DOMParser().parseFromString(prepareIclsXml(xml), "application/xml"); + // Some distributors wrap the scheme element (an / export), or leave the name out. + const root = + doc.documentElement?.tagName === "scheme" + ? doc.documentElement + : (doc.getElementsByTagName("scheme")[0] ?? undefined); + if (doc.querySelector("parsererror") || !root) + throw new SchemeParseError( + doc.querySelector("parsererror") ? `not valid XML (${parserDetail(doc)})` : "no IntelliJ element found", + ); + const name = root.getAttribute("name")?.trim() || fallbackName; const attributes: Record = {}; const entries = new Map( children(root, "attributes").flatMap((section) => @@ -397,7 +426,7 @@ export function parseIcls(xml: string): { scheme: CustomColorScheme; applied: nu : dark ? "dark" : "light"; - return { scheme: { name: root.getAttribute("name")!.trim(), parent, attributes }, applied, skipped }; + return { scheme: { name, parent, attributes }, applied, skipped }; } /** Name collisions include built-ins; imports never replace a built-in. */