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>
This commit is contained in:
Vadim Lazuk
2026-11-11 21:23:38 +08:00
committed by GitHub
co-authored by Inf1mum
parent 7034fe1640
commit f11cd361a7
8 changed files with 261 additions and 31 deletions
@@ -116,9 +116,39 @@ describe("scheme actions", () => {
it("shows a malformed-file error without staging any changes", async () => {
mocks.read.mockResolvedValueOnce({ status: "ok", data: '<scheme name="bad">' });
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<string, { name: string }>;
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<string, { name: string }>;
expect(Object.values(schemes).some((s) => s.name === "one-dark-wrapped")).toBe(true);
});
});
describe("doc comment scheme attributes", () => {
@@ -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 {
@@ -0,0 +1,7 @@
<scheme name="Bom Light" version="142" parent_scheme="Default">
<colors><option name="CARET_COLOR" value="ff00ff" /></colors>
<attributes>
<option name="DEFAULT_KEYWORD"><value><option name="FOREGROUND" value="1122ff" /><option name="FONT_TYPE" value="1" /></value></option>
<option name="TEXT"><value><option name="FOREGROUND" value="334455" /><option name="BACKGROUND" value="f0f0f0" /></value></option>
</attributes>
</scheme>
@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="windows-1252"?>
<!-- Saved by a Windows editor: the declaration describes the file's bytes, while a
caller hands parseIcls already decoded text. The name must survive unchanged. -->
<scheme name="Café Solar" version="142" parent_scheme="Default">
<colors><option name="CARET_COLOR" value="ffcc00" /></colors>
<attributes>
<option name="DEFAULT_KEYWORD"><value><option name="FOREGROUND" value="cc7832" /></value></option>
</attributes>
</scheme>
@@ -0,0 +1,89 @@
<!--
~ The MIT License (MIT)
~
~ Copyright (c) 2015-2021 Elior "Mallowigi" Boukhobza
~
~ Permission is hereby granted, free of charge, to any person obtaining a copy
~ of this software and associated documentation files (the "Software"), to deal
~ in the Software without restriction, including without limitation the rights
~ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
~ copies of the Software, and to permit persons to whom the Software is
~ furnished to do so, subject to the following conditions:
~
~ The above copyright notice and this permission notice shall be included in all
~ copies or substantial portions of the Software.
~
~ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
~ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
~ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
~ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
~ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
~ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
~ SOFTWARE.
~
~
-->
<scheme name="Material Darker" version="142" parent_scheme="Darcula">
<option name="FONT_SCALE" value="1.0" />
<metaInfo>
<property name="created">2017-04-10T18:10:53</property>
<property name="ide">idea</property>
<property name="ideVersion">2020.1.0.0</property>
<property name="modified">2020-04-18T11:14:57</property>
<property name="originalScheme">Material Darker</property>
</metaInfo>
<option name="LINE_SPACING" value="1.4" />
<option name="EDITOR_FONT_SIZE" value="12" />
<font>
<option name="EDITOR_FONT_NAME" value="Menlo" />
<option name="EDITOR_FONT_SIZE" value="12" />
</font>
<font>
<option name="EDITOR_FONT_NAME" value="Fira Code" />
<option name="EDITOR_FONT_SIZE" value="12" />
</font>
<console-font>
<option name="EDITOR_FONT_NAME" value="Menlo" />
<option name="EDITOR_FONT_SIZE" value="12" />
</console-font>
<console-font>
<option name="EDITOR_FONT_NAME" value="Fira Code" />
<option name="EDITOR_FONT_SIZE" value="12" />
</console-font>
<colors>
<option name="CARET_COLOR" value="ffcc00" />
<option name="CARET_ROW_COLOR" value="181818" />
<option name="CONSOLE_BACKGROUND_KEY" value="212121" />
<option name="DELETED_LINES_COLOR" value="f07178" />
<option name="GUTTER_BACKGROUND" value="212121" />
<option name="LINE_NUMBERS_COLOR" value="424242" />
<option name="SELECTION_BACKGROUND" value="353535" />
</colors>
<attributes>
<option name="DEFAULT_KEYWORD">
<value>
<option name="FOREGROUND" value="c792ea" />
<option name="FONT_TYPE" value="2" />
</value>
</option>
<option name="DEFAULT_STRING">
<value>
<option name="FOREGROUND" value="c3e88d" />
</value>
</option>
<option name="DEFAULT_LINE_COMMENT">
<value>
<option name="FOREGROUND" value="616161" />
<option name="FONT_TYPE" value="2" />
</value>
</option>
<option name="TEXT">
<value>
<option name="FOREGROUND" value="eeffff" />
<option name="BACKGROUND" value="212121" />
<option name="EFFECT_TYPE" value="5" />
</value>
</option>
</attributes>
</scheme>
@@ -0,0 +1,11 @@
<application>
<component name="EditorColorsSchemeImpl">
<scheme version="142" parent_scheme="Darcula">
<colors><option name="SELECTION_BACKGROUND" value="3a3d41" /></colors>
<attributes>
<option name="DEFAULT_KEYWORD"><value><option name="FOREGROUND" value="c678dd" /><option name="FONT_TYPE" value="1" /></value></option>
<option name="TEXT"><value><option name="FOREGROUND" value="abb2bf" /><option name="BACKGROUND" value="282c34" /></value></option>
</attributes>
</scheme>
</component>
</application>
+61 -13
View File
@@ -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(["", "<scheme", '<scheme name="A"><attributes></scheme>', "<nope>", '<html name="x"/>'])(
"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("<nope>")).toThrow(/not valid XML/);
try {
parseIcls('<html name="x"/>');
expect.unreachable();
} catch (error) {
expect(error).toBeInstanceOf(SchemeParseError);
expect((error as Error).message).toMatch(/<scheme> 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([
"",
"<scheme",
'<scheme name="A"><attributes></scheme>',
"<scheme/>",
'<html name="x"/>',
'<!DOCTYPE scheme [<!ENTITY a "red">]><scheme name="x"/>',
])("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('<!DOCTYPE scheme SYSTEM "scheme.dtd"><scheme name="D"><colors/></scheme>');
expect(scheme.name).toBe("D");
expect(() => parseIcls('<!DOCTYPE scheme [<!ENTITY a "red">]><scheme name="x"/>')).not.toThrow();
});
it.each([
+40 -11
View File
@@ -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 <application>/<component> 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 <scheme> element found",
);
const name = root.getAttribute("name")?.trim() || fallbackName;
const attributes: Record<string, TextAttributesOverride> = {};
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. */