Порівняти коміти

..
Автор SHA1 Повідомлення Дата
l0ng-ai 8af09aaf58 fix(tools): install debugpy when the project's Python has no pip
debugpy's private copy was made with `python -m pip` of the selected interpreter.
A virtualenv made by uv has no pip, so with such a project interpreter the
install failed with "No module named pip". The copy is a universal wheel and
doesn't need that interpreter's pip: when it has none, pip runs through
`uv tool run pip`, or another Python on PATH that has pip.
2026-11-16 11:25:03 +08:00
Deng Liuтаdengliu 0b097808f1 fix(agents): increase process-run step indentation and align running tool icons (#3636)
Expanded process runs and turn folds read nearly flat: the guide line sat left of the summary chevron, nested chevrons indented by only a few pixels, and tool rows without output yet had no chevron slot, so their icon jumped right once output arrived. The guide now drops from the parent chevron's centre, tool calls after a thought indent under it, expanded output indents with its row, and output-less tool rows reserve the chevron's width.

Co-authored-by: dengliu <[email protected]>
2026-11-16 11:10:18 +08:00
LU XIANGRUIтаwildcatDownstairs 6cc4b3779c fix(settings): import the JetBrains line height from the font's own height (#3640)
The imported line height was font size × LINE_SPACING and was only written when the export had LINE_SPACING, so tall fonts came out cramped and the default spacing (left out of the export) never applied. It is now the font's measured height (ascent + descent, rounded up per side) × LINE_SPACING (1.2 when absent), written whenever the export sets a font, size or spacing; size × 1.2 is the fallback when the font cannot be measured.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-16 11:08:13 +08:00
Muuтаmuutot 7d9efa1997 fix(plugins): deliver the post-install settings event to a freshly installed plugin (#3642)
The UI posts a synthetic settings-changed right after an install so event-driven plugins get a first delivery, but changed_settings() took its first snapshot on that call and reported an empty diff, so the event was dropped and the plugin stayed inactive until something else happened in the window. With no snapshot yet for a (window, plugin), it now hands over the current keys; later calls still report only the diff.

Co-authored-by: muutot <[email protected]>
2026-11-16 11:07:37 +08:00
GuoYuтаguoyucode af2e45883d fix(lsp): give a project attached inside the root its own language server (#3643)
Since attached projects inside the root were left out of the content roots (the index already walks them), the language-server manager routed their files to the outer project's server, whose workspace does not contain them (rust-analyzer: "file is not included in any crate"). The manager now gets the content roots plus the projects attached inside the root; index roots are unchanged.

Co-authored-by: guoyucode <[email protected]>
2026-11-16 11:04:29 +08:00
17 змінених файлів з 426 додано та 66 видалено

No files matched your search

+8 -3
Переглянути файл
@@ -677,9 +677,14 @@ impl Shared {
}
let previous =
self.setting_snapshots.lock().insert((client.map(str::to_owned), pkg.id().into()), current.clone());
previous
.map(|old| current.into_iter().filter(|(k, v)| old.get(k) != Some(v)).map(|(k, _)| k).collect())
.unwrap_or_default()
match previous {
// First contact since the plugin loaded (fresh install, update,
// re-enable): hand over every current key, so the synthetic
// post-install `settings-changed` wakes the plugin instead of being
// dropped for having no diff yet.
None => current.into_keys().collect(),
Some(old) => current.into_iter().filter(|(k, v)| old.get(k) != Some(v)).map(|(k, _)| k).collect(),
}
}
pub fn status_snapshot(&self, client: &str) -> Vec<super::PluginStatusItem> {
+39 -2
Переглянути файл
@@ -144,7 +144,7 @@ impl Host {
let lsp = LspManager::new(root.clone(), languages.clone(), sink.clone());
crate::plugins::injections::configure_lsp(&lsp);
lsp.set_execution_allowed(trusted.load(Ordering::Acquire));
lsp.set_content_roots(extra_roots.clone());
lsp.set_content_roots(language_server_roots(&root, extra_roots.clone()));
lsp.set_jdtls_import_roots(ide_build::maven_external_roots(
&root,
&settings.effective().languages.java.maven.linked_projects,
@@ -1224,7 +1224,7 @@ impl Project {
return;
}
let (roots, excludes) = (self.content_roots(), self.exclude_globs());
self.lsp.set_content_roots(roots.clone());
self.lsp.set_content_roots(language_server_roots(&self.root, roots.clone()));
self.lsp.set_jdtls_import_roots(ide_build::maven_external_roots(
&self.root,
&self.settings.effective().languages.java.maven.linked_projects,
@@ -1369,6 +1369,22 @@ fn content_roots(settings: &ide_core::settings::Settings, root: &Path, build_cac
extra_content_roots(settings, root, build_cache)
}
/// The content roots plus the projects attached inside this one. The index covers those
/// already, but each is a project of its own (a git worktree under the project, a nested
/// Cargo workspace), so its files get a language server rooted there, not at this root.
fn language_server_roots(root: &Path, mut roots: Vec<PathBuf>) -> Vec<PathBuf> {
if let Ok(Some(workspace)) = ide_workspace::workspace::Workspace::load(root)
&& !workspace.is_container(root)
{
for path in workspace.projects {
if path != root && path.starts_with(root) && !roots.contains(&path) {
roots.push(path);
}
}
}
roots
}
/// The roots a file may navigate into: its own root (the workspace member containing it, or
/// the project root) plus that root's configured dependencies. A workspace member depends
/// only on the roots picked per member in Project Structure › Dependencies —
@@ -2163,4 +2179,25 @@ mod content_roots_tests {
let roots = content_roots(&settings, &root, &tmp.path().join("build"));
assert_eq!(roots, vec![shared, dep]);
}
#[test]
fn projects_attached_inside_the_root_get_their_own_language_server_root() {
let tmp = tempfile::tempdir().unwrap();
let ws = dunce::canonicalize(tmp.path()).unwrap();
let (root, nested, other) = (ws.join("app"), ws.join("app/.wt/feature"), ws.join("other"));
for dir in [&nested, &other] {
std::fs::create_dir_all(dir).unwrap();
}
let settings = ide_core::settings::Settings::default();
let build = ws.join("build");
assert!(super::language_server_roots(&root, content_roots(&settings, &root, &build)).is_empty());
ide_workspace::workspace::Workspace::attach(&root, "app", vec![root.clone(), nested.clone(), other.clone()])
.unwrap();
// The index walks the nested project as part of the root ...
let roots = content_roots(&settings, &root, &build);
assert_eq!(roots, vec![other.clone()]);
// ... while its files go to a language server of its own.
assert_eq!(super::language_server_roots(&root, roots), vec![other, nested]);
}
}
+26 -2
Переглянути файл
@@ -6271,10 +6271,15 @@ fn api14_settings_and_input_events_use_other_and_capture_the_editor() {
assert!(f.host.wait_events(Duration::from_secs(5)));
let received: serde_json::Value = serde_json::from_str(&f.run("api14", "events", None).unwrap().unwrap()).unwrap();
let events = received.as_array().unwrap();
assert_eq!(events.len(), 3, "{received}");
assert_eq!(events.len(), 4, "{received}");
// The first synthetic post hands over the current keys ("enabled": false);
// the second is a real diff to true. Keys come from the recomputed
// snapshot, never from the event payload ("another-plugin-key").
assert_eq!(events[0]["kind"], "settings-changed");
assert_eq!(events[0]["data"], "[\"enabled\"]");
assert_eq!(events[2]["kind"], "input-mode-changed");
assert_eq!(events[1]["kind"], "settings-changed");
assert_eq!(events[1]["data"], "[\"enabled\"]");
assert_eq!(events[3]["kind"], "input-mode-changed");
assert_eq!(events[2]["editor"][0], path);
assert_eq!(events[2]["editor"][1][0], serde_json::json!([0, 0, 0, 0]));
}
@@ -7016,3 +7021,22 @@ fn the_language_server_grant_needs_api_1_9() {
let err = f.host.install_from_dir(&pkg, &Consent::all()).unwrap_err();
assert!(err.message.contains("new in plugin API 1.9"), "{err:?}");
}
/// The UI's synthetic post-install `SettingsChanged([])` reaches a plugin that
/// subscribes to `on-event:settings-changed`, though it carries no keys.
#[test]
fn a_freshly_installed_plugin_gets_the_post_install_settings_event() {
let f = fixture(Limits::default());
f.install(&sample("api14"));
use ide_plugin::WorkbenchEvent as E;
// What refreshEventKinds() posts right after commandsChanged (install).
f.host.post_events(Some("main"), vec![E::SettingsChanged(Vec::new())]);
f.host.flush_events_at(Instant::now() + Duration::from_secs(2));
assert!(f.host.wait_events(Duration::from_secs(5)));
let received: serde_json::Value = serde_json::from_str(&f.run("api14", "events", None).unwrap().unwrap()).unwrap();
let events = received.as_array().unwrap();
assert!(
events.iter().any(|e| e["kind"] == "settings-changed"),
"freshly installed plugin got no post-install event: {received}"
);
}
+38 -2
Переглянути файл
@@ -1256,6 +1256,42 @@ impl Tools {
Err(IdeError::new(ErrorKind::Io, format!("pip install {package} failed ({status})")))
}
/// A command running pip, before its arguments. The interpreter's own pip when it has one;
/// a virtualenv made by uv has none, so then pip through `uv tool run`, or another Python
/// on `PATH` that has it.
fn pip_command(&self, python: PathBuf, emit: Emit) -> Command {
let has_pip = |python: &Path| {
let mut c = self.python_command(python);
c.args(["-m", "pip", "--version"]);
run_quiet(c, Duration::from_secs(20)).is_some_and(|(ok, _)| ok)
};
let module = |python: &Path| {
let mut c = self.python_command(python);
c.args(["-m", "pip"]);
c
};
if has_pip(&python) {
return module(&python);
}
let note = format!("{} has no pip", python.display());
if let Some(uv) = self.which("uv") {
emit(InstallEvent::Line { text: format!("{note}; running pip with uv") });
// pip runs in uv's own Python: the same private working directory applies.
let mut c = self.python_command(uv);
c.args(["tool", "run", "pip"]);
return c;
}
let other = ["python3", "python"]
.into_iter()
.filter_map(|name| ide_core::tool_path::find_command(name, &self.system_path, &self.root))
.find(|p| *p != python && has_pip(p));
if let Some(other) = other {
emit(InstallEvent::Line { text: format!("{note}; using {}", other.display()) });
return module(&other);
}
module(&python)
}
/// The universal (`py3-none-any`) wheel, so the copy works with every interpreter
/// version a project selects, not just the one that installed it.
fn install_pip_target(
@@ -1269,8 +1305,8 @@ impl Tools {
let _ = std::fs::remove_dir_all(&dir);
let lib = python_lib_dir(&self.root, spec.name);
std::fs::create_dir_all(&lib)?;
let mut c = self.python_command(self.python().expect("checked"));
c.args(["-m", "pip", "install", "--disable-pip-version-check", "--no-deps", "--upgrade", "--target"])
let mut c = self.pip_command(self.python().expect("checked"), emit);
c.args(["install", "--disable-pip-version-check", "--no-deps", "--upgrade", "--target"])
.arg(&lib)
.args(["--only-binary=:all:", "--platform", "any", "--implementation", "py"])
.arg(package);
+50
Переглянути файл
@@ -895,9 +895,14 @@ esac
}
}
/// Installs of one tool name share a process-wide slot: tests installing debugpy take turns.
#[cfg(unix)]
static DEBUGPY_INSTALL: parking_lot::Mutex<()> = parking_lot::Mutex::new(());
#[cfg(unix)]
#[test]
fn selected_python_is_used_for_pip_and_uv_even_with_a_versioned_filename() {
let _guard = DEBUGPY_INSTALL.lock();
let env = Env::new();
env.script(&env.sys, "python3", "exit 99");
let sdk = env._tmp.path().join("python-sdk");
@@ -935,6 +940,51 @@ exit 1
assert!(args.contains(&format!("--python {}", sdk.join("python3.14").display())), "{args}");
}
/// A virtualenv made by uv has no pip: debugpy's private copy is made with pip through uv.
#[cfg(unix)]
#[test]
fn debugpy_installs_through_uv_when_the_selected_python_has_no_pip() {
let _guard = DEBUGPY_INSTALL.lock();
let env = Env::new();
let venv = env._tmp.path().join("project/.venv/bin");
env.script(&venv, "python", "echo \"$(basename \"$0\"): No module named pip\" >&2; exit 1");
let log = env._tmp.path().join("uv.log");
env.script(
&env.sys,
"uv",
&format!(
r#"
echo "$@" >> '{log}'
while [ $# -gt 0 ]; do
if [ "$1" = "--target" ]; then
/bin/mkdir -p "$2/debugpy" "$2/debugpy-1.8.0.dist-info"
/usr/bin/touch "$2/debugpy/__init__.py"
exit 0
fi
shift
done
exit 1
"#,
log = log.display()
),
);
let tools = env.tools().with_runtime(BTreeMap::from([("python".into(), venv.join("python"))]), BTreeMap::new());
let lines = Mutex::new(Vec::new());
let info = tools
.install("debugpy", &langs(), &CancellationToken::new(), &|e| {
if let InstallEvent::Line { text } = e {
lines.lock().push(text);
}
})
.unwrap();
assert_eq!(info.status, ToolStatus::Installed);
assert_eq!(info.version.as_deref(), Some("1.8.0"));
let args = fs::read_to_string(log).unwrap();
assert!(args.starts_with("tool run pip install "), "{args}");
assert!(args.contains("--platform any"), "{args}");
assert!(lines.lock().iter().any(|l| l.contains("has no pip")));
}
#[test]
fn a_cancelled_install_leaves_the_previous_one_in_place() {
let tmp = tempfile::tempdir().unwrap();
+83
Переглянути файл
@@ -819,3 +819,86 @@ test("keeps ordered, bulleted and task list markers unclipped inside measured ro
expect(cb.offsetFromRowLeft).toBeGreaterThanOrEqual(0);
}
});
test("indents process-run thoughts and tool calls clearly and aligns output-less tool icons", async ({ page }) => {
await openReply(page, "All checks passed.");
await page.evaluate(async (task) => {
const storePath = "/src/features/agents/store.ts";
const store = await import(storePath);
store.useAgents.setState({
tasks: new Map([[task.id, { ...task, status: "running" as const }]]),
entries: new Map([
[
task.id,
[
{ type: "thought", text: "**Checking CI Status**\n\nInspecting workflow runs." },
{
type: "tool",
id: "t1",
title: "gh pr checks 3631 --repo l0ng-ai/openidea",
kind: "execute",
status: "completed",
locations: [],
output: "All checks pending",
diffs: [],
},
{ type: "thought", text: "**Tracking Continuous Integration**\n\nWaiting for E2E." },
{
type: "tool",
id: "t2",
title: "read_bash",
kind: "other",
status: "completed",
locations: [],
output: "E2E pass",
diffs: [],
},
{
type: "tool",
id: "t3",
title: "read_bash",
kind: "other",
status: "running",
locations: [],
output: "",
diffs: [],
},
],
],
]),
});
store.openTaskInEditorLocation(task.id);
}, TASK);
const stream = page.locator("[class*='_stream_']:visible");
const summary = stream.locator("[class*='_processSummary_']").first();
await summary.click();
await expect(stream.getByText("Checking CI Status")).toBeVisible();
const layout = await stream.evaluate((root) => {
const summaryChevron = root.querySelector<SVGElement>("[class*='_processChevron_']")!.getBoundingClientRect();
const processBody = root.querySelector<HTMLElement>("[class*='_processBody_']")!.getBoundingClientRect();
const thoughtChevron = root.querySelector<SVGElement>("[class*='_thoughtChevron_']")!.getBoundingClientRect();
const toolRows = [...root.querySelectorAll<HTMLElement>("[class*='_tool_']")];
const expandableToolChevron = toolRows[0]!
.querySelector<SVGElement>("[class*='_toolChevron_']")!
.getBoundingClientRect();
const completedReadIcon = [...toolRows[1]!.querySelectorAll("svg")].at(-1)!.getBoundingClientRect();
const runningReadIcon = toolRows[2]!.querySelector("svg")!.getBoundingClientRect();
return {
summaryChevronCenter: summaryChevron.left + summaryChevron.width / 2,
guideLeft: processBody.left,
summaryToThoughtIndent: thoughtChevron.left - summaryChevron.left,
thoughtToToolIndent: expandableToolChevron.left - thoughtChevron.left,
iconLeftDiff: Math.abs(completedReadIcon.left - runningReadIcon.left),
};
});
// Guide line drops from the center of the process summary chevron.
expect(Math.abs(layout.guideLeft - layout.summaryChevronCenter)).toBeLessThanOrEqual(1.5);
// Thoughts indent clearly inside the process run, and tool calls indent under their thought step.
expect(layout.summaryToThoughtIndent).toBeGreaterThanOrEqual(20);
expect(layout.thoughtToToolIndent).toBeGreaterThanOrEqual(14);
// Output-less running tool rows align their kind icon with expandable tool rows.
expect(layout.iconLeftDiff).toBeLessThanOrEqual(1);
});
+31 -8
Переглянути файл
@@ -404,6 +404,13 @@
.agentName {
display: none;
}
.processBody,
.turnBody {
padding-left: var(--space-2);
}
.processBody > .thoughtEntry ~ .toolEntry {
padding-left: var(--space-3);
}
}
.messageActions {
display: inline-flex;
@@ -771,6 +778,10 @@
margin-bottom: 0;
}
.thoughtEntry,
.toolEntry {
min-width: 0;
}
.thought summary,
.toolDetails > summary {
cursor: pointer;
@@ -783,15 +794,18 @@
.thought summary {
display: flex;
align-items: center;
gap: var(--space-1);
gap: var(--space-1-5);
min-width: 0;
min-height: var(--h-row);
padding: 0 calc(var(--space-2) / 2);
border-radius: var(--radius-row);
color: var(--fg-muted);
font-size: var(--agent-fs-small, var(--fs-small));
-webkit-user-select: none;
user-select: none;
}
.thought summary:hover {
background: var(--bg-hover);
color: var(--fg);
}
.thoughtChevron {
@@ -807,7 +821,9 @@
transform: rotate(90deg);
}
.thoughtBody {
margin-top: var(--space-2);
margin: var(--space-1-5) 0 var(--space-1) 10px;
padding-left: var(--space-3);
border-left: 1px solid var(--border);
color: var(--fg-secondary);
}
.thoughtText {
@@ -821,7 +837,7 @@
.tool {
display: flex;
align-items: center;
gap: var(--space-2);
gap: var(--space-1-5);
min-width: 0;
box-sizing: border-box;
min-height: var(--h-row);
@@ -848,6 +864,10 @@
.toolChevron {
flex: none;
}
.toolChevronSpacer {
width: 12px;
flex: none;
}
.toolDetails[open] > summary .toolChevron {
transform: rotate(90deg);
}
@@ -927,12 +947,15 @@
gap: var(--space-0-5);
max-height: calc(var(--h-row) * 16);
overflow-y: auto;
margin-top: 2px;
padding-left: 10px;
margin: 2px 0 0 10px;
padding-left: var(--space-3);
border-left: 1px solid var(--border);
}
.processBody > .thoughtEntry ~ .toolEntry {
padding-left: var(--space-4);
}
.output {
margin: 4px 0 0;
margin: 4px 0 4px 22px;
max-height: 240px;
overflow: auto;
padding: 8px 10px;
@@ -1828,8 +1851,8 @@
display: flex;
flex-direction: column;
gap: var(--space-2);
margin-top: 2px;
padding-left: 10px;
margin: 2px 0 0 10px;
padding-left: var(--space-3);
border-left: 1px solid var(--border);
}
+7 -4
Переглянути файл
@@ -1426,7 +1426,7 @@ function ThoughtEntry({
if (working && open) onDiagramDrawn();
}, [shown, working, open, onDiagramDrawn]);
return (
<div className={styles.process}>
<div className={clsx(styles.process, styles.thoughtEntry)}>
<Fold
className={clsx(styles.thought, thinking === "auto" && working && styles.thoughtLive)}
open={open}
@@ -2072,12 +2072,15 @@ const ToolEntry = memo(function ToolEntry({
);
if (!entry.output)
return (
<div className={styles.process}>
<div className={styles.tool}>{head}</div>
<div className={clsx(styles.process, styles.toolEntry)}>
<div className={styles.tool}>
<span className={styles.toolChevronSpacer} aria-hidden="true" />
{head}
</div>
</div>
);
return (
<div className={styles.process}>
<div className={clsx(styles.process, styles.toolEntry)}>
<Fold
className={styles.toolDetails}
open={liveTool(entry) || expandToolOutput}
+38 -15
Переглянути файл
@@ -11,7 +11,10 @@ const component = (name: string, options: Record<string, string>) =>
.map(([k, v]) => `<option name="${k}" value="${v}" />`)
.join("")}</component></application>`;
const editor = { fontSize: 13, customSchemes: {}, colorOverrides: {} };
const editor = { fontFamily: "JetBrains Mono", fontSize: 13, customSchemes: {}, colorOverrides: {} };
/** JetBrains Maple Mono's metrics (ascent 1.02em, descent 0.3em), for any family. */
const fontHeight = (_family: string, size: number) => Math.ceil(size * 1.02) + Math.ceil(size * 0.3);
/** A WebStorm export, trimmed to what the import reads. */
const webstorm = {
@@ -51,8 +54,8 @@ const webstorm = {
};
describe("planJetBrainsImport", () => {
it("maps a WebStorm export to the settings it has, and lists what is left out", () => {
const plan = planJetBrainsImport(webstorm, editor);
it("maps a WebStorm export to the settings it has, and lists what is left out", async () => {
const plan = await planJetBrainsImport(webstorm, editor, fontHeight);
const writes = Object.fromEntries(plan.writes);
const schemes = writes["editor.customSchemes"] as Record<string, { name: string; parent: string }>;
const [id, scheme] = Object.entries(schemes)[0]!;
@@ -62,6 +65,8 @@ describe("planJetBrainsImport", () => {
"editor.colorScheme": id,
"editor.fontFamily": "JetBrains Maple Mono",
"editor.fontSize": 17,
// (18 + 6) × the default spacing 1.2, rounded up, as WebStorm draws it.
"editor.lineHeight": 29,
"editor.ligatures": true,
"files.trimTrailingWhitespace": true,
"editor.general.stripTrailingScope": "all",
@@ -83,8 +88,8 @@ describe("planJetBrainsImport", () => {
expect(plan.invalid).toEqual([]);
});
it("writes only the keys present, and derives the line height from IDEA's spacing", () => {
const plan = planJetBrainsImport(
it("writes only the keys present, and derives the line height from IDEA's spacing", async () => {
const plan = await planJetBrainsImport(
{
entries: [],
files: {
@@ -98,32 +103,50 @@ describe("planJetBrainsImport", () => {
},
},
editor,
fontHeight,
);
expect(plan.writes).toEqual([
["editor.lineHeight", 20],
// (14 + 4) × 1.5
["editor.lineHeight", 27],
["files.trimTrailingWhitespace", false],
["editor.softWrap", true],
]);
expect(plan.skipped).toEqual([]);
});
it("re-importing replaces the earlier copy of a scheme and drops its edits", () => {
const first = Object.fromEntries(planJetBrainsImport(webstorm, editor).writes);
it("re-importing replaces the earlier copy of a scheme and drops its edits", async () => {
const first = Object.fromEntries((await planJetBrainsImport(webstorm, editor, fontHeight)).writes);
const customs = first["editor.customSchemes"] as typeof editor.customSchemes;
const [id] = Object.keys(customs);
const again = planJetBrainsImport(webstorm, {
...editor,
customSchemes: customs,
colorOverrides: { [id!]: { keyword: { bold: true } }, other: {} },
});
const again = await planJetBrainsImport(
webstorm,
{
...editor,
customSchemes: customs,
colorOverrides: { [id!]: { keyword: { bold: true } }, other: {} },
},
fontHeight,
);
const writes = Object.fromEntries(again.writes);
expect(Object.keys(writes["editor.customSchemes"] as object)).toEqual([id]);
expect(writes["editor.colorOverrides"]).toEqual({ other: {} });
expect(writes["editor.colorScheme"]).toBe(id);
});
it("skips colour schemes that cannot be read", () => {
const plan = planJetBrainsImport({ entries: [], files: { "colors/broken.icls": "<nope" } }, editor);
it("falls back to the font size when the font cannot be measured", async () => {
const plan = await planJetBrainsImport(
{ entries: [], files: { "options/editor-font.xml": component("DefaultFont", { FONT_SIZE: "20" }) } },
editor,
() => undefined,
);
expect(plan.writes).toEqual([
["editor.fontSize", 20],
["editor.lineHeight", 29],
]);
});
it("skips colour schemes that cannot be read", async () => {
const plan = await planJetBrainsImport({ entries: [], files: { "colors/broken.icls": "<nope" } }, editor);
expect(plan.invalid).toEqual(["broken.icls"]);
expect(plan.writes).toEqual([]);
});
+4 -1
Переглянути файл
@@ -4,7 +4,7 @@ import { act, fireEvent, render, screen } from "@testing-library/react";
const read = vi.fn();
const set = vi.fn();
const notify = vi.fn();
const editor = { fontSize: 13, customSchemes: {}, colorOverrides: {} };
const editor = { fontFamily: "JetBrains Mono", fontSize: 13, customSchemes: {}, colorOverrides: {} };
vi.mock("@/platform/ipc", async (original) => {
const actual = await original<typeof import("@/platform/ipc")>();
@@ -44,6 +44,8 @@ beforeEach(() => {
},
});
set.mockResolvedValue({ status: "ok", data: { editor } });
// jsdom has no canvas: the import falls back to the font size for the line height.
vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockReturnValue(null);
});
it.each(["Cancel", "Import"])("confirms folder settings before applying them: %s", async (button) => {
@@ -78,6 +80,7 @@ it.each(["Cancel", "Import"])("confirms folder settings before applying them: %s
"editor.colorScheme": id,
"editor.fontFamily": "Monaco",
"editor.fontSize": 17,
"editor.lineHeight": 25,
});
expect(notify).toHaveBeenCalledWith(expect.objectContaining({ title: "Settings imported" }));
}
+44 -4
Переглянути файл
@@ -8,6 +8,7 @@
import { Fragment } from "react";
import type { JetBrainsSettings } from "@/bindings";
import { customSchemes } from "@/platform/colorScheme";
import { createFontProbeCanvas, fontsLoaded, monoFontFamily } from "@/platform/fonts";
import { tx } from "@/platform/i18n";
import { importScheme, parseIcls } from "@/platform/icls";
import { call, commands } from "@/platform/ipc";
@@ -28,6 +29,7 @@ export interface JetBrainsImportPlan {
}
interface EditorState {
fontFamily: string;
fontSize: number | null;
customSchemes: unknown;
colorOverrides: Record<string, unknown>;
@@ -63,7 +65,39 @@ const num = (v: string | undefined) => {
const onOff = (v: boolean) => (v ? tx("On") : tx("Off"));
export function planJetBrainsImport(bundle: JetBrainsSettings, editor: EditorState): JetBrainsImportPlan {
/** IDEA's `LINE_SPACING` when the export leaves it out. */
const DEFAULT_LINE_SPACING = 1.2;
/** The font's own line height in px, as IDEA's editor takes it from Java's FontMetrics. */
export type FontHeight = (family: string, size: number) => Promise<number | undefined> | number | undefined;
/** WebKit reports whole-pixel metrics; measured this large, they keep the font's fractions. */
const PROBE_SIZE = 1000;
async function measuredFontHeight(family: string, size: number): Promise<number | undefined> {
// The editor's own stack: WKWebView draws an installed font only through its loaded alias.
const stack = monoFontFamily(family);
await fontsLoaded(stack, size);
const canvas = createFontProbeCanvas();
try {
const ctx = canvas.getContext("2d");
if (!ctx) return undefined;
ctx.font = `${PROBE_SIZE}px ${stack}`;
const m = ctx.measureText("M");
// Java rounds the ascent and the descent up separately (anything past .05 of a pixel).
const px = (v: number) => Math.floor((v / PROBE_SIZE) * size + 0.95);
const h = px(m.fontBoundingBoxAscent) + px(m.fontBoundingBoxDescent);
return Number.isFinite(h) && h > 0 ? h : undefined;
} finally {
canvas.remove();
}
}
export async function planJetBrainsImport(
bundle: JetBrainsSettings,
editor: EditorState,
fontHeight: FontHeight = measuredFontHeight,
): Promise<JetBrainsImportPlan> {
const plan: JetBrainsImportPlan = { writes: [], rows: [], skipped: [], invalid: [] };
const add = (key: string, value: string | number | boolean | undefined, label: string, shown?: string) => {
if (value === undefined) return;
@@ -101,12 +135,18 @@ export function planJetBrainsImport(bundle: JetBrainsSettings, editor: EditorSta
}
const font = options(bundle.files["options/editor-font.xml"], "DefaultFont");
add("editor.fontFamily", font.get("FONT_FAMILY")?.trim() || undefined, tx("Font"));
const family = font.get("FONT_FAMILY")?.trim() || undefined;
add("editor.fontFamily", family, tx("Font"));
const size = num(font.get("FONT_SIZE"));
add("editor.fontSize", size, tx("Size"));
const spacing = num(font.get("LINE_SPACING"));
// IDEA spaces lines by the font's own height, not its size, so a tall font keeps its
// spacing; and the default spacing still applies when only the font changed.
const base = size ?? editor.fontSize;
add("editor.lineHeight", spacing && base ? Math.round(base * spacing) : undefined, tx("Line height"));
if (base && (family || size || spacing)) {
const natural = (await fontHeight(family ?? editor.fontFamily, base)) ?? base * DEFAULT_LINE_SPACING;
add("editor.lineHeight", Math.ceil(natural * (spacing ?? DEFAULT_LINE_SPACING)), tx("Line height"));
}
add("editor.ligatures", bool(font.get("USE_LIGATURES")), tx("Enable ligatures"));
const ed = options(bundle.files["options/editor.xml"], "EditorSettings");
@@ -174,7 +214,7 @@ function Summary({ plan }: { plan: JetBrainsImportPlan }) {
export async function importJetBrainsSettings(path: string) {
const bundle = await call(commands.settingsReadJetbrains(path));
const { editor } = await commands.settingsGetGlobal();
const plan = planJetBrainsImport(bundle, editor);
const plan = await planJetBrainsImport(bundle, editor);
if (!plan.writes.length) {
notifications().notify({
level: "warning",
+23 -2
Переглянути файл
@@ -251,8 +251,6 @@
min-height: 0;
display: flex;
flex-direction: column;
/* Data source colours are stronger than file colours. */
--row-tint-strength: var(--tint-strength);
}
.treeHost > * {
flex: 1;
@@ -264,6 +262,29 @@
gap: var(--space-1-5);
min-width: 0;
}
/* The whole tree row, indent included, so a coloured source and its children form one band. */
.tintedRow:not([aria-selected="true"]):not(:hover) {
border-radius: 0;
background: color-mix(in srgb, var(--db-tint) var(--tint-strength), transparent);
}
.tintRed {
--db-tint: var(--db-color-red);
}
.tintOrange {
--db-tint: var(--db-color-orange);
}
.tintYellow {
--db-tint: var(--db-color-yellow);
}
.tintGreen {
--db-tint: var(--db-color-green);
}
.tintBlue {
--db-tint: var(--db-color-blue);
}
.tintViolet {
--db-tint: var(--db-color-violet);
}
.nodeLabel {
overflow: hidden;
text-overflow: ellipsis;
+5 -5
Переглянути файл
@@ -8,6 +8,7 @@ import { tablesKey, useDatabase } from "./store";
import { tableInput } from "./tableInput";
import { useEditorRegistry } from "@/editor/api";
import { provideEditorService, provideToolWindowService, type EditorInput } from "@/workbench/contributions";
import styles from "./Database.module.css";
vi.mock("@tanstack/react-virtual", () => ({
useVirtualizer: ({ count }: { count: number }) => ({
@@ -194,10 +195,9 @@ describe("data source colour", () => {
});
render(<DatabaseView />);
const tree = within(screen.getByRole("tree", { name: "Data sources" }));
const tint = (name: string) =>
tree.getByText(name).closest<HTMLElement>('[role="treeitem"]')!.style.getPropertyValue("--row-tint");
for (const name of ["PostgreSQL", "public", "routines", "refresh_data"])
expect(tint(name)).toBe("var(--db-color-red)");
expect(tint("SQLite")).toBe("");
for (const name of ["PostgreSQL", "public", "routines", "refresh_data"]) {
expect(tree.getByText(name).closest('[role="treeitem"]')).toHaveClass(styles.tintedRow!, styles.tintRed!);
}
expect(tree.getByText("SQLite").closest('[role="treeitem"]')).not.toHaveClass(styles.tintedRow!);
});
});
+12 -3
Переглянути файл
@@ -6,7 +6,7 @@
* source to open its query console.
*/
import { useEffect, useMemo, useRef } from "react";
import type { DbDatabases, DbTableDetails } from "@/platform/ipc";
import type { DbColor, DbDatabases, DbTableDetails } from "@/platform/ipc";
import { executeAction } from "@/platform/actions";
import { shortcutLabel } from "@/platform/keymap";
import {
@@ -55,6 +55,15 @@ import styles from "./Database.module.css";
import { tx } from "@/platform/i18n";
import { databaseRequest } from "./requests";
const ROW_TINTS: Record<DbColor, string | undefined> = {
red: styles.tintRed,
orange: styles.tintOrange,
yellow: styles.tintYellow,
green: styles.tintGreen,
blue: styles.tintBlue,
violet: styles.tintViolet,
};
const GROUP_LABELS: Record<Group, string> = {
columns: "columns",
keys: "keys",
@@ -516,11 +525,11 @@ export function DatabaseView() {
getIcon={(n) => icon(n)}
getDetail={detail}
getColor={(n) => (n.kind === "message" && n.error ? "var(--danger)" : undefined)}
rowTint={(n) => {
rowClassName={(n) => {
// IDEA tints every row of a coloured data source across its full width and height.
const target = nodeTarget(n);
const color = target ? sourceOf(target)?.color : null;
return color ? `var(--db-color-${color})` : undefined;
return color ? `${styles.tintedRow} ${ROW_TINTS[color]}` : undefined;
}}
speedSearchField
renderNode={(n: Node, state) => {
+3
Переглянути файл
@@ -56,6 +56,9 @@
.excluded {
color: var(--vcs-ignored);
}
.excludedRow {
background: color-mix(in srgb, var(--vcs-ignored) 14%, transparent);
}
.error {
text-decoration-line: underline;
text-decoration-style: wavy;
+5 -4
Переглянути файл
@@ -436,8 +436,6 @@ interface DragState {
}
const DRAG_THRESHOLD = 4;
/** IDEA's "excluded" look: excluded folders and what is under them get a muted band. */
const EXCLUDED_TINT = "var(--vcs-ignored)";
/** Folder under a viewport point inside `container` (a file row resolves to its folder). */
function folderAt(container: HTMLElement | null, x: number, y: number): { key: string; path: string } | null {
@@ -875,8 +873,11 @@ export function ProjectView() {
isExpandable={isExpandable}
loadChildren={loadChildren}
renderNode={renderNode}
rowTint={(n) =>
n.excluded ? EXCLUDED_TINT : n.group || n.placeholder ? undefined : fileColors?.(n.path, n.dir)
rowClassName={(n) => (n.excluded ? styles.excludedRow : undefined)}
rowTint={
fileColors
? (n) => (n.excluded || n.group || n.placeholder ? undefined : fileColors(n.path, n.dir))
: undefined
}
expanded={expanded}
onExpandedChange={onExpandedChange}
+10 -11
Переглянути файл
@@ -39,8 +39,6 @@
.sizer {
position: relative;
width: 100%;
/* Keeps the tint bands of rows above the tree's background. */
isolation: isolate;
}
.row {
position: absolute;
@@ -70,15 +68,16 @@
.row:hover {
background: var(--bg-tree-hover, color-mix(in srgb, var(--fg-strong) 4%, transparent));
}
/* File Colors: a full-width band under the row, so runs of tinted rows read as one block;
hover and selection stay rounded on top of it. */
.tinted::before {
content: "";
position: absolute;
inset: 0 calc(-1 * var(--tree-inset, 6px));
z-index: -1;
background: color-mix(in srgb, var(--row-tint) var(--row-tint-strength, var(--file-tint-strength, 14%)), transparent);
pointer-events: none;
/* File Colors: the row's background takes its scope's colour. */
.tinted {
background: color-mix(in srgb, var(--row-tint) var(--file-tint-strength, 14%), transparent);
}
.tinted:hover {
background: color-mix(
in srgb,
var(--row-tint) var(--file-tint-strength, 14%),
var(--bg-tree-hover, color-mix(in srgb, var(--fg-strong) 4%, transparent))
);
}
/* Tree.selectionInactiveBackground when unfocused, selectionBackground when focused. */
.selected,