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

..
Автор SHA1 Повідомлення Дата
l0ng-ai 5b151180de fix(debugger): quick-evaluate the whole method call under the mouse
Quick Evaluate took only the identifier and its member chain, so Alt+Click on
getX in o.getX() sent o.getX, which a Java adapter resolves as a field. It also
asked with the hover context, in which adapters refuse to call methods.

Quick Evaluate and the Evaluate dialog's seed now take the call of the clicked
identifier (balanced arguments, strings skipped) and member chains through calls
and indexing (a.getB().c(), items[i].name), and Quick Evaluate evaluates in the
watch context. Plain hovers and value-on-selection keep the side-effect-free
identifier and hover context.
2026-11-20 19:52:35 +08:00
34 змінених файлів з 92 додано та 581 видалено

No files matched your search

+24 -119
Переглянути файл
@@ -197,62 +197,28 @@ fn software_term(lower: &str) -> bool {
.is_some_and(|w| ["s", "x", "z", "ch", "sh"].iter().any(|e| w.ends_with(e)) && plural_of(w))
}
/// A custom dictionary: a word list, or a Hunspell dictionary with its affix rules.
enum CustomDictionary {
Words(HashSet<String>),
Hunspell(Box<spellbook::Dictionary>),
}
impl CustomDictionary {
/// Whether the lowercased `lower` is a word of it, in any case style.
fn contains(&self, lower: &str) -> bool {
match self {
Self::Words(words) => words.contains(lower),
Self::Hunspell(dict) => {
dict.check(lower) || dict.check(&capitalize(lower)) || dict.check(&lower.to_uppercase())
}
}
}
}
/// The `.aff` next to a Hunspell `.dic` (`de_DE.dic` → `de_DE.aff`), if there is one.
fn affix_file(path: &Path) -> Option<PathBuf> {
if !path.extension().is_some_and(|e| e.eq_ignore_ascii_case("dic")) {
return None;
}
["aff", "AFF"].into_iter().map(|ext| path.with_extension(ext)).find(|aff| aff.is_file())
}
/// A custom dictionary file: a Hunspell `.dic` with the `.aff` beside it, with
/// its affix, compounding and case rules; otherwise a plain word list (a `.dic`
/// alone: leading count line and `/FLAGS` ignored). Cached by modification time.
fn dictionary_file(path: &Path) -> Arc<CustomDictionary> {
type Stamp = (Option<SystemTime>, Option<SystemTime>);
type Cache = HashMap<PathBuf, (Stamp, Arc<CustomDictionary>)>;
/// Words of a custom dictionary file: a plain word list or a Hunspell `.dic`
/// (leading count line and `/FLAGS` ignored). Cached by modification time.
fn dictionary_file(path: &Path) -> Arc<HashSet<String>> {
type Cache = HashMap<PathBuf, (Option<SystemTime>, Arc<HashSet<String>>)>;
static CACHE: OnceLock<Mutex<Cache>> = OnceLock::new();
let modified = |p: &Path| std::fs::metadata(p).and_then(|m| m.modified()).ok();
let aff = affix_file(path);
let stamp = (modified(path), aff.as_deref().and_then(modified));
if let Some((at, dict)) = CACHE.get_or_init(Default::default).lock().get(path)
&& *at == stamp
let modified = std::fs::metadata(path).and_then(|m| m.modified()).ok();
let mut cache = CACHE.get_or_init(Default::default).lock();
if let Some((at, words)) = cache.get(path)
&& *at == modified
{
return dict.clone();
return words.clone();
}
let read = |p: &Path| {
std::fs::read_to_string(p).map_err(|e| tracing::debug!("custom dictionary {}: {e}", p.display())).ok()
let words: HashSet<String> = match std::fs::read_to_string(path) {
Ok(text) => parse_word_list(&text),
Err(e) => {
tracing::debug!("custom dictionary {}: {e}", path.display());
HashSet::new()
}
};
let text = read(path).unwrap_or_default();
let hunspell = aff.as_deref().and_then(read).and_then(|aff| {
spellbook::Dictionary::new(&aff, &text)
.map_err(|e| tracing::warn!("Hunspell dictionary {}: {e}", path.display()))
.ok()
});
let dict = Arc::new(match hunspell {
Some(dict) => CustomDictionary::Hunspell(Box::new(dict)),
None => CustomDictionary::Words(parse_word_list(&text)),
});
CACHE.get_or_init(Default::default).lock().insert(path.to_path_buf(), (stamp, dict.clone()));
dict
let words = Arc::new(words);
cache.insert(path.to_path_buf(), (modified, words.clone()));
words
}
/// Lowercased words of a word list / Hunspell `.dic` text.
@@ -272,7 +238,7 @@ pub fn parse_word_list(text: &str) -> HashSet<String> {
#[derive(Default)]
pub struct Speller {
accepted: HashSet<String>,
custom: Vec<Arc<CustomDictionary>>,
custom: Vec<Arc<HashSet<String>>>,
}
impl Speller {
@@ -385,31 +351,16 @@ impl Speller {
&& !near_word(lower, |w| english().check(w))
}
/// Replacements for `word`, best first, in the word's case style: from the
/// English dictionary and the custom Hunspell dictionaries, the closest first.
/// Replacements for `word`, best first, in the word's case style.
pub fn suggest(&self, word: &str, limit: usize) -> Vec<String> {
let hunspell = self.custom.iter().filter_map(|d| match d.as_ref() {
CustomDictionary::Hunspell(dict) => Some(dict.as_ref()),
CustomDictionary::Words(_) => None,
});
let dicts: Vec<&spellbook::Dictionary> = std::iter::once(english()).chain(hunspell).collect();
let mut out = Vec::new();
for dict in &dicts {
let mut found = Vec::new();
dict.suggest(word, &mut found);
if found.is_empty() && word.chars().next().is_some_and(char::is_uppercase) {
dict.suggest(&word.to_lowercase(), &mut found);
found = found.into_iter().map(|s| capitalize(&s)).collect();
}
out.extend(found);
english().suggest(word, &mut out);
if out.is_empty() && word.chars().next().is_some_and(char::is_uppercase) {
english().suggest(&word.to_lowercase(), &mut out);
out = out.into_iter().map(|s| capitalize(&s)).collect();
}
let mut seen = HashSet::new();
out.retain(|s| s != word && seen.insert(s.clone()));
if dicts.len() > 1 {
// Stable: within a distance each dictionary keeps its own order, English first.
let lower = word.to_lowercase();
out.sort_by_key(|s| edit_distance(&lower, &s.to_lowercase()));
}
out.truncate(limit);
out
}
@@ -465,22 +416,6 @@ impl Speller {
}
}
/// Levenshtein distance in characters.
fn edit_distance(a: &str, b: &str) -> usize {
let b: Vec<char> = b.chars().collect();
let mut row: Vec<usize> = (0..=b.len()).collect();
for (i, ca) in a.chars().enumerate() {
let mut diagonal = row[0];
row[0] = i + 1;
for (j, cb) in b.iter().enumerate() {
let next = (row[j + 1] + 1).min(row[j] + 1).min(diagonal + usize::from(ca != *cb));
diagonal = row[j + 1];
row[j + 1] = next;
}
}
row[b.len()]
}
fn capitalize(s: &str) -> String {
let mut chars = s.chars();
chars.next().into_iter().flat_map(char::to_uppercase).chain(chars).collect()
@@ -801,36 +736,6 @@ mod tests {
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn hunspell_custom_dictionaries_use_their_affix_rules() {
let dir = std::env::temp_dir().join(format!("ide-spell-hunspell-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let dic = dir.join("de_TEST.dic");
std::fs::write(&dic, "3\nhaus/NZ\ntür/NZ\nschlüssel/Z\n").unwrap();
std::fs::write(
dir.join("de_TEST.aff"),
"SET UTF-8\nTRY esianrtolcdugmphbyfvkwzäöüß\nCOMPOUNDFLAG Z\nSFX N Y 1\nSFX N 0 en .\n",
)
.unwrap();
let s = Speller::new::<&str>([], std::slice::from_ref(&dic));
// Affix rules, compounds and case styles of the .aff, not just the listed stems.
for word in ["haus", "Haus", "hausen", "türen", "Haustür", "schlüsselhaus"] {
assert!(s.is_correct(word), "{word}");
}
assert!(!s.is_correct("hauz"));
assert!(!s.is_correct("schlüsselen"));
assert!(s.suggest("Hauss", 5).iter().any(|w| w == "Haus"), "{:?}", s.suggest("Hauss", 5));
// English still checks and suggests.
assert!(s.is_correct("message"));
assert!(s.suggest("mesage", 5).iter().any(|w| w == "message"));
// Without its .aff, a .dic is a word list.
std::fs::remove_file(dir.join("de_TEST.aff")).unwrap();
let words = Speller::new::<&str>([], std::slice::from_ref(&dic));
assert!(words.is_correct("haus"));
assert!(!words.is_correct("hausen"));
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn utf16_ranges() {
let s = Speller::default();
+1 -1
Переглянути файл
@@ -112,7 +112,7 @@ The debugger adds attach-only types such as **Remote JVM Debug**, **Go Remote**,
### Common fields
- **Run on**: the local machine, or an SSH host defined in **Settings › Build, Execution, Deployment › Run Targets**. Debugging is not available on run targets. See [SSH](/en/guide/remote/ssh).
- **Working directory**: relative to the project root; empty means the project root. It may use the path macros `$PROJECT_DIR$`, `$ContentRoot$`, `$MODULE_DIR$`, `$MODULE_WORKING_DIR$` and `$USER_HOME$`, expanded when the configuration starts, so a shared configuration works on every machine.
- **Working directory**: relative to the project root; empty means the project root.
- **Environment variables**: `VAR=value` pairs separated by `;`. The list button opens the **Environment Variables** dialog, where **Include system environment variables** can be turned off.
- **Debug adapter**: which debugger **Debug** uses for this configuration (for example `debugpy`, `js-debug`, `codelldb`, `delve`).
+1 -1
Переглянути файл
@@ -23,7 +23,7 @@ Only types you add appear here: choose **Add Service › Run Configuration Type*
- Configuration actions: **Run** (or **Rerun**), **Debug**, **Stop**, **Open in Browser**, **Update Application** (for configurations that support it).
- Context menu: **Show in Run Tool Window**, **Show in Debug Tool Window**, **Edit Configuration…**, **Remove from Services**.
A configuration that ran shows its console in the detail pane; one debugged from here shows the whole debugger there (Threads & Variables, Console, Memory), and a breakpoint keeps the Services tool window in front. Reorder configurations within a group by dragging them or with **Move Up** / **Move Down**; the order is saved per project.
A configuration that ran shows its console in the detail pane. Reorder configurations within a group by dragging them or with **Move Up** / **Move Down**; the order is saved per project.
## Docker
+1 -1
Переглянути файл
@@ -108,7 +108,7 @@ description: "创建、编辑和启动运行配置,从装订区运行代码,
### 通用字段
- **运行于**:本地计算机,或在 **设置 › 构建、执行、部署 › 运行目标** 中添加的 SSH 主机。运行目标上不支持调试。参见 [SSH](/zh/guide/remote/ssh)。
- **工作目录**:相对于项目根目录,留空即项目根目录。可以使用路径宏 `$PROJECT_DIR$`、`$ContentRoot$`、`$MODULE_DIR$`、`$MODULE_WORKING_DIR$` 和 `$USER_HOME$`,在配置启动时展开,因此共享的配置在每台机器上都能用。
- **工作目录**:相对于项目根目录,留空即项目根目录。
- **环境变量**:`VAR=value` 形式,用 `;` 分隔。点旁边的列表按钮打开“环境变量”对话框,可以关闭 **包括系统环境变量**。
- **调试适配器**:按“调试”时这个配置使用哪个调试器(如 `debugpy`、`js-debug`、`codelldb`、`delve`)。
+1 -1
Переглянути файл
@@ -23,7 +23,7 @@ description: "在服务工具窗口中管理运行配置、Docker 容器、镜
- 配置操作:**运行**(或 **重新运行**)、**调试**、**停止**、**在浏览器中打开**、**更新应用**(仅支持的配置)。
- 右键菜单:**在运行工具窗口中显示**、**在调试工具窗口中显示**、**编辑配置…**、**从服务中移除**。
运行过的配置会在详情区显示其控制台;从这里调试的配置在详情区显示完整的调试器(线程和变量、控制台、内存),命中断点时停留在服务工具窗口。在同一分组内可以拖动或用 **上移** / **下移** 调整顺序,顺序按项目保存。
运行过的配置会在详情区显示其控制台。在同一分组内可以拖动或用 **上移** / **下移** 调整顺序,顺序按项目保存。
## Docker
-85
Переглянути файл
@@ -1,85 +0,0 @@
import type { AgentEntry, AgentTask } from "../src/bindings";
import { expect, test } from "./fixtures";
const first: AgentTask = {
id: "context-first",
title: "First conversation",
provider: "codex",
status: "ready",
isolation: "local",
model: null,
cwd: "/dev/acme-api",
branch: null,
base: null,
baseCommit: null,
error: null,
createdMs: 0,
updatedMs: 0,
config: [],
commands: [],
usage: null,
queue: [],
};
const second: AgentTask = { ...first, id: "context-second", title: "Second conversation" };
for (const active of ["conversation", "file"] as const) {
test(`an agent context menu keeps the current ${active} open`, async ({ workbench: page }) => {
await page.getByRole("treeitem", { name: "README.md", exact: true }).dblclick();
await expect(page.getByRole("tab", { name: "README.md", exact: true })).toBeVisible();
await page.evaluate(
async ({ first, second }) => {
const storePath = "/src/features/agents/store.ts";
const ipcPath = "/src/platform/ipc.ts";
const contributionsPath = "/src/workbench/contributions.ts";
const store = await import(storePath);
const { commands } = await import(ipcPath);
const { toolWindowService } = await import(contributionsPath);
commands.agentChanges = async () => ({ status: "ok", data: [] });
const entries: AgentEntry[] = [{ type: "agent", text: "The active conversation stays here." }];
store.useAgents.setState({
loaded: true,
error: null,
providers: [],
tasks: new Map([
[first.id, first],
[second.id, second],
]),
entries: new Map([
[first.id, entries],
[second.id, []],
]),
composers: new Map([[first.id, { text: "Keep this unsent draft", files: [], images: [] }]]),
unread: new Set(),
docked: null,
homeOpen: false,
sessionLocation: "editor",
});
toolWindowService().show("agents", true);
store.openTask(first.id);
},
{ first, second },
);
const firstTab = page.getByRole("tab", { name: first.title, exact: true });
const fileTab = page.getByRole("tab", { name: "README.md", exact: true });
await expect(firstTab).toHaveAttribute("aria-selected", "true");
if (active === "file") await fileTab.click();
const current = active === "file" ? fileTab : firstTab;
const target = page.getByRole("tree", { name: "Agent tasks" }).getByText(second.title, { exact: true });
await target.click({ button: "right" });
await expect(page.getByRole("menuitem", { name: "Rename…", exact: true })).toBeVisible();
await expect(current).toHaveAttribute("aria-selected", "true");
await expect(page.getByRole("tab", { name: second.title, exact: true })).toHaveCount(0);
await page.keyboard.press("Escape");
await expect(current).toHaveAttribute("aria-selected", "true");
await expect
.poll(() =>
page.evaluate(async (id) => {
const storePath = "/src/features/agents/store.ts";
return (await import(storePath)).composerDraft(id).text;
}, first.id),
)
.toBe("Keep this unsent draft");
await target.click();
await expect(page.getByRole("tab", { name: second.title, exact: true })).toHaveAttribute("aria-selected", "true");
});
}
+1 -1
Переглянути файл
@@ -17,7 +17,7 @@ func main() {
[[language-servers]]
name = "gopls"
command = "gopls"
initialization-options = { semanticTokens = true, vulncheck = "Imports", hints = { constantValues = true } }
initialization-options = { semanticTokens = true, vulncheck = "Imports" }
root-markers = ["go.work", "go.mod"]
install-hint = "go install golang.org/x/tools/gopls@latest"
+8 -55
Переглянути файл
@@ -9,7 +9,6 @@ import { promptInput } from "@/workbench/inputDialogs";
import { ContextMenuHost, dragSession, hideContextMenu } from "@/ui";
import { AgentsHeaderActions, AgentsView } from "./AgentsView";
import { SESSION_KIND, TASK_DRAG } from "./model";
import { usePlatform } from "@/platform/platformInfo";
import { archiveTask, unarchiveTask, deleteTask, dockTask, openTask, useAgents } from "./store";
import { taskActions, taskMenu, useAgentsHeaderMenu } from "./taskActions";
import styles from "./Agents.module.css";
@@ -141,42 +140,6 @@ function setup() {
}
describe("Agents selection", () => {
it.each([SESSION_KIND, "file"])("right-clicking a task keeps the current %s view open", (kind) => {
editor.active = { kind, key: "current", data: { task: "one" } };
setup();
context("two");
expect(screen.getByRole("menuitem", { name: "Rename…" })).toBeTruthy();
expect(selectedTasks()).toEqual(["two"]);
expect(openTask).not.toHaveBeenCalled();
fireEvent.keyDown(document, { key: "Escape" });
expect(openTask).not.toHaveBeenCalled();
});
it("preserves a multi-selection when opening its context menu without activating a task", () => {
setup();
select("one");
select("three", { shiftKey: true });
vi.mocked(openTask).mockClear();
context("two");
expect(selectedTasks()).toEqual(["one", "two", "three"]);
expect(screen.getByRole("menuitem", { name: "Delete (3)…" })).toBeTruthy();
expect(openTask).not.toHaveBeenCalled();
});
it("treats macOS Control-click as a context menu without opening the task", () => {
const os = usePlatform.getState().os;
usePlatform.setState({ os: "macos" });
try {
setup();
fireEvent.mouseDown(row("two"), { button: 0, ctrlKey: true });
fireEvent.contextMenu(row("two"), { button: 0, ctrlKey: true });
expect(screen.getByRole("menuitem", { name: "Rename…" })).toBeTruthy();
expect(openTask).not.toHaveBeenCalled();
} finally {
usePlatform.setState({ os });
}
});
it("extends and shrinks a range without opening its lead or losing selection to an editor echo", () => {
setup();
select("one");
@@ -201,24 +164,14 @@ describe("Agents selection", () => {
expect(openTask).not.toHaveBeenCalled();
});
it.each([
{ os: "macos", modifier: "metaKey" },
{ os: "windows", modifier: "ctrlKey" },
{ os: "linux", modifier: "ctrlKey" },
])("toggles individual tasks with $modifier on $os", ({ os, modifier }) => {
const previousOs = usePlatform.getState().os;
usePlatform.setState({ os });
try {
setup();
select("one");
select("three", { [modifier]: true });
expect(selectedTasks()).toEqual(["one", "three"]);
select("three", { [modifier]: true });
expect(selectedTasks()).toEqual(["one"]);
expect(openTask).toHaveBeenCalledTimes(1);
} finally {
usePlatform.setState({ os: previousOs });
}
it.each(["metaKey", "ctrlKey"])("toggles individual tasks with %s", (modifier) => {
setup();
select("one");
select("three", { [modifier]: true });
expect(selectedTasks()).toEqual(["one", "three"]);
select("three", { [modifier]: true });
expect(selectedTasks()).toEqual(["one"]);
expect(openTask).toHaveBeenCalledTimes(1);
});
});
+2 -3
Переглянути файл
@@ -322,10 +322,9 @@ export function AgentsView() {
})
}
selected={selected}
onSelectionChange={(sel, lead, reason) => {
onSelectionChange={(sel, lead) => {
setSelected(sel);
if (reason !== "contextMenu" && !inline && sel.size === 1 && lead?.kind === "task" && sel.has(lead.task.id))
showTask(lead.task.id);
if (!inline && sel.size === 1 && lead?.kind === "task" && sel.has(lead.task.id)) showTask(lead.task.id);
}}
onActivate={(n) => n.kind === "task" && showTask(n.task.id)}
onContextMenu={(n, sel, e) => {
+2 -18
Переглянути файл
@@ -70,35 +70,19 @@ it.each([undefined, true, false])(
);
it.each(["breakpoint", "function breakpoint", "exception", "pause"])(
"reveals an in-place session in Services on suspend (%s)",
"reveals an in-place session on suspend (%s)",
async (reason) => {
const show = vi.fn();
provideToolWindowService({ show } as unknown as ToolWindowService);
await startSession(config("launch"), { show: false });
expect(show).not.toHaveBeenCalled();
handleDebugEvent(42, { kind: "stopped", threadId: 1, reason, description: null, allThreadsStopped: true });
// Services shows the session's debugger in place (#4773).
expect(show).toHaveBeenCalledExactlyOnceWith("services");
expect(show).toHaveBeenCalledWith("debug");
expect(useDebug.getState().active).toBe(42);
expect(useDebug.getState().sessions[42]).toMatchObject({ status: "paused", selectedThread: 1 });
},
);
it("reveals a session started elsewhere in the Debug tool window on suspend", async () => {
const show = vi.fn();
provideToolWindowService({ show } as unknown as ToolWindowService);
await startSession(config("launch"));
show.mockClear();
handleDebugEvent(42, {
kind: "stopped",
threadId: 1,
reason: "breakpoint",
description: null,
allThreadsStopped: true,
});
expect(show).toHaveBeenCalledExactlyOnceWith("debug");
});
it.each(["launch", "attach"])("awaits every file before %s can send configurationDone", async (request) => {
const completed: string[] = [];
const release: Array<() => void> = [];
+1 -2
Переглянути файл
@@ -79,7 +79,6 @@ function useLiveSessionCount(): number | null {
export function activate(): () => void {
useDebugRunSessions.setState({
Console: lazyComponent(() => import("./ui/DebugConsole").then((m) => m.DebugServiceConsole)),
View: lazyComponent(() => import("./ui/DebugToolWindow").then((m) => m.DebugServiceView)),
});
loadWatches(useProject.getState().project?.root ?? null);
publishContext();
@@ -89,7 +88,7 @@ export function activate(): () => void {
loadJsBreakpoints(useProject.getState().project?.root ?? null);
loadResponseOverrides(useProject.getState().project?.root ?? null);
const disposers = [
() => useDebugRunSessions.setState({ sessions: [], serviceSessions: [], Console: null, View: null }),
() => useDebugRunSessions.setState({ sessions: [], serviceSessions: [], Console: null }),
registerDebugActions(),
registerDebugTabActions(),
registerDevToolsWindows(),
+6 -11
Переглянути файл
@@ -29,7 +29,6 @@ import {
maybeEditorService,
notifications,
runOutput,
SERVICES_WINDOW,
toolWindowService,
useDebugRunSessions,
} from "@/workbench/contributions";
@@ -78,8 +77,6 @@ export interface DebugSession {
process: RunId | null;
/** Pinned tab (root sessions): once finished, a later session opens a new tab instead of taking its place. */
pinned?: boolean;
/** Started in place from the Services tool window (root sessions): its stops show it there, not in the Debug window. */
inPlace?: boolean;
status: SessionStatus;
stoppedThread: number | null;
stopReason: string | null;
@@ -723,7 +720,6 @@ export async function startPreparedSession(
adapter: config.debugAdapter ?? "",
runConfig: config,
pinned,
inPlace: options.show === false,
}),
},
console: { ...s.console, [id]: [] },
@@ -825,7 +821,6 @@ export async function startSession(
launch: options.rerunnable === false ? null : launch,
process: options.process ?? null,
pinned: preparation ? preparation.pinned : pinned,
inPlace: options.show === false,
status: cur.status === "starting" ? "running" : cur.status,
},
},
@@ -989,12 +984,13 @@ export async function rerunSession(id: DebugSessionId, options: { show?: boolean
if (!root.runConfig && !launch) return;
if (isLive(root)) await stopSession(root.id);
rerunOf = root.id;
// A session debugged in place from Services reruns there too.
const show = options.show ?? (root.inPlace ? false : undefined);
try {
if (root.runConfig)
await executeAction("run.debugConfig", show === false ? { config: root.runConfig, show: false } : root.runConfig);
else await startSession(launch!, { show });
await executeAction(
"run.debugConfig",
options.show === false ? { config: root.runConfig, show: false } : root.runConfig,
);
else await startSession(launch!, { show: options.show });
} finally {
rerunOf = null;
}
@@ -1368,8 +1364,7 @@ export function handleDebugEvent(id: DebugSessionId, event: DebugEvent) {
void loadFrames(id, event.threadId, !markTraceStop(id, event.threadId, s.stops + 1));
const dbg = workflowSettings().debugger;
try {
// A session debugged in place from Services shows its debugger there (#4773).
if (dbg.showOnBreakpoint) toolWindowService().show(rootOf(s).inPlace ? SERVICES_WINDOW : "debug");
if (dbg.showOnBreakpoint) toolWindowService().show("debug");
} catch {
// ignore
}
-12
Переглянути файл
@@ -353,15 +353,3 @@
border-bottom: 0;
border-top: 1px solid var(--border);
}
.serviceView {
display: flex;
flex-direction: column;
height: 100%;
min-height: 0;
}
.serviceView > * {
flex: 1;
min-height: 0;
}
+2 -30
Переглянути файл
@@ -1,6 +1,6 @@
/** Debug tool window: toolbar, Threads & Variables (frames + variables), Console. */
import { writeClipboardText } from "@/platform/clipboard";
import { useEffect, useLayoutEffect, useMemo, useRef, useState, type KeyboardEvent, type ReactNode } from "react";
import { useEffect, useLayoutEffect, useMemo, useRef, useState, type KeyboardEvent } from "react";
import clsx from "clsx";
import { executeAction } from "@/platform/actions";
import { basename, useProject } from "@/platform/project";
@@ -173,35 +173,7 @@ export function DebugTabs() {
);
}
/**
* Services › a configuration being debugged: the same debugger as the Debug tool window, for
* that session (#4773). `console` replaces the Console tab, e.g. with the console of the run the
* debugger is attached to.
*/
export function DebugServiceView({ sessionId, console: consolePane }: { sessionId: number; console?: ReactNode }) {
const shown = useDebug((s) => {
const active = s.active != null ? s.sessions[s.active] : undefined;
return !!active && rootOf(active).id === sessionId;
});
useEffect(() => {
if (useDebug.getState().sessions[sessionId]) selectSession(sessionId);
}, [sessionId]);
// The toolbar acts on the active session: using this view makes its session the active one again.
const reselect = () => {
if (!shown && useDebug.getState().sessions[sessionId]) selectSession(sessionId);
};
return (
<div className={styles.serviceView} onPointerDownCapture={reselect} onFocusCapture={reselect}>
{shown && <DebugView consolePane={consolePane} />}
</div>
);
}
export function DebugToolWindow() {
return <DebugView />;
}
function DebugView({ consolePane }: { consolePane?: ReactNode }) {
const tx = useTx();
const active = useDebug((s) => (s.active != null ? s.sessions[s.active] : undefined));
const muted = useBreakpoints((s) => s.muted);
@@ -342,7 +314,7 @@ function DebugView({ consolePane }: { consolePane?: ReactNode }) {
) : tab === "network" ? (
<NetworkView key={active.id} session={active.id} />
) : (
(consolePane ?? <DebugConsole key={active.id} session={active} />)
<DebugConsole key={active.id} session={active} />
)}
</div>
</div>
-32
Переглянути файл
@@ -1,32 +0,0 @@
import { describe, expect, it } from "vitest";
import { expandCwd } from "./cwdMacros";
const ctx = { root: "/work/app/", module: "services/api", home: "/Users/me" };
describe("working directory macros (#4755)", () => {
it("expands the project, module and home folders", () => {
expect(expandCwd("$PROJECT_DIR$/web", ctx)).toEqual({ cwd: "/work/app/web" });
expect(expandCwd("$ContentRoot$", ctx)).toEqual({ cwd: "/work/app" });
expect(expandCwd("$MODULE_DIR$/bin", ctx)).toEqual({ cwd: "/work/app/services/api/bin" });
expect(expandCwd("$MODULE_WORKING_DIR$", ctx)).toEqual({ cwd: "/work/app/services/api" });
expect(expandCwd("$USER_HOME$/scratch", ctx)).toEqual({ cwd: "/Users/me/scratch" });
});
it("uses the project folder as the module folder when there is no module", () => {
expect(expandCwd("$MODULE_DIR$", { ...ctx, module: null })).toEqual({ cwd: "/work/app" });
expect(expandCwd("$MODULE_DIR$", { ...ctx, module: "/elsewhere/mod" })).toEqual({ cwd: "/elsewhere/mod" });
});
it("leaves a path without macros as it is", () => {
expect(expandCwd("server", ctx)).toEqual({ cwd: "server" });
expect(expandCwd("/abs/$dollar", ctx)).toEqual({ cwd: "/abs/$dollar" });
});
it("names an unknown macro and one without a value", () => {
const unknown = expandCwd("$PROJECT_ROOT$/web", ctx);
expect("error" in unknown && unknown.error).toContain("$PROJECT_ROOT$");
expect("error" in unknown && unknown.error).toContain("$PROJECT_DIR$");
const remote = expandCwd("$USER_HOME$", { ...ctx, home: null });
expect(remote).toEqual({ error: "$USER_HOME$ is not available in a remote project." });
});
});
-80
Переглянути файл
@@ -1,80 +0,0 @@
/**
* Path macros in a run configuration's working directory (`$PROJECT_DIR$/web`), expanded when
* it runs or is debugged; the stored value keeps them, so the configuration moves with the project.
*/
import { tx } from "@/platform/i18n";
import { isTauri, type RunConfig } from "@/platform/ipc";
import { isRemoteWindow } from "@/platform/remote";
import { useProject } from "@/platform/project";
import { notifications } from "@/workbench/contributions";
const MACRO = /\$([A-Za-z_][A-Za-z0-9_]*)\$/g;
/** The macros a working directory may use. */
export const CWD_MACROS = ["PROJECT_DIR", "ContentRoot", "MODULE_DIR", "MODULE_WORKING_DIR", "USER_HOME"] as const;
export interface CwdContext {
root: string;
/** The configuration's module directory, absolute or relative to `root`. */
module?: string | null;
/** The user's home folder; null where it isn't known (a remote project). */
home: string | null;
}
const absolute = (p: string) => p.startsWith("/") || /^[A-Za-z]:[\\/]/.test(p) || p.startsWith("\\\\");
const trimEnd = (p: string) => p.replace(/[\\/]+$/, "");
const join = (root: string, p: string) => (absolute(p) ? p : `${trimEnd(root)}/${p.replace(/^\.[\\/]/, "")}`);
/** `cwd` with its macros replaced; an error names a macro that is unknown or has no value here. */
export function expandCwd(cwd: string, ctx: CwdContext): { cwd: string } | { error: string } {
let error: string | null = null;
const module = ctx.module ? join(ctx.root, ctx.module) : ctx.root;
const values: Record<string, string | null> = {
PROJECT_DIR: ctx.root,
ContentRoot: ctx.root,
MODULE_DIR: module,
MODULE_WORKING_DIR: module,
USER_HOME: ctx.home,
};
const out = cwd.replace(MACRO, (all, name: string) => {
const value = Object.hasOwn(values, name) ? values[name] : undefined;
if (value) return trimEnd(value);
const supported = CWD_MACROS.map((m) => `$${m}$`).join(", ");
error ??=
value === undefined
? tx`Unknown macro ${all} in the working directory. Supported: ${supported}.`
: tx`${all} is not available in a remote project.`;
return all;
});
return error ? { error } : { cwd: out };
}
let home: Promise<string | null> | null = null;
const homeDir = () =>
(home ??= isTauri()
? import("@tauri-apps/api/path").then((m) => m.homeDir()).catch(() => null)
: Promise.resolve(null));
/** `config` with the macros of its working directory expanded; throws when one can't be. */
export async function withExpandedCwd(config: RunConfig): Promise<RunConfig> {
const cwd = config.cwd;
if (!cwd?.includes("$")) return config;
const root = useProject.getState().project?.root;
if (!root) return config;
const result = expandCwd(cwd, {
root,
module: config.module,
home: isRemoteWindow() ? null : await homeDir(),
});
if ("error" in result) throw new Error(result.error);
return { ...config, cwd: result.cwd };
}
export function notifyCwdError(config: RunConfig, error: unknown) {
notifications().notify({
group: "run",
level: "error",
title: tx`Cannot start '${config.name}'`,
body: error instanceof Error ? error.message : String(error),
});
}
-6
Переглянути файл
@@ -37,7 +37,6 @@ import {
runContextAction,
} from "./contextRun";
import { runWithExecutor } from "./executors";
import { notifyCwdError, withExpandedCwd } from "./cwdMacros";
import { debugWithAgent, jdwpLaunch } from "./javaDebug";
import { attachesToChild, debugAttachingToChild } from "./pluginAttach";
import { RunDialogsOverlay } from "./dialogs";
@@ -185,11 +184,6 @@ async function debugConfig(config: RunConfig, chain: readonly string[] = [], sho
}
async function debugLaunch(config: RunConfig, chain: readonly string[], show?: boolean): Promise<void> {
try {
config = await withExpandedCwd(config);
} catch (e) {
return notifyCwdError(config, e);
}
if (!(await prepareLaunch(config, chain, show))) return;
if (config.kind === UNITY_CONFIG_KIND) return showUnityAttach(config);
// Python on a Docker / Compose target: debugpy in the container, the debugger attaches.
+5 -8
Переглянути файл
@@ -757,7 +757,7 @@ function RunDetail({ item }: { item: ServiceTreeItem }) {
// Re-render on session changes.
useRun((s) => s.sessions);
const debugViews = useDebugRunSessions();
const { Console, View } = debugViews;
const Console = debugViews.Console;
const t = useT();
const txTemplate = useTxTemplate();
const r = resolve(item);
@@ -773,14 +773,11 @@ function RunDetail({ item }: { item: ServiceTreeItem }) {
);
// The configuration ran: its console, as in the Run tool window. Run / Debug / Stop
// come from this window's toolbar (the selection), so the console strip leaves them out.
const execution = r.session?.run;
const runConsole = execution && <SessionPanel key={execution.id} session={execution} showLifecycle={false} />;
if (r.session?.run) {
const execution = r.session;
return <SessionPanel key={execution.run!.id} session={execution.run!} showLifecycle={false} />;
}
const d = r.session?.debug[0];
// Being debugged: the whole debugger in place, as in IDEA's Services (#4773); the console of a
// run the debugger is attached to stays its Console tab.
if (d && View && (d.status !== "terminated" || !execution))
return <View key={d.id} sessionId={d.id} console={runConsole} />;
if (runConsole) return runConsole;
if (d && Console)
return (
<div className={styles.debugConsole}>
-7
Переглянути файл
@@ -4,7 +4,6 @@
* per-session `ConsoleModel`, batched per animation frame.
*/
import { withRunTarget } from "@/platform/runTargetSelection";
import { notifyCwdError, withExpandedCwd } from "./cwdMacros";
import { create } from "zustand";
import { Channel } from "@tauri-apps/api/core";
import {
@@ -848,12 +847,6 @@ async function startRunIn(
options: StartRunOptions,
): Promise<RunSession | null> {
config = withRunTarget(config);
try {
config = await withExpandedCwd(config);
} catch (e) {
notifyCwdError(config, e);
return null;
}
if (!options.launch && isCMakeBuild(config)) {
await buildCMake(config.id, options.show !== false);
return null;
+13 -24
Переглянути файл
@@ -1,6 +1,5 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { fireEvent, render, screen, within } from "@testing-library/react";
import { usePlatform } from "@/platform/platformInfo";
import { ToolWindowShownProvider, useServiceProviders, type ServiceTreeItem } from "@/workbench/contributions";
import { ServicesTreeView } from "./ServicesTree";
import { useServicesTree } from "./tree";
@@ -55,29 +54,19 @@ function setup() {
}
describe("Services selection → actions", () => {
it.each([
{ os: "macos", modifier: "metaKey" },
{ os: "windows", modifier: "ctrlKey" },
{ os: "linux", modifier: "ctrlKey" },
])("$modifier on $os toggles rows and Run applies to the selection", ({ os, modifier }) => {
const previousOs = usePlatform.getState().os;
usePlatform.setState({ os });
try {
const { row, selected, toolbar } = setup();
fireEvent.mouseDown(row("one"));
fireEvent.mouseDown(row("two"), { [modifier]: true });
expect(selected()).toEqual(["one", "two"]);
expect(screen.getByTestId("detail")).toHaveTextContent("two");
fireEvent.click(within(toolbar).getByRole("button", { name: "Run" }));
expect(run.mock.calls).toEqual([["one"], ["two"]]);
fireEvent.mouseDown(row("one"), { [modifier]: true });
expect(selected()).toEqual(["two"]);
fireEvent.mouseDown(row("two"), { [modifier]: true });
expect(selected()).toEqual([]);
expect(screen.queryByTestId("detail")).not.toBeInTheDocument();
} finally {
usePlatform.setState({ os: previousOs });
}
it.each(["ctrlKey", "metaKey"])("%s toggles rows and Run applies to the selection", (modifier) => {
const { row, selected, toolbar } = setup();
fireEvent.mouseDown(row("one"));
fireEvent.mouseDown(row("two"), { [modifier]: true });
expect(selected()).toEqual(["one", "two"]);
expect(screen.getByTestId("detail")).toHaveTextContent("two");
fireEvent.click(within(toolbar).getByRole("button", { name: "Run" }));
expect(run.mock.calls).toEqual([["one"], ["two"]]);
fireEvent.mouseDown(row("one"), { [modifier]: true });
expect(selected()).toEqual(["two"]);
fireEvent.mouseDown(row("two"), { [modifier]: true });
expect(selected()).toEqual([]);
expect(screen.queryByTestId("detail")).not.toBeInTheDocument();
});
it("tells the provider which node became the lead selection", () => {
+1 -1
Переглянути файл
@@ -65,7 +65,7 @@ function SpellingPage() {
<Row
label="Dictionary files"
stacked
hint="Plain-text word lists (one word per line) or Hunspell .dic files; a .dic with its .aff beside it also accepts the inflected forms and compounds its rules allow. Relative paths resolve against the project root, ~/ against the home folder."
hint="Plain-text word lists (one word per line) or Hunspell .dic files. Relative paths resolve against the project root, ~/ against the home folder."
>
<GlobListEditor
aria-label="Custom dictionaries"
-4
Переглянути файл
@@ -93,10 +93,6 @@
text-overflow: ellipsis;
color: var(--fg-subtle);
}
.nodeCount {
flex: none;
color: var(--fg-subtle);
}
.detailIcon {
flex: none;
--icon-color: var(--fg-subtle);
+1 -1
Переглянути файл
@@ -1002,7 +1002,7 @@ export function ChangesTree({ mode }: { mode: "commit" | "local" | "dialog" }) {
/>
)}
{label}
{n.type !== "file" && <span className={styles.nodeCount}>{fileCount(n.files.length)}</span>}
{n.type === "group" && <span className={styles.detail}>{fileCount(n.files.length)}</span>}
{!staging && n.type === "file" && n.files[0] && isPartiallyStaged(n.files[0]) && (
<span className={styles.partial} title={tx("Partially staged: only staged hunks are committed")}>
<T>partial</T>
+4 -27
Переглянути файл
@@ -10,7 +10,6 @@ vi.mock("../DiffEditor", () => ({ DiffEditor: () => <div /> }));
import { ChangesTree } from "../CommitView";
import { useVcs } from "../store";
import { useCommit } from "../commitStore";
import { useProject } from "@/platform/project";
const change = (path: string) => ({
@@ -27,7 +26,6 @@ const row = (name: string) => screen.getByText(name).closest('[role="treeitem"]'
describe("repository nodes in the changes tree", () => {
beforeEach(() => {
localStorage.clear();
useCommit.setState({ groupByDir: false, groupByRepo: true });
useProject.setState({
project: { name: "p", root: "/p", trusted: true, isGit: true, settings: {} } as never,
settings: {} as never,
@@ -43,7 +41,7 @@ describe("repository nodes in the changes tree", () => {
it("shows the branch each repository is on and follows branch switches", () => {
render(<ChangesTree mode="commit" />);
expect(row("orders").textContent).toBe("orders1 file");
expect(row("orders").textContent).toBe("orders");
act(() =>
useVcs.setState({
heads: {
@@ -52,35 +50,14 @@ describe("repository nodes in the changes tree", () => {
},
}),
);
expect(row("orders").textContent).toBe("orders1 filefeature/ABC-123");
expect(row("p").textContent).toBe("p1 filemain");
expect(row("orders").textContent).toBe("ordersfeature/ABC-123");
expect(row("p").textContent).toBe("pmain");
act(() =>
useVcs.setState({
heads: { ...useVcs.getState().heads, "/p/orders": { head: null, headCommit: "abcdef0123456789" } },
}),
);
expect(row("orders").textContent).toBe("orders1 fileabcdef01");
});
it("counts the files under each repository and each nested folder", () => {
useCommit.setState({ groupByDir: true });
const app = change("/p/App.kt");
const order = change("/p/orders/src/Order.kt");
const test = change("/p/orders/src/tests/OrderTest.kt");
const data = change("/p/orders/src/tests/orders.json");
useVcs.setState({ status: [app, order, test, data] });
render(<ChangesTree mode="commit" />);
expect(row("p").textContent).toBe("p1 file");
expect(row("orders").textContent).toBe("orders3 files");
expect(row("src").textContent).toBe("src3 files");
expect(row("tests").textContent).toBe("tests2 files");
expect(row("Order.kt").textContent).toBe("Order.kt");
act(() => useVcs.setState({ status: [app, order, test] }));
expect(row("orders").textContent).toBe("orders2 files");
expect(row("src").textContent).toBe("src2 files");
expect(row("tests").textContent).toBe("tests1 file");
expect(row("orders").textContent).toBe("ordersabcdef01");
});
it("puts a decorative icon before the branch, on repository rows only", () => {
+2 -5
Переглянути файл
@@ -1,5 +1,4 @@
{
"Plain-text word lists (one word per line) or Hunspell .dic files; a .dic with its .aff beside it also accepts the inflected forms and compounds its rules allow. Relative paths resolve against the project root, ~/ against the home folder.": "Plain-text word lists (one word per line) or Hunspell .dic files; a .dic with its .aff beside it also accepts the inflected forms and compounds its rules allow. Relative paths resolve against the project root, ~/ against the home folder.",
"Trust Folder": "Trust Folder",
"No files selected": "No files selected",
"{added} added": "{added} added",
@@ -910,6 +909,7 @@
"devcontainer up exited with {status}": "devcontainer up exited with {status}",
"Select an item to view details": "Select an item to view details",
"Select files in the Project view, Commit tool window, or open a file in the editor": "Select files in the Project view, Commit tool window, or open a file in the editor",
"Nothing to show": "Nothing to show",
"IDE-managed Tomcat runtime directory must not overlap Tomcat home or base directory": "IDE-managed Tomcat runtime directory must not overlap Tomcat home or base directory",
"Invalid log stream configuration": "Invalid log stream configuration",
@@ -2800,8 +2800,5 @@
"Cannot download to {folder}": "Cannot download to {folder}",
"Copy the selected files and folders of a remote project to a folder on this computer": "Copy the selected files and folders of a remote project to a folder on this computer",
"{modifier}+Click to only see \"{name}\"": "{modifier}+Click to only see \"{name}\"",
"Not a thread count Maven accepts, so builds run serially. Use a number (4) or a core multiplier (2C, 2.5C).": "Not a thread count Maven accepts, so builds run serially. Use a number (4) or a core multiplier (2C, 2.5C).",
"Unknown macro {all} in the working directory. Supported: {supported}.": "Unknown macro {all} in the working directory. Supported: {supported}.",
"{all} is not available in a remote project.": "{all} is not available in a remote project.",
"Cannot start '{name}'": "Cannot start '{name}'"
"Not a thread count Maven accepts, so builds run serially. Use a number (4) or a core multiplier (2C, 2.5C).": "Not a thread count Maven accepts, so builds run serially. Use a number (4) or a core multiplier (2C, 2.5C)."
}
+1
Переглянути файл
@@ -3244,6 +3244,7 @@
"Accepted in every project.": "Aceptadas en todos los proyectos.",
"Custom dictionaries": "Diccionarios personalizados",
"Dictionary files": "Archivos de diccionario",
"Plain-text word lists (one word per line) or Hunspell .dic files. Relative paths resolve against the project root, ~/ against the home folder.": "Listas de palabras en texto plano (una palabra por línea) o archivos .dic de Hunspell. Las rutas relativas se resuelven respecto a la raíz del proyecto y ~/ respecto a la carpeta personal.",
"No custom dictionaries": "No hay diccionarios personalizados",
"Dictionary path": "Ruta del diccionario",
"Natural Languages": "Idiomas naturales",
+1
Переглянути файл
@@ -3117,6 +3117,7 @@
"Accepted in every project.": "Acceptés dans tous les projets.",
"Custom dictionaries": "Dictionnaires personnalisés",
"Dictionary files": "Fichiers de dictionnaire",
"Plain-text word lists (one word per line) or Hunspell .dic files. Relative paths resolve against the project root, ~/ against the home folder.": "Listes de mots en texte brut (un mot par ligne) ou fichiers Hunspell .dic. Les chemins relatifs sont résolus depuis la racine du projet, ~/ depuis le dossier personnel.",
"No custom dictionaries": "Aucun dictionnaire personnalisé",
"Dictionary path": "Chemin du dictionnaire",
"Natural Languages": "Langues naturelles",
+1
Переглянути файл
@@ -3293,6 +3293,7 @@
"Accepted in every project.": "모든 프로젝트에서 허용됩니다.",
"Custom dictionaries": "사용자 지정 사전",
"Dictionary files": "사전 파일",
"Plain-text word lists (one word per line) or Hunspell .dic files. Relative paths resolve against the project root, ~/ against the home folder.": "일반 텍스트 단어 목록(한 줄에 한 단어) 또는 Hunspell .dic 파일. 상대 경로는 프로젝트 루트를, ~/는 홈 폴더를 기준으로 해결됩니다.",
"No custom dictionaries": "사용자 지정 사전 없음",
"Dictionary path": "사전 경로",
"Natural Languages": "자연어",
+1
Переглянути файл
@@ -3216,6 +3216,7 @@
"Accepted in every project.": "Akceptowane we wszystkich projektach.",
"Custom dictionaries": "Własne słowniki",
"Dictionary files": "Pliki słowników",
"Plain-text word lists (one word per line) or Hunspell .dic files. Relative paths resolve against the project root, ~/ against the home folder.": "Listy słów w zwykłym tekście (jednosłowne w wierszu) lub pliki .dic Hunspell. Ścieżki względne są rozwiązywane względem katalogu głównego projektu, a ~/ względem folderu domowego.",
"No custom dictionaries": "Brak własnych słowników",
"Dictionary path": "Ścieżka słownika",
"Natural Languages": "Języki naturalne",
+1
Переглянути файл
@@ -3217,6 +3217,7 @@
"Accepted in every project.": "Aceitas em todos os projetos.",
"Custom dictionaries": "Dicionários personalizados",
"Dictionary files": "Arquivos de dicionário",
"Plain-text word lists (one word per line) or Hunspell .dic files. Relative paths resolve against the project root, ~/ against the home folder.": "Listas de palavras em texto simples (uma palavra por linha) ou arquivos .dic do Hunspell. Caminhos relativos são resolvidos em relação à raiz do projeto, ~/ em relação à pasta pessoal.",
"No custom dictionaries": "Nenhum dicionário personalizado",
"Dictionary path": "Caminho do dicionário",
"Natural Languages": "Idiomas naturais",
+3 -5
Переглянути файл
@@ -1,5 +1,4 @@
{
"Plain-text word lists (one word per line) or Hunspell .dic files; a .dic with its .aff beside it also accepts the inflected forms and compounds its rules allow. Relative paths resolve against the project root, ~/ against the home folder.": "纯文本单词列表(每行一个词)或 Hunspell .dic 文件;旁边有同名 .aff 的 .dic 还会接受其规则允许的变形和复合词。相对路径基于项目根目录解析,~/ 表示主目录。",
"MCP server instructions": "MCP 服务器说明",
"MCP tools (deferred)": "MCP 工具(延迟加载)",
"System tools (deferred)": "系统工具(延迟加载)",
@@ -4105,6 +4104,7 @@
"Accepted in every project.": "在所有项目中接受。",
"Custom dictionaries": "自定义词典",
"Dictionary files": "词典文件",
"Plain-text word lists (one word per line) or Hunspell .dic files. Relative paths resolve against the project root, ~/ against the home folder.": "纯文本单词列表(每行一个单词)或 Hunspell .dic 文件。相对路径相对于项目根目录解析,~/ 相对于主文件夹解析。",
"No custom dictionaries": "没有自定义词典",
"Dictionary path": "词典路径",
"Natural Languages": "自然语言",
@@ -5285,6 +5285,7 @@
"Configuration…": "配置…",
"No deployment server configured": "未配置部署服务器",
"Select files in the Project view, Commit tool window, or open a file in the editor": "请在项目视图或提交工具窗口中选择文件,或在编辑器中打开文件",
"Upload to": "上传到",
"Download from": "下载自",
"Sync with Deployed to": "与已部署的同步",
@@ -9159,8 +9160,5 @@
"Cannot download to {folder}": "无法下载到 {folder}",
"Copy the selected files and folders of a remote project to a folder on this computer": "把远程项目中选中的文件和文件夹复制到本机的文件夹",
"{modifier}+Click to only see \"{name}\"": "{modifier}+点击仅显示“{name}”",
"Not a thread count Maven accepts, so builds run serially. Use a number (4) or a core multiplier (2C, 2.5C).": "Maven 不接受这个线程数,构建将串行执行。请填写数字(4)或核数倍数(2C、2.5C)。",
"Unknown macro {all} in the working directory. Supported: {supported}.": "工作目录中有未知的宏 {all}。支持:{supported}。",
"{all} is not available in a remote project.": "{all} 在远程项目中不可用。",
"Cannot start '{name}'": "无法启动“{name}”"
"Not a thread count Maven accepts, so builds run serially. Use a number (4) or a core multiplier (2C, 2.5C).": "Maven 不接受这个线程数,构建将串行执行。请填写数字(4)或核数倍数(2C、2.5C)。"
}
-29
Переглянути файл
@@ -49,35 +49,6 @@ const labels = (tree: HTMLElement) =>
.queryAllByRole("treeitem")
.map((el) => el.textContent);
describe("Tree context-menu selection", () => {
it.each([
{ os: "windows", gesture: { button: 2 } },
{ os: "macos", gesture: { button: 0, ctrlKey: true } },
])("marks $os context-menu selection without changing ordinary activation", ({ os, gesture }) => {
const previousOs = usePlatform.getState().os;
usePlatform.setState({ os });
try {
const selection = vi.fn();
const menu = vi.fn();
const { tree, key, onActivate } = setup({ onSelectionChange: selection, onContextMenu: menu });
const readme = within(tree).getByRole("treeitem", { name: "README.md" });
fireEvent.mouseDown(readme, gesture);
fireEvent.contextMenu(readme, gesture);
expect(selection).toHaveBeenLastCalledWith(new Set(["README.md"]), data[1], "contextMenu");
expect(menu).toHaveBeenCalledWith(data[1], new Set(["README.md"]), expect.anything());
expect(onActivate).not.toHaveBeenCalled();
key("Home");
expect(selection).toHaveBeenLastCalledWith(new Set(["src"]), data[0]);
fireEvent.mouseDown(readme, { button: 0 });
expect(selection).toHaveBeenLastCalledWith(new Set(["README.md"]), data[1]);
key("Enter");
expect(onActivate).toHaveBeenCalledWith(data[1], expect.anything());
} finally {
usePlatform.setState({ os: previousOs });
}
});
});
describe("Tree directory context", () => {
it("does not contribute virtual document URIs as filesystem directories", () => {
const { key } = setup({ getDirectory: () => "jdt://contents/library.jar/package" });
+7 -9
Переглянути файл
@@ -104,8 +104,7 @@ export interface TreeProps<T> {
selected?: ReadonlySet<string>;
defaultSelected?: Iterable<string>;
/** Context-menu selection can update the action target without navigating to it. */
onSelectionChange?: (selected: Set<string>, lead: T | null, reason?: "contextMenu") => void;
onSelectionChange?: (selected: Set<string>, lead: T | null) => void;
multiSelect?: boolean;
/** Enter / double-click on a leaf (or on nodes `activateExpandable` accepts). */
@@ -427,23 +426,22 @@ export function Tree<T>(props: TreeProps<T>) {
};
const commitSelection = useCallback(
(next: Set<string>, leadKey: string | null, reason?: "contextMenu") => {
(next: Set<string>, leadKey: string | null) => {
if (!selectedControlled) setSelectedInner(next);
setLead(leadKey);
const leadRow = leadKey != null ? rows[indexOfKey.get(leadKey) ?? -1] : undefined;
if (reason) props.onSelectionChange?.(next, leadRow?.node ?? null, reason);
else props.onSelectionChange?.(next, leadRow?.node ?? null);
props.onSelectionChange?.(next, leadRow?.node ?? null);
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[rows, indexOfKey, selectedControlled, props.onSelectionChange],
);
const selectIndex = (i: number, mode: "single" | "toggle" | "range" = "single", reason?: "contextMenu") => {
const selectIndex = (i: number, mode: "single" | "toggle" | "range" = "single") => {
const row = rows[i];
if (!row || row.loading) return;
if (mode === "single" || !multiSelect) {
setAnchor(row.key);
commitSelection(new Set([row.key]), row.key, reason);
commitSelection(new Set([row.key]), row.key);
} else if (mode === "toggle") {
const next = new Set(selected);
if (next.has(row.key)) next.delete(row.key);
@@ -651,8 +649,8 @@ export function Tree<T>(props: TreeProps<T>) {
};
const onRowMouseDown = (e: MouseEvent, i: number) => {
if (e.button === 2 || (e.button === 0 && e.ctrlKey && isMacHost())) {
if (!selected.has(rows[i]!.key)) selectIndex(i, "single", "contextMenu");
if (e.button === 2) {
if (!selected.has(rows[i]!.key)) selectIndex(i);
return;
}
if (e.button !== 0) return;
+1 -3
Переглянути файл
@@ -1980,9 +1980,7 @@ export const useDebugRunSessions = create<{
sessions: DebugRunSession[];
serviceSessions: DebugServiceSession[];
Console: ComponentType<{ sessionId: number }> | null;
/** The whole debugger of a session (Services shows it in place); `console` replaces its Console tab. */
View: ComponentType<{ sessionId: number; console?: ReactNode }> | null;
}>(() => ({ sessions: [], serviceSessions: [], Console: null, View: null }));
}>(() => ({ sessions: [], serviceSessions: [], Console: null }));
/**
* The Services tool window's badge: how many of its listed services are running.