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

...
Автор SHA1 Повідомлення Дата
l0ng-ai 7cfe01122b fix(hierarchy): show no expand arrow on types without subtypes
The type hierarchy loaded a level only when its node was expanded, so every
type showed an expand arrow, also one without subtypes. The level below each
shown type is now loaded ahead, four requests at a time, so a leaf shows as
one. Call hierarchies stay lazy.

Fixes #2471
2026-11-10 23:34:28 +08:00
l0ng-ai 828db7bd13 fix(hierarchy): let the hierarchy tab be closed (#2552)
The Hierarchy tool window's content tab had no close button, so a type or
call hierarchy stayed until another one replaced it. The tab is closable
now; closing it clears the tree and hides the tool window, which has no
other content.

Refs #2471
2026-11-10 23:32:55 +08:00
l0ng-ai ef1421012a fix(refactor): type a chained call by its last call in Introduce Variable (#2551)
When the code has errors (e.g. a statement without its semicolon), Introduce
Variable falls back to a syntax-based declaration and types it from the hover
of the call the expression ends in. That call was found with a greedy regex,
so in `demo.getList().get(0)` the argument list swallowed `().get(0)` and
the hover of `getList` typed the variable as `List<String>`. The trailing
call is now found by matching its parentheses.

Fixes #2509
2026-11-10 23:30:56 +08:00
l0ng-ai 96e12d8d9f fix(kotlin): colour annotation names as annotations (#2549)
The JetBrains Kotlin LSP reports an annotation usage as a constructor call
(`method`), so the name after `@` took the Function call colour while the
`@` had Metadata. Names of annotation usages, including use-site targets
(`@field:Name`) and nested names (`@Outer.Inner`), now get the annotation
class; labels such as `return@forEach` and `this@Outer` are left alone.

Fixes #2543
2026-11-10 23:27:17 +08:00
l0ng-ai dc99fc83d2 fix(debugger): keep the selected tab when a step finishes (#2548)
Every pause brought Threads & Variables to the front, so stepping from the Console tab switched away from the output after each Step Over. Only a stop at a breakpoint, exception or pause request does that now; finishing a step keeps the tab the user is on.

Refs #2494
2026-11-10 23:22:45 +08:00
l0ng-ai ce7eb155b0 fix(http): read environment files saved with a byte order mark (#2547)
Editors on Windows such as Notepad save UTF-8 with a BOM, which serde_json rejects, so such an http-client.env.json offered no environments.

Refs #2435
2026-11-10 23:20:58 +08:00
devтаdevadapter 6788447d3a fix(security): run credential store access off the async runtime (#2459)
On Linux, saving a password (e.g. a new data source with Save password ticked) left the dialog on Connecting…: the Secret Service client runs its blocking calls on a tokio runtime of its own, and from a Tauri command thread the nested block_on panicked with "Cannot start a runtime from within a runtime"; keyring's poisoned LazyLock then made every later password access panic until restart. SecretFile, used for database, SSH, git and proxy passwords, now runs store access on a plain thread when called from async code.

Co-authored-by: devadapter <[email protected]>
2026-11-10 23:19:24 +08:00
zaojiaociтаzaojiaoci 2ad642cdc9 fix(plugins): keep pinned program paths out of the verbatim form (#2012)
std::fs::canonicalize returns \\?\-prefixed paths on Windows, so a process grant's pinned program path was stored in that form. Canonicalize the program's directory with dunce, which keeps the usual form.

Fixes #2001

Co-authored-by: zaojiaoci <[email protected]>
2026-11-10 23:19:14 +08:00
14 змінених файлів з 397 додано та 75 видалено

No files matched your search

+1
Переглянути файл
@@ -18,6 +18,7 @@ semver = "1"
blake3.workspace = true
zip.workspace = true
base64.workspace = true
dunce.workspace = true
ed25519-dalek = "3"
[dev-dependencies]
+18 -2
Переглянути файл
@@ -441,11 +441,13 @@ pub fn resolve_program(name: &str, path_var: Option<&OsStr>) -> Result<PathBuf,
/// `p` with its parent canonicalized but the file name as found: PATH
/// entries like `/var` → `/private/var` (macOS) or `~` links collapse to
/// their real directory, while a linked program (`cargo` → rustup) keeps
/// its link name so the shim still dispatches on argv[0].
/// its link name so the shim still dispatches on argv[0]. `dunce` keeps the
/// path in its usual form on Windows: a `\\?\`-prefixed pin would never
/// match the path the program was actually started with.
fn canonical_dir(p: &Path) -> PathBuf {
let Some(dir) = p.parent() else { return p.to_path_buf() };
let Some(name) = p.file_name() else { return p.to_path_buf() };
std::fs::canonicalize(dir).map(|d| d.join(name)).unwrap_or_else(|_| p.to_path_buf())
dunce::canonicalize(dir).map(|d| d.join(name)).unwrap_or_else(|_| p.to_path_buf())
}
fn is_executable(p: &Path) -> bool {
@@ -498,6 +500,20 @@ mod tests {
list.iter().map(|s| s.parse().unwrap()).collect()
}
#[test]
#[cfg(windows)]
fn pinned_program_path_has_no_verbatim_prefix() {
// std::fs::canonicalize returns \\?\-prefixed paths on Windows; a pin
// stored in that form would never match the plain path the program is
// started with. dunce keeps the usual form.
let dir = tempfile::tempdir().unwrap();
std::fs::write(dir.path().join("cargo.exe"), b"").unwrap();
let pinned = resolve_program("cargo.exe", Some(dir.path().as_os_str())).unwrap();
let shown = pinned.to_string_lossy();
assert!(!shown.starts_with(r"\\?\"), "verbatim prefix leaked into the pin: {shown}");
assert!(pinned.is_absolute());
}
fn req<'a>(version: &'a str, hash: &'a str, required: &[&str], optional: &[&str]) -> Request<'a> {
Request {
subject: Subject::Installed("p".into()),
+10
Переглянути файл
@@ -52,6 +52,8 @@ fn search_dirs(file: Option<&Path>, root: Option<&Path>) -> Vec<PathBuf> {
}
fn parse_env(text: &str) -> IdeResult<EnvMap> {
// Editors on Windows (Notepad) save UTF-8 with a byte order mark, which serde_json rejects.
let text = text.strip_prefix('\u{feff}').unwrap_or(text);
let value: serde_json::Value =
serde_json::from_str(text).map_err(|e| IdeError::invalid(format!("invalid environment file: {e}")))?;
let mut out = EnvMap::new();
@@ -262,4 +264,12 @@ mod tests {
let envs = Environments::load(Some(&other.path().join("s.http")), Some(root)).unwrap();
assert_eq!(envs.names(), vec!["dev"]);
}
#[test]
fn reads_env_files_saved_with_a_byte_order_mark() {
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join(PUBLIC_FILE), "\u{feff}{\"dev\":{\"host\":\"h\"}}").unwrap();
let envs = Environments::load(Some(&tmp.path().join("a.http")), Some(tmp.path())).unwrap();
assert_eq!(envs.names(), vec!["dev"]);
}
}
+134 -62
Переглянути файл
@@ -101,6 +101,22 @@ fn new_id() -> String {
uuid::Uuid::new_v4().to_string()
}
/// Runs a credential-store operation off the async runtime.
///
/// The Linux Secret Service client is blocking (`zbus`) and starts a runtime of
/// its own; calling it while a runtime already drives the current thread panics
/// with "Cannot start a runtime from within a runtime". The store may also wait
/// on an OS prompt, so run it on a plain thread when called from async code.
fn off_runtime<R: Send>(f: impl FnOnce() -> R + Send) -> R {
if tokio::runtime::Handle::try_current().is_err() {
return f();
}
std::thread::scope(|scope| match scope.spawn(f).join() {
Ok(value) => value,
Err(panic) => std::panic::resume_unwind(panic),
})
}
impl SecretFile {
pub fn new(path: PathBuf) -> Self {
Self::with_legacy(path, |v| serde_json::from_value(v).ok())
@@ -115,85 +131,95 @@ impl SecretFile {
}
pub fn get(&self, key: &str) -> Option<String> {
let _g = LOCK.lock();
match self.load() {
Contents::Index(mut index) if index.keys.contains(key) => match self.vault.get(&service(&index.id), key) {
Ok(secret) => Some(secret),
Err(StoreError::NoEntry) => {
// Removed outside the app: stop listing it.
index.keys.remove(key);
self.write_logged(&index);
None
off_runtime(|| {
let _g = LOCK.lock();
match self.load() {
Contents::Index(mut index) if index.keys.contains(key) => {
match self.vault.get(&service(&index.id), key) {
Ok(secret) => Some(secret),
Err(StoreError::NoEntry) => {
// Removed outside the app: stop listing it.
index.keys.remove(key);
self.write_logged(&index);
None
}
Err(e) => {
tracing::warn!("saved passwords: {key}: {e}");
None
}
}
}
Err(e) => {
tracing::warn!("saved passwords: {key}: {e}");
None
}
},
Contents::Index(_) => None,
Contents::Plaintext(mut old, _) => old.remove(key),
}
Contents::Index(_) => None,
Contents::Plaintext(mut old, _) => old.remove(key),
}
})
}
pub fn set(&self, key: &str, secret: &str) -> IdeResult<()> {
let _g = LOCK.lock();
let mut index = match self.load() {
Contents::Index(index) => index,
Contents::Plaintext(_, why) => return Err(unavailable(&why)),
};
let service = service(&index.id);
self.vault.set(&service, key, secret).map_err(|e| unavailable(&e.to_string()))?;
if index.keys.insert(key.to_owned())
&& let Err(e) = self.write(&index)
{
let _ = self.vault.delete(&service, key);
return Err(e);
}
Ok(())
off_runtime(|| {
let _g = LOCK.lock();
let mut index = match self.load() {
Contents::Index(index) => index,
Contents::Plaintext(_, why) => return Err(unavailable(&why)),
};
let service = service(&index.id);
self.vault.set(&service, key, secret).map_err(|e| unavailable(&e.to_string()))?;
if index.keys.insert(key.to_owned())
&& let Err(e) = self.write(&index)
{
let _ = self.vault.delete(&service, key);
return Err(e);
}
Ok(())
})
}
pub fn delete(&self, key: &str) {
let _g = LOCK.lock();
match self.load() {
Contents::Index(mut index) => {
if !index.keys.contains(key) {
return;
off_runtime(|| {
let _g = LOCK.lock();
match self.load() {
Contents::Index(mut index) => {
if !index.keys.contains(key) {
return;
}
match self.vault.delete(&service(&index.id), key) {
Ok(()) | Err(StoreError::NoEntry) => {}
Err(e) => {
// Kept in the index so that the next delete tries again.
tracing::warn!("saved passwords: could not forget {key}: {e}");
return;
}
}
index.keys.remove(key);
self.write_logged(&index);
}
match self.vault.delete(&service(&index.id), key) {
Ok(()) | Err(StoreError::NoEntry) => {}
Err(e) => {
// Kept in the index so that the next delete tries again.
Contents::Plaintext(mut old, _) => {
if old.remove(key).is_none() {
return;
}
// A move halfway may have copied it already.
if let Some(id) = self.pending_id()
&& let Err(e) = self.vault.delete(&service(&id), key)
&& !matches!(e, StoreError::NoEntry)
{
tracing::warn!("saved passwords: could not forget {key}: {e}");
return;
}
self.write_logged(&old);
}
index.keys.remove(key);
self.write_logged(&index);
}
Contents::Plaintext(mut old, _) => {
if old.remove(key).is_none() {
return;
}
// A move halfway may have copied it already.
if let Some(id) = self.pending_id()
&& let Err(e) = self.vault.delete(&service(&id), key)
&& !matches!(e, StoreError::NoEntry)
{
tracing::warn!("saved passwords: could not forget {key}: {e}");
return;
}
self.write_logged(&old);
}
}
})
}
/// Every stored key, sorted (the secrets themselves stay private).
pub fn keys(&self) -> Vec<String> {
let _g = LOCK.lock();
match self.load() {
Contents::Index(index) => index.keys.into_iter().collect(),
Contents::Plaintext(old, _) => old.into_keys().collect(),
}
off_runtime(|| {
let _g = LOCK.lock();
match self.load() {
Contents::Index(index) => index.keys.into_iter().collect(),
Contents::Plaintext(old, _) => old.into_keys().collect(),
}
})
}
fn load(&self) -> Contents {
@@ -558,4 +584,50 @@ mod tests {
assert_eq!(mode & 0o777, 0o600);
}
}
/// A credential store that behaves like the Linux Secret Service client:
/// its blocking API runs a tokio runtime.
#[derive(Default)]
struct NestedRuntimeVault {
entries: Mutex<HashMap<(String, String), String>>,
}
fn nested_runtime() {
tokio::runtime::Builder::new_multi_thread().build().expect("a nested runtime").block_on(async {});
}
impl Vault for NestedRuntimeVault {
fn available(&self) -> bool {
true
}
fn get(&self, service: &str, key: &str) -> StoreResult<String> {
nested_runtime();
self.entries.lock().get(&(service.to_owned(), key.to_owned())).cloned().ok_or(StoreError::NoEntry)
}
fn set(&self, service: &str, key: &str, secret: &str) -> StoreResult<()> {
nested_runtime();
self.entries.lock().insert((service.to_owned(), key.to_owned()), secret.to_owned());
Ok(())
}
fn delete(&self, service: &str, key: &str) -> StoreResult<()> {
nested_runtime();
self.entries.lock().remove(&(service.to_owned(), key.to_owned())).map(|_| ()).ok_or(StoreError::NoEntry)
}
}
/// Saving a password from a Tauri command runs on a tokio runtime; the
/// Secret Service's blocking client starts a runtime of its own and panics
/// when both share a thread ("Cannot start a runtime from within a runtime").
#[tokio::test(flavor = "multi_thread")]
async fn credential_store_access_leaves_the_async_runtime_first() {
let tmp = tempfile::tempdir().unwrap();
let vault = Arc::new(NestedRuntimeVault::default());
let file =
SecretFile::with_vault(tmp.path().join("db-passwords.json"), |v| serde_json::from_value(v).ok(), vault);
file.set("s1", "hunter2").unwrap();
assert_eq!(file.get("s1").as_deref(), Some("hunter2"));
assert_eq!(file.keys(), ["s1"]);
file.delete("s1");
assert_eq!(file.get("s1"), None);
}
}
+39
Переглянути файл
@@ -1,5 +1,6 @@
import { describe, expect, it } from "vitest";
import { Text } from "@codemirror/state";
import { Tree } from "@lezer/common";
import { semanticRanges } from "../index";
describe("Kotlin semantic tokens", () => {
@@ -42,4 +43,42 @@ describe("Kotlin semantic tokens", () => {
)[0]?.className,
).toBe("cm-sem-property");
});
it("colours annotation names as annotations, not as the constructor calls the server reports", () => {
const lines = [
'@Column(name = "x")',
"@field:Inject @Outer.Inner",
"list.forEach { return@forEach }",
"[email protected]()",
];
const doc = Text.of(lines);
const types = ["method", "class", "label"];
const tok = (line: number, word: string, type: string) => [
line,
lines[line]!.lastIndexOf(word),
word.length,
types.indexOf(type),
0,
];
const data = [
tok(0, "Column", "method"),
tok(1, "Inject", "class"),
tok(1, "Outer", "class"),
tok(1, "Inner", "class"),
tok(2, "forEach", "label"),
tok(3, "Outer", "class"),
].flat();
const tokens = { tokenTypes: types, tokenModifiers: [], data };
const ranges = semanticRanges(doc, tokens, false, "kotlin", Tree.empty);
const classOf = (line: number, word: string) => {
const from = doc.line(line + 1).from + lines[line]!.lastIndexOf(word);
return ranges.find((r) => r.from === from)?.className;
};
expect(classOf(0, "Column")).toBe("cm-sem-annotation");
expect(classOf(1, "Inject")).toBe("cm-sem-annotation");
expect(classOf(1, "Outer")).toBe("cm-sem-annotation");
expect(classOf(1, "Inner")).toBe("cm-sem-annotation");
expect(classOf(2, "forEach")).toBe("cm-sem-constant");
expect(classOf(3, "Outer")).not.toBe("cm-sem-annotation");
});
});
+43 -1
Переглянути файл
@@ -1,7 +1,49 @@
import type { Text } from "@codemirror/state";
import { registerLanguageSemantics, type LanguageSemantics } from "../languages";
const NAME = /[A-Za-z_][\w]*/y;
/**
* The names of annotation usages (`@Column`, `@field:Column`, `@Outer.Inner`), as `"from:to"` → `"annotation"`.
* An `@` right after a name is a label (`return@forEach`, `this@Outer`, `loop@`), not an annotation.
*/
function annotationNames(doc: Text): Map<string, string> {
const out = new Map<string, string>();
const text = doc.toString();
for (let at = text.indexOf("@"); at >= 0; at = text.indexOf("@", at + 1)) {
if (/[\w`]/.test(text[at - 1] ?? "")) continue;
let pos = at + 1;
const name = () => {
NAME.lastIndex = pos;
const m = NAME.exec(text);
return m ? { from: pos, to: pos + m[0].length } : null;
};
let first = name();
// A use-site target (`@field:`, `@get:`, `@file:`) precedes the annotation's name.
if (first && text[first.to] === ":" && text[first.to + 1] !== ":") {
pos = first.to + 1;
first = name();
}
for (let part = first; part;) {
out.set(`${part.from}:${part.to}`, "annotation");
if (text[part.to] !== ".") break;
pos = part.to + 1;
part = name();
}
}
return out;
}
const kotlinSemantics: LanguageSemantics = {
tokenClasses({ type, modifiers, classes }) {
symbolKinds: (_tree, doc) => annotationNames(doc),
tokenClasses({ type, modifiers, kind, classes }) {
// JetBrains Kotlin LSP reports an annotation usage as a constructor call (`method`);
// IDEA colours the name as an annotation (Metadata), like its `@`.
if (kind === "annotation" && type !== "label") {
classes.length = 0;
classes.push("cm-sem-annotation");
return;
}
if (type === "operator" && modifiers.includes("declaration")) classes.push("cm-sem-function");
// JetBrains Kotlin LSP uses `modification` for mutable declarations and references.
if ((type === "variable" || type === "property" || type === "parameter") && modifiers.includes("modification"))
+6 -5
Переглянути файл
@@ -30,6 +30,7 @@ import {
javaTypeFromHover,
literalType,
replacesBareStatement,
trailingName,
variableDeclaration,
type DeclContext,
type DeclResult,
@@ -378,17 +379,17 @@ function usesSemicolons(doc: Text, statement: SyntaxNode): boolean {
/** Return / declared type of a Java call or name from the server's hover, if it answers. */
async function javaHoverType(p: Prepared, expr: SyntaxNode, text: string): Promise<string | null> {
const m = /([A-Za-z_$][\w$]*)\s*(\([\s\S]*\))?\s*$/.exec(text);
if (!m || !/method_invocation|identifier|field_access/.test(expr.kind)) return null;
const last = trailingName(text);
if (!last || !/method_invocation|identifier|field_access/.test(expr.kind)) return null;
const { from } = rangeToOffsets(p.doc, expr.range);
const pos = p.doc.lineAt(from + m.index);
const at = { line: pos.number - 1, col: from + m.index - pos.from };
const pos = p.doc.lineAt(from + last.index);
const at = { line: pos.number - 1, col: from + last.index - pos.from };
try {
const hover = await Promise.race([
call(commands.lspHover(nextRequestId(), p.ctx.doc, at)),
new Promise<null>((resolve) => setTimeout(() => resolve(null), 1500)),
]);
return hover ? javaTypeFromHover(hover.contents.value, m[1]!) : null;
return hover ? javaTypeFromHover(hover.contents.value, last.name) : null;
} catch {
return null;
}
+10
Переглянути файл
@@ -5,6 +5,7 @@ import {
isLiteral,
javaConstructedType,
javaTypeFromHover,
trailingName,
literalType,
replacesBareStatement,
variableDeclaration,
@@ -152,6 +153,15 @@ describe("templates", () => {
expect(isLiteral("kotlin", "identifier", "true")).toBe(true);
});
it("finds the name a chained expression ends in, for the hover that types it", () => {
expect(trailingName("demo.getList().get(0)")).toEqual({ name: "get", index: 15 });
expect(trailingName("a.b(c(d)).e")).toEqual({ name: "e", index: 10 });
expect(trailingName("names()")).toEqual({ name: "names", index: 0 });
expect(trailingName("list.get(i) ")).toEqual({ name: "get", index: 5 });
expect(trailingName("(a + b)")).toBeNull();
expect(trailingName("x)")).toBeNull();
});
it("reads a Java type from a jdtls hover", () => {
expect(javaTypeFromHover("```java\nString java.lang.String.trim()\n```", "trim")).toBe("String");
expect(javaTypeFromHover("```java\njava.util.List<java.lang.String> a.B.names()\n```", "names")).toBe(
+21
Переглянути файл
@@ -229,6 +229,27 @@ export function javaConstructedType(text: string): string | null {
return obj[1]!.replace(/\s+/g, "");
}
/**
* The name an expression ends in — the last call's method (`a.b().c(0)` → `c`) or the last
* name (`a.b` → `b`) — with its offset in `text`. Null when it ends in something else.
*/
export function trailingName(text: string): { name: string; index: number } | null {
let end = text.trimEnd().length;
if (text[end - 1] === ")") {
// Back to the `(` that opens the trailing argument list.
let depth = 0;
let i = end - 1;
for (; i >= 0; i--) {
if (text[i] === ")") depth++;
else if (text[i] === "(" && --depth === 0) break;
}
if (i < 0) return null;
end = text.slice(0, i).trimEnd().length;
}
const m = /[A-Za-z_$][\w$]*$/.exec(text.slice(0, end));
return m ? { name: m[0], index: m.index } : null;
}
/**
* Type of a Java expression from a jdtls-style hover (```java\nString java.lang.String.trim()\n```
* or `String name`), for a call / name ending in `name`. Null when unclear.
+8 -1
Переглянути файл
@@ -17,11 +17,13 @@ import {
} from "@/ui";
import { openLocation } from "./ipc";
import {
closeHierarchy,
ROOT_ID,
directionLabel,
hierarchyTitle,
hierarchyTarget,
loadChildren,
prefetchLevels,
refreshHierarchy,
noneFoundLabel,
setDirection,
@@ -64,9 +66,10 @@ export function HierarchyTabs() {
variant="compact"
className={styles.tabs}
aria-label="Hierarchies"
items={[{ id: "current", label }]}
items={[{ id: "current", label, closable: true }]}
activeId="current"
onSelect={() => undefined}
onClose={closeHierarchy}
/>
);
}
@@ -220,6 +223,10 @@ export function HierarchyView() {
getChildren={getChildren}
isExpandable={isExpandable}
loadChildren={(n) => (n.kind === "item" ? loadChildren(n.node) : undefined)}
onExpandedChange={(_expanded, n, open) => {
const shown = open ? children.get(n.id) : undefined;
if (shown) prefetchLevels(shown);
}}
defaultExpanded={[ROOT_ID]}
handleRef={tree}
isOccurrence={() => true}
+49 -1
Переглянути файл
@@ -2,9 +2,10 @@ import { describe, expect, it, vi } from "vitest";
import type { HierarchyItem, OutlineItem, ReferencesIncomplete, SymbolKind } from "@/bindings";
const hint = vi.fn();
const hide = vi.hoisted(() => vi.fn());
vi.mock("@/workbench/contributions", async (orig) => ({
...(await orig<typeof import("@/workbench/contributions")>()),
toolWindowService: () => ({ show: () => undefined }),
toolWindowService: () => ({ show: () => undefined, hide }),
}));
const range = (l1: number, c1: number, l2: number, c2: number) => ({
@@ -54,6 +55,20 @@ const callHierarchy = vi.fn((): { items: HierarchyItem[]; incomplete: References
incomplete: null,
}));
const cancelRequest = vi.fn(async () => undefined);
// Subtypes by the line of the type asked about: the caret's type → Long (30), Striped64 (40); Striped64 → LongAdder (50).
const typeItem = (name: string, line: number): HierarchyItem => ({
...item(name),
kind: "class",
path: "/p/Types.java",
selectionRange: range(line, 0, line, name.length),
});
const typeHierarchy = vi.fn((pos: { line: number; col: number }): HierarchyItem[] =>
pos.line === 40
? [typeItem("LongAdder", 50)]
: pos.line < 30
? [typeItem("Long", 30), typeItem("Striped64", 40)]
: [],
);
// The positions a hierarchy request is answered at; anything else is "no symbol".
let servedAt = (pos: { line: number; col: number }) => pos.line === 2 && pos.col === 7;
@@ -66,6 +81,7 @@ vi.mock("@/platform/ipc", async (orig) => {
...real.commands,
docOutline: async () => OUTLINE,
cancelRequest,
lspTypeHierarchy: async (_doc: number, pos: { line: number; col: number }) => typeHierarchy(pos),
lspCallHierarchy: async (_request: number, _doc: number, pos: { line: number; col: number }) => {
// The server prepares a hierarchy only on the method name.
if (!servedAt(pos)) throw new real.IpcError({ kind: "notFound", message: "No symbol" });
@@ -167,3 +183,35 @@ describe("hierarchy", () => {
}
});
});
describe("type hierarchy", () => {
it("loads each shown type's level ahead, so a type without subtypes shows no expand arrow", async () => {
servedAt = () => true;
try {
useHierarchy.setState({ mode: "type", direction: "outgoing" });
await showHierarchy("type");
const [long, striped] = useHierarchy.getState().children.get(ROOT_ID) ?? [];
await vi.waitFor(() => {
const { children } = useHierarchy.getState();
expect(children.get(long!.id)).toEqual([]);
expect(children.get(striped!.id)?.map((n) => n.item.name)).toEqual(["LongAdder"]);
});
const { children } = useHierarchy.getState();
// Only the shown levels: LongAdder's subtypes wait until Striped64 is expanded.
expect(children.has(children.get(striped!.id)![0]!.id)).toBe(false);
} finally {
servedAt = (pos) => pos.line === 2 && pos.col === 7;
useHierarchy.setState({ mode: "call", direction: "incoming" });
}
});
});
describe("closing the hierarchy tab", () => {
it("clears the tree and hides the tool window", async () => {
const { closeHierarchy, useHierarchy } = await import("./hierarchy");
useHierarchy.setState({ root: { name: "Number", path: "/p/Number.java", line: 0, col: 0 } as never });
closeHierarchy();
expect(useHierarchy.getState().root).toBeNull();
expect(hide).toHaveBeenCalledWith("hierarchy");
});
});
+45 -2
Переглянути файл
@@ -73,6 +73,12 @@ export function resetHierarchy() {
}));
}
/** Closes the hierarchy's content tab; with no content left the tool window hides. */
export function closeHierarchy() {
resetHierarchy();
toolWindowService().hide("hierarchy");
}
/** The empty-result line of the hierarchy tree. */
export function noneFoundLabel(mode: HierarchyMode, direction: HierarchyDirection): string {
if (mode === "call") return direction === "incoming" ? tx`— no callers found` : tx`— no callees found`;
@@ -171,6 +177,7 @@ async function loadRoot(quiet = false): Promise<RootResult> {
request(s.mode, doc, root.line, root.col, s.direction),
);
setChildren(generation, ROOT_ID, [rootKey(root)], items, incomplete && incompleteNote(incomplete, root.name));
prefetchLevels(useHierarchy.getState().children.get(ROOT_ID) ?? []);
return "loaded";
} catch (e) {
if (useHierarchy.getState().generation !== generation) return "stale";
@@ -214,7 +221,8 @@ async function enclosingRoot(c: CaretContext, mode: HierarchyMode): Promise<Hier
return null;
}
}
export async function loadChildren(node: HierarchyNode) {
/** Loads `node`'s level. `ahead`: a look-ahead load (prefetchLevels), which reports nothing. */
export async function loadChildren(node: HierarchyNode, ahead = false) {
const { mode, direction, generation } = useHierarchy.getState();
const at = node.item.selectionRange.start;
try {
@@ -228,8 +236,9 @@ export async function loadChildren(node: HierarchyNode) {
items,
incomplete && incompleteNote(incomplete, node.item.name),
);
if (!ahead) prefetchLevels(useHierarchy.getState().children.get(node.id) ?? []);
} catch (e) {
if (useHierarchy.getState().generation !== generation) return;
if (ahead || useHierarchy.getState().generation !== generation) return;
useHierarchy.setState((st) => ({
failed: new Set(st.failed).add(node.id),
children: new Map(st.children).set(node.id, []),
@@ -238,6 +247,40 @@ export async function loadChildren(node: HierarchyNode) {
}
}
const AHEAD_CONCURRENCY = 4;
const ahead: HierarchyNode[] = [];
let aheadRunning = 0;
let aheadGeneration = -1;
/**
* IDEA's type hierarchy shows no expand arrow on a type without subtypes (or supertypes): the
* level below each shown node is loaded ahead, a few requests at a time. Call hierarchies stay
* lazy, as in IDEA.
*/
export function prefetchLevels(nodes: readonly HierarchyNode[]) {
const { mode, generation, children } = useHierarchy.getState();
if (mode !== "type") return;
if (aheadGeneration !== generation) {
ahead.length = 0;
aheadGeneration = generation;
}
for (const n of nodes) if (!n.recursion && !children.has(n.id) && !ahead.includes(n)) ahead.push(n);
pumpAhead();
}
function pumpAhead() {
while (aheadRunning < AHEAD_CONCURRENCY && ahead.length) {
const node = ahead.shift()!;
const { generation, children } = useHierarchy.getState();
if (generation !== aheadGeneration || children.has(node.id)) continue;
aheadRunning++;
void loadChildren(node, true).finally(() => {
aheadRunning--;
pumpAhead();
});
}
}
export async function showHierarchy(mode: HierarchyMode) {
const c = caretContext();
if (!c) {
+5
Переглянути файл
@@ -134,6 +134,11 @@ describe("debug tool window", () => {
expect(console.getAttribute("aria-selected")).toBe("true");
act(() => useDebug.setState({ sessions: { 1: session } }));
expect(variables.getAttribute("aria-selected")).toBe("true");
// Stepping from the Console keeps it in front.
fireEvent.click(console);
act(() => useDebug.setState({ sessions: { 1: { ...session, status: "running" } } }));
act(() => useDebug.setState({ sessions: { 1: { ...session, stopReason: "step" } } }));
expect(console.getAttribute("aria-selected")).toBe("true");
});
it("renders session tabs, views, frames and typed variables", async () => {
+8 -1
Переглянути файл
@@ -153,7 +153,14 @@ export function DebugToolWindow() {
setView({
session: active.startedAt,
status: active.status,
tab: active.status === "starting" ? "console" : active.status === "paused" ? "variables" : view.tab,
// A breakpoint or exception brings Threads & Variables to the front; finishing a step keeps
// the tab the user is on (e.g. Console, to watch the output while stepping).
tab:
active.status === "starting"
? "console"
: active.status === "paused" && active.stopReason !== "step"
? "variables"
: view.tab,
});
const tab = view.tab;