From a8a0cdb3155c1140348349afe9086ee568652a9c Mon Sep 17 00:00:00 2001 From: l0ng-ai Date: Mon, 30 Nov 2026 18:16:20 +0800 Subject: [PATCH 01/46] fix(plugins): load precompiled plugin components in the signed macOS app (#7010) compile_cached loaded the cached .cwasm with Component::deserialize_file, which maps the file and makes its pages executable; the hardened runtime of the signed app refuses that, so every activation discarded the cache and compiled the plugin again. The file is now read into memory and deserialized from the bytes. A new test checks the cache is hit; signed with the app entitlements it fails with the old code. Refs #6954 --- crates/ide-plugin/src/runtime.rs | 27 +++++++++++++++++++++++++-- 1 file changed, 25 insertions(+), 2 deletions(-) diff --git a/crates/ide-plugin/src/runtime.rs b/crates/ide-plugin/src/runtime.rs index 6306754cff..f6519e668d 100644 --- a/crates/ide-plugin/src/runtime.rs +++ b/crates/ide-plugin/src/runtime.rs @@ -613,11 +613,14 @@ impl PluginEngine { pub fn compile_cached(&self, wasm: &Path, cache_dir: &Path) -> Result { let bytes = std::fs::read(wasm).map_err(|e| format!("{}: {e}", wasm.display()))?; let file = cache_dir.join(format!("{}.cwasm", self.cache_key(&bytes))); - if file.is_file() { + // Read into memory rather than `deserialize_file`: that maps the file and makes its pages + // executable, which the hardened runtime of the signed macOS app refuses ("failed to make + // memory executable"), so the cache never hit and every activation compiled again. + if let Ok(precompiled) = std::fs::read(&file) { // SAFETY: the cache directory belongs to the IDE (inside its plugins // directory) and is written only by `store_precompiled` below from // components this engine compiled; a corrupt file fails validation. - match unsafe { Component::deserialize_file(&self.engine, &file) } { + match unsafe { Component::deserialize(&self.engine, &precompiled) } { Ok(component) => return Ok(component), Err(e) => { tracing::info!("discarding precompiled {}: {e}", file.display()); @@ -3035,6 +3038,26 @@ impl Runtime { mod tests { use super::*; + /// The second compile of the same component loads the cached one instead of compiling and + /// writing it again (a failed load deletes and rewrites the file). + #[test] + fn a_precompiled_component_is_loaded_from_the_cache() { + let engine = PluginEngine::new().unwrap(); + let wasm = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/hello/dist/plugin.wasm"); + let cache = tempfile::tempdir().unwrap(); + engine.compile_cached(&wasm, cache.path()).unwrap(); + let cached = || { + let entries: Vec<_> = std::fs::read_dir(cache.path()).unwrap().flatten().map(|e| e.path()).collect(); + assert_eq!(entries.len(), 1, "{entries:?}"); + let file = entries[0].clone(); + (std::fs::metadata(&file).unwrap().modified().unwrap(), file) + }; + let before = cached(); + std::thread::sleep(std::time::Duration::from_millis(20)); + engine.compile_cached(&wasm, cache.path()).unwrap(); + assert_eq!(cached(), before, "loaded, not compiled and stored again"); + } + #[test] fn readonly_field_extensions_are_parsed_and_unknown_or_malformed_fields_are_skipped() { let fields = [ From 1cfbb24b31c7a6b3de7d85c47723c7589971e0cd Mon Sep 17 00:00:00 2001 From: l0ng-ai Date: Mon, 30 Nov 2026 18:18:33 +0800 Subject: [PATCH 02/46] fix(project-tree): add Select Opened File as a Project View action for the keymap (#7011) The keymap listed "Select Opened File" only as the Database view action, so a shortcut assigned to it revealed the file in the Database view and did nothing in a project without data sources. Like IDEA's SelectOpenedFileInProjectView, the Project view now has its own Select Opened File action (the toolbar button runs it), and imported IDEA keymaps map SelectOpenedFileInProjectView and SelectInProjectView. Fixes #6978 --- src/features/project-tree/HeaderActions.tsx | 4 ++-- src/features/project-tree/actions.ts | 10 ++++++++++ src/features/project-tree/selectIn.test.ts | 12 ++++++++++++ src/platform/ideaActions.ts | 2 ++ src/platform/keymaps/intellij-macos.ts | 1 + src/platform/keymaps/intellij-windows.ts | 1 + 6 files changed, 28 insertions(+), 2 deletions(-) diff --git a/src/features/project-tree/HeaderActions.tsx b/src/features/project-tree/HeaderActions.tsx index 44c6fcf8b2..87888f3f90 100644 --- a/src/features/project-tree/HeaderActions.tsx +++ b/src/features/project-tree/HeaderActions.tsx @@ -100,9 +100,9 @@ export function ProjectHeaderActions() { {!alwaysSelect && ( )} diff --git a/src/features/project-tree/actions.ts b/src/features/project-tree/actions.ts index 539d78975f..72c781614b 100644 --- a/src/features/project-tree/actions.ts +++ b/src/features/project-tree/actions.ts @@ -254,6 +254,16 @@ export function registerProjectActions(): () => void { keywords: ["locate", "reveal", "scroll from source", "select opened file"], run: ({ arg }) => void selectInProjectView(typeof arg === "string" ? arg : null), }, + { + // IDEA's SelectOpenedFileInProjectView: the Project view toolbar's locate button. + id: "project.selectOpenedFile", + title: "Select Opened File", + category: "Project View", + icon: "locate", + when: OPEN, + keywords: ["locate", "reveal", "scroll from source", "select in project view"], + run: () => void selectInProjectView(null), + }, { id: "project.reveal", title: "Reveal in Project View", diff --git a/src/features/project-tree/selectIn.test.ts b/src/features/project-tree/selectIn.test.ts index 517389c628..b4853ce686 100644 --- a/src/features/project-tree/selectIn.test.ts +++ b/src/features/project-tree/selectIn.test.ts @@ -152,6 +152,18 @@ describe("Select In (⌥F1)", () => { expect(useContextMenuStore.getState().menu).toBeNull(); }); + it("Select Opened File is a Project View action of its own, as in IDEA's keymap", async () => { + const { IDEA_ACTIONS } = await import("@/platform/ideaActions"); + disposers.push(registerProjectActions(), () => setContext("projectOpen", false)); + setContext("projectOpen", true); + expect(getAction("project.selectOpenedFile")).toMatchObject({ + title: "Select Opened File", + category: "Project View", + }); + expect(IDEA_ACTIONS.SelectOpenedFileInProjectView).toBe("project.selectOpenedFile"); + expect(IDEA_ACTIONS.SelectInProjectView).toBe("navigate.selectInProjectView"); + }); + it("expands an in-project folder when expand is true and reveals out-of-project folders in the file manager", async () => { const { useProjectTree } = await import("./store"); const prev = useProjectTree.getState(); diff --git a/src/platform/ideaActions.ts b/src/platform/ideaActions.ts index 25663dd982..0789cb8ac6 100644 --- a/src/platform/ideaActions.ts +++ b/src/platform/ideaActions.ts @@ -6,6 +6,8 @@ export const IDEA_ACTIONS: Readonly> = { GotoDeclaration: "navigate.declaration", GotoImplementation: "navigate.implementation", GotoTypeDeclaration: "navigate.typeDeclaration", + SelectInProjectView: "navigate.selectInProjectView", + SelectOpenedFileInProjectView: "project.selectOpenedFile", GotoSuperMethod: "navigate.superMethod", GotoTest: "navigate.gotoTest", GotoRelated: "navigate.relatedSymbol", diff --git a/src/platform/keymaps/intellij-macos.ts b/src/platform/keymaps/intellij-macos.ts index 2e17e48e57..8a85ab86ec 100644 --- a/src/platform/keymaps/intellij-macos.ts +++ b/src/platform/keymaps/intellij-macos.ts @@ -531,6 +531,7 @@ export const intellijMacos: Record = { "db.showDiagram": ["Meta+Alt+Shift+U"], "db.showDiagramPopup": ["Meta+Alt+U"], "db.selectOpened": [], + "project.selectOpenedFile": [], "db.expandAll": [], "db.collapseAll": [], // Terminal (keyWhen: terminalFocus); after VCS Update / Go to Test so it wins there. diff --git a/src/platform/keymaps/intellij-windows.ts b/src/platform/keymaps/intellij-windows.ts index 0b3be6116c..1c251e4ec3 100644 --- a/src/platform/keymaps/intellij-windows.ts +++ b/src/platform/keymaps/intellij-windows.ts @@ -529,6 +529,7 @@ export const intellijWindows: Record = { "db.showDiagram": ["Ctrl+Alt+Shift+U"], "db.showDiagramPopup": ["Ctrl+Alt+U"], "db.selectOpened": [], + "project.selectOpenedFile": [], "db.expandAll": [], "db.collapseAll": [], // Terminal (keyWhen: terminalFocus); after VCS Update / Go to Test so it wins there. From cc9279a6d6026fbbfd4324b9738517f673e85c87 Mon Sep 17 00:00:00 2001 From: l0ng-ai Date: Mon, 30 Nov 2026 18:22:26 +0800 Subject: [PATCH 03/46] fix(editor): indent Slint element blocks by their braces (#7012) Slint borrows the C mode for highlighting until slint-lsp's semantic tokens arrive, and Enter used that mode's statement indentation: after a child element's closing brace the next line went back to column 0, and nested blocks below it opened one level short. Slint now uses the brace-based fallback indentation even though a highlighting mode is loaded. No other language with a borrowed mode has this mismatch. Fixes #6976 --- src/editor/core/cm/languages.test.ts | 44 ++++++++++++++++++++++++++-- src/editor/core/cm/languages.ts | 9 +++++- 2 files changed, 50 insertions(+), 3 deletions(-) diff --git a/src/editor/core/cm/languages.test.ts b/src/editor/core/cm/languages.test.ts index ac9979a5b2..5e07204b38 100644 --- a/src/editor/core/cm/languages.test.ts +++ b/src/editor/core/cm/languages.test.ts @@ -1,12 +1,12 @@ import { EditorSelection, EditorState } from "@codemirror/state"; import { EditorView } from "@codemirror/view"; import { insertNewlineAndIndent } from "@codemirror/commands"; -import { LanguageDescription, type Language } from "@codemirror/language"; +import { LanguageDescription, indentUnit, type Language } from "@codemirror/language"; import { describe, expect, it } from "vitest"; import { getIndentation } from "@codemirror/language"; import { highlightTree, tagHighlighter, tags as t } from "@lezer/highlight"; import { logWarning } from "./highlight"; -import { fencedCodeMode, findLanguageDescription, loadSupport } from "./languages"; +import { commentTokens, fencedCodeMode, findLanguageDescription, loadSupport } from "./languages"; describe("language modes", () => { it("highlights Julia declarations, calls, types, macros and literals without semantic tokens", async () => { @@ -765,3 +765,43 @@ describe("language modes", () => { expect(found).not.toContain("yes:keyword"); }); }); + +describe("Slint indentation", () => { + it("indents element blocks by their braces under the C highlighting mode", async () => { + const support = await loadSupport(findLanguageDescription("C", "/p/app.slint")!); + const slint = commentTokens({ + id: "slint", + name: "Slint", + extensions: ["slint"], + uiMode: "C", + lineComment: "//", + blockComment: ["/*", "*/"], + indent: { tabSize: 4, insertSpaces: true }, + }); + const enter = (doc: string, at = doc.length) => { + const view = new EditorView({ + state: EditorState.create({ + doc, + selection: EditorSelection.cursor(at), + extensions: [support!, slint, indentUnit.of(" ")], + }), + parent: document.body, + }); + insertNewlineAndIndent(view); + const out = view.state.doc.toString(); + view.destroy(); + return out; + }; + const app = "export component App inherits Window {"; + expect(enter(app)).toBe(`${app}\n `); + expect(enter(`${app}}`, app.length)).toBe(`${app}\n \n}`); + expect(enter(`${app}\n width: 100px;`)).toBe(`${app}\n width: 100px;\n `); + // After a child element closes, the next line stays at the child's level. + expect(enter(`${app}\n Text {\n text: "hi";\n }`)).toBe( + `${app}\n Text {\n text: "hi";\n }\n `, + ); + expect(enter(`${app}\n Text {\n }\n Rectangle {`)).toBe( + `${app}\n Text {\n }\n Rectangle {\n `, + ); + }); +}); diff --git a/src/editor/core/cm/languages.ts b/src/editor/core/cm/languages.ts index 09fce0bb29..a49c4ede01 100644 --- a/src/editor/core/cm/languages.ts +++ b/src/editor/core/cm/languages.ts @@ -740,6 +740,13 @@ const NO_INDENT_LANGS = new Set([ "gitattributes", ]); +/** + * Languages highlighted by a borrowed mode whose own indentation doesn't fit them: Slint's + * element blocks (`Text { … }` without a `;`) read as unfinished C statements, so Enter after + * one lands at the wrong column. These use the brace-based fallback indentation instead. + */ +const BRACE_INDENT_OVER_MODE = new Set(["slint"]); + function opensBlock(code: string, language: string | undefined): boolean { if (!code) return false; if (/[{([]$/.test(code)) return true; @@ -779,7 +786,7 @@ function indentationCode(text: string, lineComment: string | undefined): string */ export function fallbackIndent(language?: string): Extension { return indentService.of((cx, pos) => { - if (cx.state.facet(languageFacet)) return undefined; + if (cx.state.facet(languageFacet) && !BRACE_INDENT_OVER_MODE.has(language ?? "")) return undefined; const lineComment = cx.state.languageDataAt<{ line?: string }>("commentTokens", pos)[0]?.line; const stripComment = (text: string) => indentationCode(text, lineComment); From 7ff223001bc9d68de26a2596fb3d9f0259a22fc0 Mon Sep 17 00:00:00 2001 From: l0ng-ai Date: Mon, 30 Nov 2026 18:25:17 +0800 Subject: [PATCH 04/46] fix(fonts): keep Latin text monospaced when the chosen font isn't installed (#7013) With a fallback font set and a primary family that isn't installed, every glyph came from the fallback. A CJK fallback such as PingFang SC has proportional Latin letters, and the terminal sized its cells for the widest of them, so text came out spread apart. Once the native font catalog shows the family is missing, the bundled JetBrains Mono now stands in for it ahead of the fallback, which still covers the glyphs it lacks. Applies to every monospace stack built from the editor or terminal font settings. Fixes #6974 --- src/platform/fonts.test.ts | 23 +++++++++++++++++++++++ src/platform/fonts.ts | 22 ++++++++++++++++++++-- 2 files changed, 43 insertions(+), 2 deletions(-) diff --git a/src/platform/fonts.test.ts b/src/platform/fonts.test.ts index eaf8d7c58c..01cfbcb5a7 100644 --- a/src/platform/fonts.test.ts +++ b/src/platform/fonts.test.ts @@ -101,6 +101,29 @@ describe("resolveMonoFont", () => { }); }); +describe("a chosen family that isn't installed", () => { + afterEach(() => { + vi.resetModules(); + }); + + it("puts the bundled face before the fallback, so Latin text doesn't take the fallback's proportional letters", async () => { + const fonts = await import("./fonts"); + // Before the native catalog loads nothing is known to be missing. + expect(fonts.monoFontFamily("Fira Code", "PingFang SC", BASE)).toBe(`"Fira Code", "PingFang SC", ${BASE}`); + fonts.noteInstalledFonts(["PingFang SC", "Menlo"]); + expect(fonts.monoFontFamily("Fira Code", "PingFang SC", BASE)).toBe( + `"Fira Code", "JetBrains Mono", "JetBrains Mono Variable", "PingFang SC", ${BASE}`, + ); + // Installed, bundled and generic families keep the fallback right after them; so does no fallback. + expect(fonts.monoFontFamily("menlo", "PingFang SC", BASE)).toBe(`"menlo", "PingFang SC", ${BASE}`); + expect(fonts.monoFontFamily("Inter", "PingFang SC", BASE)).toBe( + `"Inter", "Inter Variable", "PingFang SC", ${BASE}`, + ); + expect(fonts.monoFontFamily("monospace", "PingFang SC", BASE)).toBe(`"monospace", "PingFang SC", ${BASE}`); + expect(fonts.monoFontFamily("Fira Code", "", BASE)).toBe(`"Fira Code", ${BASE}`); + }); +}); + describe("discovered Nerd Font fallbacks (#3723)", () => { afterEach(() => { vi.resetModules(); diff --git a/src/platform/fonts.ts b/src/platform/fonts.ts index 9990f2ae89..f9cc7a1c7a 100644 --- a/src/platform/fonts.ts +++ b/src/platform/fonts.ts @@ -98,12 +98,15 @@ async function loadUserFont(name: string, alias: string): Promise { * face is named alone unless the native catalog lists an installed JetBrains Mono. */ let monoInstalled: boolean | null = null; +/** Lower-cased installed family names from the native catalog, once it has loaded. */ +let installedFamilies: ReadonlySet | null = null; const bundledMonoOnly = () => guessOs() === "linux" && monoInstalled !== true; const BUNDLED_MONO_STACK = '"JetBrains Mono Variable", ui-monospace, monospace'; /** Records whether the system has JetBrains Mono installed (`installed`: the native catalog, not the bundled list). */ export function noteInstalledFonts(installed: readonly string[], root?: HTMLElement): void { - monoInstalled = installed.some((name) => name.trim().toLowerCase() === BUNDLED_MONO_FAMILY.toLowerCase()); + installedFamilies = new Set(installed.map((name) => name.trim().toLowerCase())); + monoInstalled = installedFamilies.has(BUNDLED_MONO_FAMILY.toLowerCase()); installMonoStack(root); } @@ -256,7 +259,22 @@ export function monoFontFamily(family: string | undefined, fallback = "", base = const name = familyName(family ?? ""); const fb = familyName(fallback); const head = familyFaces(name || BUNDLED_MONO_FAMILY); - return [...head, ...(fb ? familyFaces(fb) : []), base].join(", "); + // A chosen family that isn't installed leaves every glyph to the fallback, often a CJK face + // whose Latin letters are proportional: a grid measures its cells by the widest of them and + // the text comes out spread apart. The bundled face stands in for the missing one, and the + // fallback still covers what that lacks. + const standIn = fb && name && familyMissing(name) ? familyFaces(BUNDLED_MONO_FAMILY) : []; + return [...head, ...standIn, ...(fb ? familyFaces(fb) : []), base].join(", "); +} + +const GENERIC_FAMILIES = + /^(?:monospace|ui-monospace|sans-serif|serif|system-ui|ui-sans-serif|ui-serif|cursive|fantasy)$/i; + +/** Whether the native catalog has loaded and doesn't list `name` (bundled and generic families always count as present). */ +function familyMissing(name: string): boolean { + if (!installedFamilies) return false; + const key = name.toLowerCase(); + return !installedFamilies.has(key) && !BUNDLED_FACES.has(key) && !GENERIC_FAMILIES.test(name); } /** Tools › Terminal › Font, shared by the terminal and the Run console. */ From b9e555300f42ed83fff0919dbe4f9c465db6eea7 Mon Sep 17 00:00:00 2001 From: Ivan <87540740+Pecnikas@users.noreply.github.com> Date: Mon, 30 Nov 2026 15:30:57 +0500 Subject: [PATCH 05/46] fix(macos): defer moving a full-screen tab out of its group until the app is active (#6997) Close Project on a tab of a native full-screen group moves the tab into a window, and so a full-screen Space, of its own. While the app is inactive, AppKit's enter-full-screen transition for that Space crashes in SLSWindowServerClientSpaceAddWindowsAndRemoveFromSpaces as soon as the web view draws its next frame, taking every project window with it. Detaching such a tab is now deferred: the tab stays in its group (showing Welcome) and moves to its own Space when the app is next activated. Foreground closes and windowed groups detach immediately as before. Fixes #6937 Co-authored-by: Pecnikas <87540740+Pecnikas@users.noreply.github.com> --- src-tauri/src/application_focus.rs | 2 ++ src-tauri/src/macos.rs | 10 ++++++++++ src-tauri/src/window_groups.rs | 18 ++++++++++++++++++ 3 files changed, 30 insertions(+) diff --git a/src-tauri/src/application_focus.rs b/src-tauri/src/application_focus.rs index be929ce701..7b4edfd532 100644 --- a/src-tauri/src/application_focus.rs +++ b/src-tauri/src/application_focus.rs @@ -26,6 +26,8 @@ impl ApplicationFocus { pub fn changed(app: &tauri::AppHandle, focused: bool) { let generation = app.state::().changed(focused); if focused { + #[cfg(target_os = "macos")] + crate::window_groups::detach_deferred(app); return; } let app = app.clone(); diff --git a/src-tauri/src/macos.rs b/src-tauri/src/macos.rs index 9eb560dae8..28ebadadd1 100644 --- a/src-tauri/src/macos.rs +++ b/src-tauri/src/macos.rs @@ -114,6 +114,16 @@ pub fn sync_tab_group( }) } +pub fn fullscreen_in_background(window: &WebviewWindow) -> bool { + let target = window.clone(); + on_main(window, move || { + let active = + MainThreadMarker::new().is_some_and(|mtm| objc2_app_kit::NSApplication::sharedApplication(mtm).isActive()); + !active && native(&target).is_some_and(|w| w.styleMask().contains(objc2_app_kit::NSWindowStyleMask::FullScreen)) + }) + .unwrap_or(false) +} + /// Takes `window` out of its tab group into a window of its own; in full screen, a Space of its own. pub fn move_tab_to_new_window(window: &WebviewWindow) -> tauri::Result<()> { let target = window.clone(); diff --git a/src-tauri/src/window_groups.rs b/src-tauri/src/window_groups.rs index 29d0797b11..40b3dc1d74 100644 --- a/src-tauri/src/window_groups.rs +++ b/src-tauri/src/window_groups.rs @@ -201,9 +201,19 @@ pub fn merge(app: &AppHandle, caller: &str) -> IdeResult<()> { select(app, caller, caller) } +#[cfg(target_os = "macos")] +static DEFERRED_DETACH: parking_lot::Mutex> = parking_lot::Mutex::new(Vec::new()); + pub fn detach(app: &AppHandle, caller: &str) -> IdeResult<()> { let err = |e: tauri::Error| IdeError::internal(e.to_string()); let state = app.state::(); + #[cfg(target_os = "macos")] + if state.groups.lock().group(caller).is_some() + && app.get_webview_window(caller).is_some_and(|w| crate::macos::fullscreen_in_background(&w)) + { + DEFERRED_DETACH.lock().push(caller.to_owned()); + return Ok(()); + } let Some(next) = state.groups.lock().detach(caller) else { changed(app); return Ok(()); @@ -234,6 +244,14 @@ pub fn detach(app: &AppHandle, caller: &str) -> IdeResult<()> { Ok(()) } +#[cfg(target_os = "macos")] +pub fn detach_deferred(app: &AppHandle) { + let labels = std::mem::take(&mut *DEFERRED_DETACH.lock()); + for label in labels { + let _ = detach(app, &label); + } +} + pub fn destroyed(app: &AppHandle, caller: &str) { let Some(state) = app.try_state::() else { return }; let next = state.groups.lock().detach(caller); From 88a6bbca14b339bf32dec2eb27edb4f2e82c4345 Mon Sep 17 00:00:00 2001 From: audichuang <72485427+audichuang@users.noreply.github.com> Date: Mon, 30 Nov 2026 18:32:37 +0800 Subject: [PATCH 06/46] perf(vcs): run Git outside the log index lock so commit details and one-commit queries do not wait for a history walk (#7006) history::log held the log index lock for its whole run, so every Git subprocess it started (file history, path selection, range ids, rev-list, the --grep text filter) ran under the lock, and commit details plus the one-commit queries behind inline blame waited for the whole walk. The lock is now taken per phase: Git runs unlocked and only in-memory work holds the guard. update_head_reachable runs under the guard that builds the rows, and the shared nodes are used only when they were built for the query's shallow set, rebuilt otherwise, so a query stays on one snapshot while others run in between. Co-authored-by: audichuang <72485427+audichuang@users.noreply.github.com> --- crates/ide-vcs/src/history.rs | 72 +++++++++++++++++++++++------ crates/ide-vcs/tests/log_lock.rs | 79 ++++++++++++++++++++++++++++++++ 2 files changed, 136 insertions(+), 15 deletions(-) create mode 100644 crates/ide-vcs/tests/log_lock.rs diff --git a/crates/ide-vcs/src/history.rs b/crates/ide-vcs/src/history.rs index 803eedb1b6..b73b7aa4bb 100644 --- a/crates/ide-vcs/src/history.rs +++ b/crates/ide-vcs/src/history.rs @@ -464,11 +464,16 @@ fn renamed_from( Ok(None) } +/// The log index, locked only around reads and writes: Git runs without it, so commit +/// details and one-commit queries need not wait for a long history walk. +fn lock(index: &std::sync::Mutex) -> std::sync::MutexGuard<'_, crate::log_index::LogIndex> { + index.lock().unwrap_or_else(|p| p.into_inner()) +} + pub(crate) fn log(r: &Repo, q: &LogQuery, cancel: &CancellationToken) -> IdeResult> { if cancel.is_cancelled() { return Err(IdeError::cancelled()); } - let mut index = r.log_index.lock().unwrap_or_else(|p| p.into_inner()); let result = if q.summary_only { let mut all = q.clone(); all.skip = 0; @@ -483,14 +488,19 @@ pub(crate) fn log(r: &Repo, q: &LogQuery, cancel: &CancellationToken) -> IdeResu repo.shallow_commits().map_err(gx)?.map(|ids| ids.iter().copied().collect::>()).unwrap_or_default(); let shallow: HashSet = shallow_vec.iter().copied().collect(); let key = format!("{}:{generation}:{shallow_vec:?}", serde_json::to_string(&all).map_err(gx)?); - let cached = index.views.get(&key).cloned(); + let cached = lock(&r.log_index).views.get(&key).cloned(); let view = if let Some(cached) = cached { cached } else { // Immutable metadata is reused across roots, filters, merges and ref changes. all.request = q.request; - let rows = - std::sync::Arc::new(crate::log_index::IndexedView::new(log_indexed_rows(r, &all, cancel, &mut index)?)); + let rows = std::sync::Arc::new(crate::log_index::IndexedView::new(log_indexed_rows( + r, + &all, + cancel, + &r.log_index, + )?)); + let mut index = lock(&r.log_index); if index.views.len() >= 4 { index.views.clear(); } @@ -512,6 +522,7 @@ pub(crate) fn log(r: &Repo, q: &LogQuery, cancel: &CancellationToken) -> IdeResu let retain = q.retain_until.as_ref().and_then(|id| find_pos(id)).map(|i| i + 1).unwrap_or(0); let limit = if q.limit == 0 { usize::MAX } else { (q.limit as usize).max(retain.saturating_sub(start)) }; let total = view.rows.len() as u32; + let mut index = lock(&r.log_index); let db = index.db().cloned(); let txn = db.as_ref().and_then(|db| db.begin_read().ok()); let table = txn.as_ref().and_then(|t| t.open_table(crate::log_index::COMMITS).ok()); @@ -538,9 +549,9 @@ pub(crate) fn log(r: &Repo, q: &LogQuery, cancel: &CancellationToken) -> IdeResu } Ok(result) } else { - log_indexed(r, q, cancel, &mut index) + log_indexed(r, q, cancel, &r.log_index) }; - index.flush(); + lock(&r.log_index).flush(); result } @@ -640,7 +651,7 @@ fn log_indexed( r: &Repo, q: &LogQuery, cancel: &CancellationToken, - index: &mut crate::log_index::LogIndex, + shared: &std::sync::Mutex, ) -> IdeResult> { let repo = r.gix()?; let shallow: HashSet = @@ -676,6 +687,8 @@ fn log_indexed( && q.since_ms.is_none() && q.until_ms.is_none() { + let mut guard = lock(shared); + let index = &mut *guard; update_head_reachable(&repo, index, cancel)?; let id = tips[0]; let record = index.get(&repo, id)?; @@ -706,7 +719,9 @@ fn log_indexed( commit.message_truncated = false; return Ok(vec![commit]); } - let rows = log_indexed_rows(r, q, cancel, index)?; + let rows = log_indexed_rows(r, q, cancel, shared)?; + let mut guard = lock(shared); + let index = &mut *guard; let db = index.db().cloned(); let txn = db.as_ref().and_then(|db| db.begin_read().ok()); let table = txn.as_ref().and_then(|t| t.open_table(crate::log_index::COMMITS).ok()); @@ -724,7 +739,7 @@ fn log_indexed_rows( r: &Repo, q: &LogQuery, cancel: &CancellationToken, - index: &mut crate::log_index::LogIndex, + shared: &std::sync::Mutex, ) -> IdeResult> { if cancel.is_cancelled() { return Err(IdeError::cancelled()); @@ -775,7 +790,7 @@ fn log_indexed_rows( } } } - Some(sort_subset(&repo, ids, q.order, q.first_parent, &shallow, cancel, &index.nodes)?) + Some(sort_shared(&repo, ids, q, &shallow, cancel, shared)?) } else { None }; @@ -802,14 +817,17 @@ fn log_indexed_rows( }; let authors: Vec<_> = q.author.iter().chain(&q.authors).map(|a| a.trim().to_lowercase()).filter(|a| !a.is_empty()).collect(); - update_head_reachable(&repo, index, cancel)?; let mut range_ids_set = range_ids.as_ref().map(|ids| ids.iter().copied().collect::>()); type Walk<'a> = Box> + 'a>; let walk: Walk<'_> = if let Some(ids) = range_ids { Box::new(ids.into_iter().map(Ok)) } else if q.summary_only { - let ids = index.graph(&repo, &tips, &shallow, q.first_parent, cancel)?; - Box::new(sort_subset(&repo, ids, q.order, q.first_parent, &shallow, cancel, &index.nodes)?.into_iter().map(Ok)) + // One guard for both: a concurrent query with another shallow set resets `nodes`. + let mut guard = lock(shared); + let ids = guard.graph(&repo, &tips, &shallow, q.first_parent, cancel)?; + let sorted = sort_subset(&repo, ids, q.order, q.first_parent, &shallow, cancel, &guard.nodes)?; + drop(guard); + Box::new(sorted.into_iter().map(Ok)) } else if repo.is_shallow().unwrap_or(false) || q.request.is_some() { // The process can be interrupted even during indegree preparation. Git also // respects shallow boundaries while retaining a topological order. @@ -866,7 +884,7 @@ fn log_indexed_rows( LogOrder::Topo | LogOrder::Standard => topo::Sorting::TopoOrder, LogOrder::Date => topo::Sorting::DateOrder, }; - let topo = topo::Builder::from_iters(&repo.objects, tips, None::>) + let topo = topo::Builder::from_iters(&repo.objects, tips.clone(), None::>) .sorting(sorting) .parents(if q.first_parent { Parents::First } else { Parents::All }) .with_commit_graph(graph) @@ -876,11 +894,20 @@ fn log_indexed_rows( }; let walk: Walk<'_> = if q.order == LogOrder::Standard { let ids = walk.collect::>>()?; - Box::new(sort_subset(&repo, ids, q.order, q.first_parent, &shallow, cancel, &index.nodes)?.into_iter().map(Ok)) + Box::new(sort_shared(&repo, ids, q, &shallow, cancel, shared)?.into_iter().map(Ok)) } else { walk }; let text = q.text.as_deref().map(|t| TextFilter::new(r, &scopes, q, t, cancel)).transpose()?.flatten(); + let mut guard = lock(shared); + let index = &mut *guard; + // Under the guard that builds the rows: a query run meanwhile (after a branch switch) + // may have moved the shared set to another HEAD. + update_head_reachable(&repo, index, cancel)?; + // A query started before a shallow change may have reset `nodes` to its older set. + if index.shallow != shallow { + index.ensure_nodes(&repo, &tips, &shallow, cancel)?; + } let db = index.db().cloned(); let txn = db.as_ref().and_then(|db| db.begin_read().ok()); let table = txn.as_ref().and_then(|t| t.open_table(crate::log_index::COMMITS).ok()); @@ -952,6 +979,21 @@ fn log_indexed_rows( Ok(out) } +/// Sorts with the shared nodes only when they were built for this query's shallow set. +fn sort_shared( + repo: &gix::Repository, + ids: Vec, + q: &LogQuery, + shallow: &HashSet, + cancel: &CancellationToken, + shared: &std::sync::Mutex, +) -> IdeResult> { + let guard = lock(shared); + let empty = HashMap::new(); + let nodes = if &guard.shallow == shallow { &guard.nodes } else { &empty }; + sort_subset(repo, ids, q.order, q.first_parent, shallow, cancel, nodes) +} + /// A ready-node stack gives incoming merge parents priority, while child counts /// prevent an ancestor shared with another branch from moving ahead of its children. fn sort_subset( diff --git a/crates/ide-vcs/tests/log_lock.rs b/crates/ide-vcs/tests/log_lock.rs new file mode 100644 index 0000000000..e14622842e --- /dev/null +++ b/crates/ide-vcs/tests/log_lock.rs @@ -0,0 +1,79 @@ +//! A long file history walk must not hold the log index while Git runs: commit details and +//! one-commit queries (inline blame, the blame popup) share that index. +#![cfg(unix)] + +use ide_vcs::{LogQuery, Repo}; +use std::os::unix::fs::PermissionsExt; +use std::path::Path; +use std::process::Command; +use std::time::{Duration, Instant}; + +fn git(dir: &Path, args: &[&str]) -> String { + let out = Command::new("git") + .current_dir(dir) + .args([ + "-c", + "init.defaultBranch=main", + "-c", + "user.name=T", + "-c", + "user.email=t@e", + "-c", + "commit.gpgsign=false", + ]) + .args(args) + .output() + .unwrap(); + assert!(out.status.success(), "{args:?}: {}", String::from_utf8_lossy(&out.stderr)); + String::from_utf8_lossy(&out.stdout).trim().to_string() +} + +#[test] +fn details_and_one_commit_queries_do_not_wait_for_a_file_history_walk() { + let tmp = tempfile::tempdir().unwrap(); + let dir = tmp.path().join("repo"); + std::fs::create_dir(&dir).unwrap(); + git(&dir, &["init", "-q"]); + for i in 0..3 { + std::fs::write(dir.join("file"), format!("{i}")).unwrap(); + git(&dir, &["add", "-A"]); + git(&dir, &["commit", "-qm", &format!("c{i}")]); + } + // A git whose path-limited history walks take seconds. + let real = String::from_utf8(Command::new("sh").args(["-c", "command -v git"]).output().unwrap().stdout).unwrap(); + let started = tmp.path().join("walk-started"); + let wrapper = tmp.path().join("slow-git"); + std::fs::write( + &wrapper, + format!( + "#!/bin/sh\ncase \" $* \" in *\" --full-history \"*) : > '{}'; sleep 3;; esac\nexec '{}' \"$@\"\n", + started.display(), + real.trim() + ), + ) + .unwrap(); + std::fs::set_permissions(&wrapper, std::fs::Permissions::from_mode(0o755)).unwrap(); + let repo = Repo::discover(&dir).unwrap().unwrap(); + repo.set_execution_allowed(true); + repo.set_git_executable(Some(&wrapper)); + std::thread::scope(|scope| { + let walk = scope.spawn(|| { + repo.log(&LogQuery { path: Some("file".into()), follow: true, ..Default::default() }).unwrap().len() + }); + let deadline = Instant::now() + Duration::from_secs(20); + while !started.exists() { + assert!(Instant::now() < deadline, "the history walk never started"); + std::thread::sleep(Duration::from_millis(20)); + } + let asked = Instant::now(); + let details = repo.log_details("HEAD").unwrap(); + let head = repo.log(&LogQuery { branch: Some("HEAD".into()), limit: 1, ..Default::default() }).unwrap(); + let waited = asked.elapsed(); + println!("queries waited {waited:?}"); + assert_eq!(details.message, "c2"); + assert_eq!(head.len(), 1); + assert!(!walk.is_finished(), "the walk ended before the queries ran; the test proves nothing"); + assert!(waited < Duration::from_secs(2), "queries waited {waited:?} for the walk"); + assert_eq!(walk.join().unwrap(), 3); + }); +} From c8dc6134857e5a3db4a6d093d53d68bf181eba1f Mon Sep 17 00:00:00 2001 From: l0ng-ai Date: Mon, 30 Nov 2026 18:36:46 +0800 Subject: [PATCH 07/46] fix(projects): offer New Tab when opening a remote project or from a remote window (#7017) The Open Project prompt gated Attach and New Tab on one flag that required a local project in a local window, so opening an SSH/WSL project, or any project from a remote window, offered only New Window and This Window, and "Open project in: tab" fell back to a new window. Attach still needs a local project in a local window, but a project tab is a window of its own joined to this window's group, so it now applies whenever this window has a project: a remote project opens in a new window that joins the group. Fixes #6923 --- src/platform/locales/text/en.json | 1 + src/platform/locales/text/ru.json | 1 + src/platform/locales/text/tr.json | 1 + src/platform/locales/text/zh-TW.json | 1 + src/platform/locales/text/zh.json | 1 + src/workbench/projectWindow.test.ts | 30 ++++++++++++++++++++---- src/workbench/projectWindow.ts | 34 +++++++++++++++------------- 7 files changed, 48 insertions(+), 21 deletions(-) diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index e36b79bf55..a89ff02d78 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -3740,6 +3740,7 @@ "Saving a Dart file of a running Flutter debug session reloads the app, unless the file has errors.": "Saving a Dart file of a running Flutter debug session reloads the app, unless the file has errors.", "Hot reload on save failed: {0}": "Hot reload on save failed: {0}", "Projects can be opened in a new window, replace the current project, be attached to the already opened projects, or open as a new tab of this window.\nHow would you like to open \"{name}\"?": "Projects can be opened in a new window, replace the current project, be attached to the already opened projects, or open as a new tab of this window.\nHow would you like to open \"{name}\"?", + "Projects can be opened in a new window, replace the current project, or open as a new tab of this window.\nHow would you like to open \"{name}\"?": "Projects can be opened in a new window, replace the current project, or open as a new tab of this window.\nHow would you like to open \"{name}\"?", "New Tab": "New Tab", "New tab in current window": "New tab in current window", "Show Only Widgets": "Show Only Widgets", diff --git a/src/platform/locales/text/ru.json b/src/platform/locales/text/ru.json index fe6ce8ffc7..435c1b6b7e 100644 --- a/src/platform/locales/text/ru.json +++ b/src/platform/locales/text/ru.json @@ -9762,6 +9762,7 @@ "Saving a Dart file of a running Flutter debug session reloads the app, unless the file has errors.": "Сохранение файла Dart во время запущенной сессии отладки Flutter перезагружает приложение, если в файле нет ошибок.", "Hot reload on save failed: {0}": "Ошибка горячей перезагрузки при сохранении: {0}", "Projects can be opened in a new window, replace the current project, be attached to the already opened projects, or open as a new tab of this window.\nHow would you like to open \"{name}\"?": "Проекты можно открывать в новом окне, вместо текущего проекта, присоединять к уже открытым проектам или открывать как новую вкладку в этом окне.\nКак открыть «{name}»?", + "Projects can be opened in a new window, replace the current project, or open as a new tab of this window.\nHow would you like to open \"{name}\"?": "Проекты можно открывать в новом окне, вместо текущего проекта или как новую вкладку в этом окне.\nКак открыть «{name}»?", "Show Only Widgets": "Показывать только виджеты", "Update failed": "Не удалось выполнить обновление", "Updating branches": "Обновление веток", diff --git a/src/platform/locales/text/tr.json b/src/platform/locales/text/tr.json index eae6899523..d3615f8847 100644 --- a/src/platform/locales/text/tr.json +++ b/src/platform/locales/text/tr.json @@ -2668,6 +2668,7 @@ "Saving a Dart file of a running Flutter debug session reloads the app, unless the file has errors.": "Çalışan Flutter hata ayıklama oturumunda Dart dosyası kaydedildiğinde, dosyada hata yoksa uygulama yeniden yüklenir.", "Hot reload on save failed: {0}": "Kaydetmede sıcak yeniden yükleme başarısız: {0}", "Projects can be opened in a new window, replace the current project, be attached to the already opened projects, or open as a new tab of this window.\nHow would you like to open \"{name}\"?": "Projeler yeni pencerede açılabilir, geçerli projenin yerini alabilir, açık projelere bağlanabilir veya bu pencerede yeni sekmede açılabilir.\n\"{name}\" nasıl açılsın?", + "Projects can be opened in a new window, replace the current project, or open as a new tab of this window.\nHow would you like to open \"{name}\"?": "Projeler yeni pencerede açılabilir, geçerli projenin yerini alabilir veya bu pencerede yeni sekmede açılabilir.\n\"{name}\" nasıl açılsın?", "New Tab": "Yeni sekme", "New tab in current window": "Geçerli pencerede yeni sekme", "Show Only Widgets": "Yalnızca Bileşenleri Göster", diff --git a/src/platform/locales/text/zh-TW.json b/src/platform/locales/text/zh-TW.json index 96cb167cd5..66fd1a18c8 100644 --- a/src/platform/locales/text/zh-TW.json +++ b/src/platform/locales/text/zh-TW.json @@ -9195,6 +9195,7 @@ "Saving a Dart file of a running Flutter debug session reloads the app, unless the file has errors.": "儲存正在執行的 Flutter 偵錯工作階段裡的 Dart 檔案時重新載入應用,檔案有錯誤時跳過。", "Hot reload on save failed: {0}": "儲存時熱過載失敗:{0}", "Projects can be opened in a new window, replace the current project, be attached to the already opened projects, or open as a new tab of this window.\nHow would you like to open \"{name}\"?": "專案可以在新視窗中開啟、取代目前專案、附加到已開啟的專案,或以新分頁在目前視窗中開啟。\n要如何開啟「{name}」?", + "Projects can be opened in a new window, replace the current project, or open as a new tab of this window.\nHow would you like to open \"{name}\"?": "專案可以在新視窗中開啟、取代目前專案,或以新分頁在目前視窗中開啟。\n要如何開啟「{name}」?", "Show Only Widgets": "僅顯示 Widget", "Update failed": "更新失敗", "Updating branches": "正在更新分支", diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index 63ca504ebd..13538650ed 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -10315,6 +10315,7 @@ "Saving a Dart file of a running Flutter debug session reloads the app, unless the file has errors.": "保存正在运行的 Flutter 调试会话里的 Dart 文件时重新加载应用,文件有错误时跳过。", "Hot reload on save failed: {0}": "保存时热重载失败:{0}", "Projects can be opened in a new window, replace the current project, be attached to the already opened projects, or open as a new tab of this window.\nHow would you like to open \"{name}\"?": "项目可以在新窗口中打开、替换当前项目、附加到已打开的项目,或以新标签页在当前窗口中打开。\n要如何打开“{name}”?", + "Projects can be opened in a new window, replace the current project, or open as a new tab of this window.\nHow would you like to open \"{name}\"?": "项目可以在新窗口中打开、替换当前项目,或以新标签页在当前窗口中打开。\n要如何打开“{name}”?", "Show Only Widgets": "仅显示 Widget", "Update failed": "更新失败", "Updating branches": "正在更新分支", diff --git a/src/workbench/projectWindow.test.ts b/src/workbench/projectWindow.test.ts index 3ed189d27d..9183155cd8 100644 --- a/src/workbench/projectWindow.test.ts +++ b/src/workbench/projectWindow.test.ts @@ -7,9 +7,11 @@ import { ask } from "./messages"; import { commands } from "@/platform/ipc"; const windowOpenRemote = vi.fn(); +const windowGroupJoin = vi.fn(); +const remoteWindow = vi.hoisted(() => ({ value: false })); vi.mock("./messages", () => ({ ask: vi.fn() })); vi.mock("@/platform/remote", () => ({ - isRemoteWindow: () => false, + isRemoteWindow: () => remoteWindow.value, connectRemote: vi.fn(), })); vi.mock("@/platform/ipc", () => ({ @@ -18,10 +20,12 @@ vi.mock("@/platform/ipc", () => ({ commands: { settingsSet: vi.fn(async () => ({ general: { openProjectIn: "attach" } })), windowOpenRemote: (...a: unknown[]) => windowOpenRemote(...a), + windowGroupJoin: (...a: unknown[]) => windowGroupJoin(...a), }, })); beforeEach(() => { vi.clearAllMocks(); + remoteWindow.value = false; useProject.setState({ project: { root: "/a", name: "A", settings: {}, trusted: true, isGit: false }, settings: {}, @@ -40,14 +44,20 @@ it("offers attach for this open without remembering it", async () => { expect(await chooseProjectWindow("C")).toBe(button); expect(ask).toHaveBeenCalledTimes(2); }); -it("does not attach without a project or when opening a remote project", async () => { +it("offers a new tab but no attach for a remote project or from a remote window", async () => { useProject.setState({ settings: { general: { openProjectIn: "attach" } } as never, }); vi.mocked(ask).mockResolvedValue({ button: "cancel", checked: false }); expect(await chooseProjectWindow("remote", false)).toBeNull(); - expect(vi.mocked(ask).mock.calls[0]![0].buttons.map((b) => b.id)).toEqual(["cancel", "new", "same"]); - useProject.setState({ project: null }); + expect(vi.mocked(ask).mock.calls[0]![0].buttons.map((b) => b.id)).toEqual(["cancel", "tab", "new", "same"]); + remoteWindow.value = true; + expect(await chooseProjectWindow("B")).toBeNull(); + expect(vi.mocked(ask).mock.calls[1]![0].buttons.map((b) => b.id)).toEqual(["cancel", "tab", "new", "same"]); + useProject.setState({ project: null, lightEdit: true }); + expect(await chooseProjectWindow("B")).toBeNull(); + expect(vi.mocked(ask).mock.calls[2]![0].buttons.map((b) => b.id)).toEqual(["cancel", "new", "same"]); + useProject.setState({ project: null, lightEdit: false }); expect(await chooseProjectWindow("B")).toBe("same"); }); @@ -65,7 +75,7 @@ it("opens a project tab by policy, or a new window when this one can't take one" useProject.setState({ settings: { general: { openProjectIn: "tab" } } } as never); expect(openPolicy()).toBe("tab"); expect(await chooseProjectWindow("B")).toBe("tab"); - expect(await chooseProjectWindow("remote", false)).toBe("new"); + expect(await chooseProjectWindow("remote", false)).toBe("tab"); useProject.setState({ project: null, lightEdit: true }); expect(await chooseProjectWindow("B")).toBe("new"); expect(ask).not.toHaveBeenCalled(); @@ -91,6 +101,16 @@ describe("a recent project opened with a modifier key", () => { usePlatform.setState({ os }); }); + it("opens a remote project as a project tab of this window", async () => { + windowOpenRemote.mockResolvedValueOnce({ kind: "current" }).mockResolvedValueOnce({ kind: "opened", label: "w2" }); + const here = vi.fn(async () => {}); + useProject.setState({ settings: { general: { openProjectIn: "tab" } } as never }); + expect(await openRemoteProject(target, "/home/me/app", here)).toBe(true); + expect(windowOpenRemote).toHaveBeenLastCalledWith(target, "/home/me/app", true); + expect(windowGroupJoin).toHaveBeenCalledWith("w2"); + expect(here).not.toHaveBeenCalled(); + }); + it("opens a remote project in that window without asking", async () => { windowOpenRemote.mockResolvedValue({ kind: "opened" }); const here = vi.fn(async () => {}); diff --git a/src/workbench/projectWindow.ts b/src/workbench/projectWindow.ts index 309d63db37..292d8da517 100644 --- a/src/workbench/projectWindow.ts +++ b/src/workbench/projectWindow.ts @@ -40,26 +40,26 @@ export async function chooseProjectWindow( ): Promise<"new" | "same" | "attach" | "tab" | null> { const { project, lightEdit } = useProject.getState(); if (!project && !lightEdit) return "same"; - // Both ways of keeping this window's project: a workspace folder, or a project tab of this window. - const canAdd = allowAttach && !!project && !isRemoteWindow(); + // Attach adds a local folder to this local window's workspace; a project tab is a window of its + // own joined to this one's group, so it takes remote projects and remote windows too. + const canTab = !!project; + const canAttach = allowAttach && canTab && !isRemoteWindow(); const mode = openPolicy(); // A project tab needs this window's project beside it; without one, a new window is the closest. - if (mode === "tab") return canAdd ? "tab" : "new"; + if (mode === "tab") return canTab ? "tab" : "new"; if (mode !== "ask") return mode; const r = await ask({ title: t("app.window.askTitle"), - width: canAdd ? 640 : undefined, - body: canAdd + width: canAttach ? 640 : undefined, + body: canAttach ? tx`Projects can be opened in a new window, replace the current project, be attached to the already opened projects, or open as a new tab of this window.\nHow would you like to open "${name}"?` - : t("app.window.askBody", { name }), + : canTab + ? tx`Projects can be opened in a new window, replace the current project, or open as a new tab of this window.\nHow would you like to open "${name}"?` + : t("app.window.askBody", { name }), buttons: [ { id: "cancel", label: t("common.cancel") }, - ...(canAdd - ? [ - { id: "attach", label: t("app.window.askAttach") }, - { id: "tab", label: tx`New Tab` }, - ] - : []), + ...(canAttach ? [{ id: "attach", label: t("app.window.askAttach") }] : []), + ...(canTab ? [{ id: "tab", label: tx`New Tab` }] : []), { id: "new", label: t("app.window.askNew") }, { id: "same", label: t("app.window.askThis"), primary: true }, ], @@ -81,8 +81,8 @@ export async function chooseProjectWindow( /** * Opens folder `path` of `target` (an SSH host or a WSL distribution): focuses the - * window that has it, else opens it in a new window or (`here`) this one per - * "Open project in", or where `override` says. `false`: cancelled. + * window that has it, else opens it in a new window, a project tab of this window or + * (`here`) this one per "Open project in", or where `override` says. `false`: cancelled. */ export async function openRemoteProject( target: RemoteTarget, @@ -93,8 +93,10 @@ export async function openRemoteProject( if ((await call(commands.windowOpenRemote(target, path, false))).kind === "focused") return true; const mode = override ?? (await chooseProjectWindow(path.replace(/\/+$/, "").split("/").pop() || path, false)); if (!mode) return false; - if (mode === "new") { - await call(commands.windowOpenRemote(target, path, true)); + if (mode === "new" || mode === "tab") { + const outcome = await call(commands.windowOpenRemote(target, path, true)); + // As a local project tab: the window holding the project, new or focused, joins this one's group. + if (mode === "tab" && outcome.kind !== "current") await call(commands.windowGroupJoin(outcome.label)); return true; } // The remote host's project doesn't take this window's untitled buffers. From 182c7c1dbb0aa8cd515c6cfb461d8b368129e715 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=96=9B=E7=BA=AA=E5=85=8B?= <245674286@qq.com> Date: Mon, 30 Nov 2026 19:42:00 +0800 Subject: [PATCH 08/46] feat(editor): double-click the empty tab strip to maximize the editor (#6969) A double click on the empty part of an editor tab strip (not on a tab, a button or trailing content) now maximizes the editor by hiding all tool windows, the same as a double click on a regular tab; doing it again restores them. Tabs gets an onBlankDoubleClick callback that fires only for the strip itself or its scroller. Closes #6968 Co-authored-by: xuejike <3352235+xuejike@users.noreply.github.com> --- docs/en/guide/editor.mdx | 2 ++ docs/zh/guide/editor.mdx | 2 ++ src/editor/core/view/EditorArea.tsx | 2 ++ src/ui/Tabs.test.tsx | 10 ++++++++++ src/ui/Tabs.tsx | 16 +++++++++++++++- 5 files changed, 31 insertions(+), 1 deletion(-) diff --git a/docs/en/guide/editor.mdx b/docs/en/guide/editor.mdx index 294d27e0e6..3f53f2fb67 100644 --- a/docs/en/guide/editor.mdx +++ b/docs/en/guide/editor.mdx @@ -145,6 +145,8 @@ Tab placement, the tab limit and what happens when it is reached, the preview ta With tabs placed left or right, the tab column is as wide as its longest name, up to a limit. Drag the column's inner edge (or focus it and press `←` / `→`) to change the limit; it applies to every editor group and is remembered. +Double-click a tab, or the empty part of the tab strip, to maximize the editor: all tool windows are hidden, and doing it again brings them back. Double-clicking a preview tab keeps it open as a regular tab instead. + ## Split editors | Action | macOS | Windows / Linux | diff --git a/docs/zh/guide/editor.mdx b/docs/zh/guide/editor.mdx index d292cc19a2..da721ae6ac 100644 --- a/docs/zh/guide/editor.mdx +++ b/docs/zh/guide/editor.mdx @@ -143,6 +143,8 @@ description: "多光标与选区、行编辑、剪贴板历史、代码折叠、 标签页放在左侧或右侧时,标签页列的宽度随最长的名称变化,但不超过一个上限。拖动该列靠近编辑器的边缘(或聚焦后按 `←` / `→`)可以调整上限;调整对所有编辑器组生效,并会被记住。 +双击标签页或标签页栏的空白处可以最大化编辑器:隐藏所有工具窗口,再双击一次即恢复。双击预览标签页则会把它转为常规标签页。 + ## 拆分编辑器 | 操作 | macOS | Windows / Linux | diff --git a/src/editor/core/view/EditorArea.tsx b/src/editor/core/view/EditorArea.tsx index 08fa0a23b1..2a917b01d0 100644 --- a/src/editor/core/view/EditorArea.tsx +++ b/src/editor/core/view/EditorArea.tsx @@ -399,6 +399,8 @@ function PaneView({ paneId }: { paneId: string }) { onCloseOthers={(id) => void ctrl.closeOthers(paneId, id)} onTogglePin={(id) => ctrl.togglePin(paneId, id)} closeOnShiftClick + // IDEA: a double click on the strip's empty part maximizes the editor, as on a tab. + onBlankDoubleClick={() => void executeAction("toolwindow.hideAll")} onDoubleClick={(id) => { // IDEA: a preview tab becomes a regular one; any other tab maximizes the editor. if (pane.tabs.find((t) => t.id === id)?.preview) ctrl.keepTab(paneId, id); diff --git a/src/ui/Tabs.test.tsx b/src/ui/Tabs.test.tsx index d5ebc4d1c4..56f5d7501c 100644 --- a/src/ui/Tabs.test.tsx +++ b/src/ui/Tabs.test.tsx @@ -103,6 +103,16 @@ describe("Tabs interactions", () => { expect(onClose).toHaveBeenCalledWith("b"); }); + it("double click on the empty strip calls onBlankDoubleClick, not on a tab", () => { + const onBlank = vi.fn(); + const { container } = render( {}} onBlankDoubleClick={onBlank} />); + fireEvent.doubleClick(screen.getByRole("tab", { name: "A" })); + expect(onBlank).not.toHaveBeenCalled(); + fireEvent.doubleClick(screen.getByRole("tablist")); + fireEvent.doubleClick(container.firstElementChild!); + expect(onBlank).toHaveBeenCalledTimes(2); + }); + it("Shift+left-click closes an editor tab without selecting it", () => { const onClose = vi.fn(); const onSelect = vi.fn(); diff --git a/src/ui/Tabs.tsx b/src/ui/Tabs.tsx index 57368298fa..2c6d8b1787 100644 --- a/src/ui/Tabs.tsx +++ b/src/ui/Tabs.tsx @@ -136,6 +136,8 @@ export interface TabsProps { /** Shift+left-click a tab closes it (editor tabs; plain clicks still select). */ closeOnShiftClick?: boolean; onDoubleClick?: (id: string) => void; + /** Double click on the empty part of the strip (not on a tab or button), e.g. to maximize the editor. */ + onBlankDoubleClick?: () => void; onContextMenu?: (id: string, e: MouseEvent) => void; /** `editor`: 30px with separators (editor tabs); `compact`: 28px plain (popups, tool window sub-tabs). */ variant?: "editor" | "compact"; @@ -176,6 +178,7 @@ export function Tabs({ onTogglePin, closeOnShiftClick, onDoubleClick, + onBlankDoubleClick, onContextMenu, variant = "editor", trailing, @@ -397,7 +400,18 @@ export function Tabs({ ); return ( -
+
{ + // Only the strip's own background counts: tabs, buttons and trailing content handle their own clicks. + if (e.target === e.currentTarget || e.target === scrollRef.current) onBlankDoubleClick(); + } + : undefined + } + > {vertical && trailing &&
{trailing}
}
Date: Mon, 30 Nov 2026 19:43:10 +0800 Subject: [PATCH 09/46] feat(search): select Search Everywhere results in the Project view (#6955) File, symbol and text results in Search Everywhere get Select in Project View, in the Alt+Enter menu and in a new right-click menu on the row: it closes the popup and selects the result in the Project tool window. This helps with files that open in another application, such as a .doc, where choosing the result leaves no trace of where the file lives. The item is offered only for paths inside the project. One item list now feeds both menus, and Open to the Side is disabled for folders. Co-authored-by: Greenker <76565859+Greenker@users.noreply.github.com> --- .../search/__tests__/dialogs.test.tsx | 34 +++++++++ .../search/everywhere/SearchEverywhere.tsx | 74 ++++++++++++++----- 2 files changed, 88 insertions(+), 20 deletions(-) diff --git a/src/features/search/__tests__/dialogs.test.tsx b/src/features/search/__tests__/dialogs.test.tsx index 8d9c1177db..3e33f819ff 100644 --- a/src/features/search/__tests__/dialogs.test.tsx +++ b/src/features/search/__tests__/dialogs.test.tsx @@ -62,6 +62,7 @@ vi.mock("../find/windowStore", async (orig) => ({ const contributions = await import("@/workbench/contributions"); const { commands, emitLocalIdeEvent } = await import("@/platform/ipc"); +const { ContextMenuHost } = await import("@/ui"); const { RecentPopupsOverlay } = await import("../recent/RecentPopups"); const { cycleSwitcher, showRecentPopup, hideRecentPopup, useRecentPopup } = await import("../recent/store"); const { openLocation } = await import("../common/open"); @@ -448,6 +449,39 @@ function clickOption(index: number, modifiers = {}) { fireEvent.click(row, modifiers); } +describe("Search Everywhere result actions", () => { + it.each(["keyboard", "right click"] as const)("selects a file in the Project view from the %s menu", async (how) => { + const run = vi.fn(); + const project = useProject.getState().project; + useProject.setState({ project: { root: "/p", name: "p", isGit: false } as never }); + const dispose = registerAction({ + id: "navigate.selectInProjectView", + title: "Select in Project View", + run: ({ arg }) => run(arg), + }); + try { + render( + <> + + + , + ); + act(() => showSearchEverywhere("files", { query: "order" })); + await tick(); + if (how === "keyboard") fireEvent.keyDown(screen.getByLabelText("Search query"), { key: "Enter", altKey: true }); + else fireEvent.contextMenu(resultOptions()[0]!); + await tick(); + fireEvent.click(screen.getByRole("menuitem", { name: /Select in Project View/ })); + await tick(); + expect(run).toHaveBeenCalledExactlyOnceWith("/p/src/OrderController.kt"); + expect(useSearchEverywhere.getState().open).toBe(false); + } finally { + dispose(); + useProject.setState({ project }); + } + }); +}); + describe("Search Everywhere multi-selection", () => { it("extends, shrinks, crosses the anchor and clamps Shift selection; plain arrows select one", async () => { const input = await showDuplicateFiles(); diff --git a/src/features/search/everywhere/SearchEverywhere.tsx b/src/features/search/everywhere/SearchEverywhere.tsx index a3bc86dcb2..b6fb476c35 100644 --- a/src/features/search/everywhere/SearchEverywhere.tsx +++ b/src/features/search/everywhere/SearchEverywhere.tsx @@ -34,13 +34,14 @@ import { selectRow, selectedRows, rowSelectionMode, + showContextMenu, type RowSelection, type MenuItem, T, } from "@/ui"; import { useFileDecoration } from "@/workbench/contributions"; import { highlightTokens, languageForPath, type CodeToken } from "@/editor/lsp/markdown"; -import { badgeKind, basename, openInListOrder, openLocation, relDir } from "../common/open"; +import { badgeKind, basename, openInListOrder, openLocation, projectRoot, relDir } from "../common/open"; import { parseLocationQuery } from "../common/query"; import { setTextSearchOption, useFindPopup } from "../find/store"; import { CodePreview, type PreviewHighlight } from "../find/parts"; @@ -441,35 +442,67 @@ function SearchEverywhereDialog() { /** IDEA's ⌥↵ on an action: record a shortcut for it (written to the active keymap). */ const assignShortcut = (id: string) => closeThen(() => void executeAction("settings.assignShortcut", id)); + /** Actions of a file, symbol or text result: IDEA's ⌥↵ menu and the row's context menu. */ + const resultMenu = (row: NavigationRow): MenuItem[] => { + const copy = (text: string) => void writeClipboardText(text).catch(() => {}); + const folder = row.kind === "file" && row.folder; + const root = projectRoot(); + const inProject = !!root && (row.path === root || row.path.startsWith(root.endsWith("/") ? root : `${root}/`)); + const items: MenuItem[] = [ + { label: "Open", run: () => activate(row) }, + { + label: "Open to the Side", + shortcut: formatBinding("Shift+Enter"), + disabled: !!folder, + run: () => activate(row, true), + }, + // IDEA's Select in Project View (Select Opened File): shows a result opened in another + // application (.doc in WPS) in the Project view, where its place in the project is visible. + ...(inProject + ? [ + { + label: "Select in Project View", + shortcut: shortcutLabel("navigate.selectInProjectView") ?? undefined, + run: () => closeThen(() => void executeActionFrom("search", "navigate.selectInProjectView", row.path)), + }, + ] + : []), + { kind: "separator" }, + ]; + items.push( + { label: "Copy Path", run: () => copy(nativePath(row.path)) }, + { label: "Copy Path from Project Root", run: () => copy(row.rel) }, + ...(row.kind === "symbol" ? [{ label: "Copy Name", run: () => copy(row.name) }] : []), + ...(row.kind === "file" || row.kind === "text" + ? [ + { + label: "Find in Directory…", + run: () => closeThen(() => void executeAction("find.inPath", { directory: dirOf(row.path) })), + }, + ] + : []), + ); + return items; + }; + const openIntentions = () => { const row = activeRow; if (!row || row.kind === "section" || row.kind === "more" || row.kind === "command") return; if (row.kind === "action") return row.run ? undefined : assignShortcut(row.id); const anchor = listRef.current?.querySelector('[data-lead="true"]') ?? inputRef.current; if (!anchor) return; - const copy = (text: string) => void writeClipboardText(text).catch(() => {}); const items: MenuItem[] = - row.kind === "setting" - ? [{ label: "Open Settings Page", run: () => activate(row) }] - : [ - { label: "Open", run: () => activate(row) }, - { label: "Open to the Side", shortcut: formatBinding("Shift+Enter"), run: () => activate(row, true) }, - { kind: "separator" }, - { label: "Copy Path", run: () => copy(nativePath(row.path)) }, - { label: "Copy Path from Project Root", run: () => copy(row.rel) }, - ...(row.kind === "symbol" ? [{ label: "Copy Name", run: () => copy(row.name) }] : []), - ...(row.kind === "file" || row.kind === "text" - ? [ - { - label: "Find in Directory…", - run: () => closeThen(() => void executeAction("find.inPath", { directory: dirOf(row.path) })), - }, - ] - : []), - ]; + row.kind === "setting" ? [{ label: "Open Settings Page", run: () => activate(row) }] : resultMenu(row); setMenu({ anchor, items, placement: "right-start" }); }; + const onRowContextMenu = (row: SeRow, index: number, e: MouseEvent) => { + if (row.kind !== "file" && row.kind !== "symbol" && row.kind !== "text") return; + e.preventDefault(); + select(index, e); + showContextMenu(e, resultMenu(row)); + }; + const onKeyDown = (e: KeyboardEvent) => { if (isImeKey(e.nativeEvent)) return; if (tab === "text" && e.altKey && !e.metaKey && !e.ctrlKey && !e.shiftKey) { @@ -574,6 +607,7 @@ function SearchEverywhereDialog() { if (preview && previewOf(r) && e.type === "click" && e.detail !== 2) return; activate(r, e.shiftKey); }} + onContextMenu={onRowContextMenu} focusable={false} rowHeight={rowHeight} sectionHeight={rowHeight} From 2ecb44098aa779ec022b1e78b45830e93dad5bf2 Mon Sep 17 00:00:00 2001 From: l0ng-ai Date: Mon, 30 Nov 2026 19:48:37 +0800 Subject: [PATCH 10/46] fix(debugger): drop lldb-dap pseudo paths on Windows too (#7030) A referenced source's pseudo path such as /usr/lib/swift/libswiftCore.dylib`swift_willThrow was kept on Windows, where a path with a root but no drive is not absolute, so frames_drop_pseudo_paths_of_referenced_sources failed on Rust (windows-latest) since #6961. A rooted path now counts. --- crates/ide-dap/src/lib.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/ide-dap/src/lib.rs b/crates/ide-dap/src/lib.rs index 9379b78346..bf29baa13f 100644 --- a/crates/ide-dap/src/lib.rs +++ b/crates/ide-dap/src/lib.rs @@ -618,9 +618,10 @@ pub(crate) fn take_debug_server(arguments: &mut Value) -> IdeResult`) stay. +/// Rooted rather than absolute: on Windows a `/usr/…` path has a root but no drive. fn is_pseudo_path(source: Option<&Value>, path: &str) -> bool { let reference = source.and_then(|s| s.get("sourceReference")).and_then(Value::as_i64).unwrap_or(0); - reference > 0 && Path::new(path).is_absolute() && !Path::new(path).exists() + reference > 0 && Path::new(path).has_root() && !Path::new(path).exists() } /// DAP stack frame → [`StackFrame`] (1-based → 0-based). From 4d5ee2d01c1809659a115518791e3386a31224d8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=96=9B=E7=BA=AA=E5=85=8B?= <245674286@qq.com> Date: Mon, 30 Nov 2026 19:56:24 +0800 Subject: [PATCH 11/46] feat(agents): drag and delete the whole task list selection (#6933) In the Agents task list, dragging a row of a multi-selection moves every selected task (into a group, Pinned, a status group, or before or after a task, keeping their order), and Delete deletes the selection while the list has focus. Tree collapsed the selection to the pressed row on mouse down, before a drag could start; a press on a selected row now narrows the selection only on a release without movement. agents.deleteTasks gets a list-focus key binding like agents.archiveTasks, and a click or arrow key opens the session without taking focus from the list; Enter and double-click still focus it. Closes #6932 Co-authored-by: xuejike <3352235+xuejike@users.noreply.github.com> --- src/features/agents/AgentsView.test.tsx | 21 ++++++--- src/features/agents/AgentsView.tsx | 54 +++++++++++++++++++----- src/features/agents/store.ts | 35 +++++++++++---- src/features/agents/taskActions.ts | 7 +++ src/platform/keymaps/intellij-macos.ts | 1 + src/platform/keymaps/intellij-windows.ts | 1 + src/platform/keymaps/vscode-macos.ts | 1 + src/platform/keymaps/vscode-windows.ts | 1 + src/ui/Tree.tsx | 12 +++++- 9 files changed, 109 insertions(+), 24 deletions(-) diff --git a/src/features/agents/AgentsView.test.tsx b/src/features/agents/AgentsView.test.tsx index 8104312be7..4b11a539bf 100644 --- a/src/features/agents/AgentsView.test.tsx +++ b/src/features/agents/AgentsView.test.tsx @@ -162,7 +162,7 @@ describe("Agents selection", () => { vi.mocked(openTask).mockClear(); context("two"); expect(selectedTasks()).toEqual(["one", "two", "three"]); - expect(screen.getByRole("menuitem", { name: "Delete (3)…" })).toBeTruthy(); + expect(screen.getByRole("menuitem", { name: /^Delete \(3\)…/ })).toBeTruthy(); expect(openTask).not.toHaveBeenCalled(); }); @@ -298,9 +298,20 @@ describe("Agents docked view", () => { setup(); expect(screen.queryByRole("button", { name: "Open in Editor" })).toBeNull(); select("two"); - expect(openTask).toHaveBeenCalledWith("two"); + expect(openTask).toHaveBeenCalledWith("two", { focus: false }); expect(dockTask).not.toHaveBeenCalled(); }); + + it("keeps focus in the list when a click opens a task, so Delete deletes that task", async () => { + setup(); + const tree = screen.getByRole("tree", { name: "Agent tasks" }); + tree.focus(); + select("two"); + expect(openTask).toHaveBeenCalledWith("two", { focus: false }); + // The shortcut runs the action without an argument: it takes the list's selection. + await taskActions.find((a) => a.id === "agents.deleteTasks")!.run({ ctx: {}, arg: undefined }); + await waitFor(() => expect(deleteTask).toHaveBeenCalledExactlyOnceWith("two", false)); + }); }); describe("Agents bulk actions", () => { @@ -311,7 +322,7 @@ describe("Agents bulk actions", () => { select("one"); select("three", { shiftKey: true }); context("two"); - fireEvent.click(screen.getByRole("menuitem", { name: "Delete (3)…" })); + fireEvent.click(screen.getByRole("menuitem", { name: /^Delete \(3\)…/ })); await waitFor(() => expect(deleteTask).toHaveBeenCalledTimes(3)); expect(confirmChecked).toHaveBeenCalledTimes(1); expect(confirmChecked).toHaveBeenCalledWith( @@ -329,7 +340,7 @@ describe("Agents bulk actions", () => { select("one"); select("two", { shiftKey: true }); context("four"); - fireEvent.click(screen.getByRole("menuitem", { name: "Delete…" })); + fireEvent.click(screen.getByRole("menuitem", { name: /^Delete…/ })); await waitFor(() => expect(deleteTask).toHaveBeenCalledExactlyOnceWith("four", false)); }); @@ -784,6 +795,6 @@ describe("Agents pinned and grouped tasks", () => { expect(openTask).not.toHaveBeenCalled(); fireEvent.pointerUp(window, { button: 0, clientX: 10, clientY: 104 }); fireEvent.click(sourceSpan, { button: 0 }); - expect(openTask).toHaveBeenCalledWith("two"); + expect(openTask).toHaveBeenCalledWith("two", { focus: false }); }); }); diff --git a/src/features/agents/AgentsView.tsx b/src/features/agents/AgentsView.tsx index 569e362308..c1cb4c77c4 100644 --- a/src/features/agents/AgentsView.tsx +++ b/src/features/agents/AgentsView.tsx @@ -52,8 +52,8 @@ import { openHome, pinTasks, refreshExternalSessions, - reorderTask, reorderTaskGroup, + reorderTasks, showImportSessions, useAgents, } from "./store"; @@ -238,6 +238,8 @@ export function AgentsView() { searchingRef.current = matches !== null; }, [matches]); const cancelDragRef = useRef<(() => void) | undefined>(undefined); + /** Every task the current drag carries, in list order; set when it starts. */ + const draggedIdsRef = useRef([]); const [tasksEl, setTasksEl] = useState(null); const [dropIndicator, setDropIndicator] = useState(null); useEffect(() => { @@ -266,11 +268,18 @@ export function AgentsView() { const { tasks, organize } = useAgents.getState(); const source = tasks.get(data.payload); if (!source) return null; + // Dragging a selected task moves the whole selection. + const ids = draggedIdsRef.current.includes(source.id) ? draggedIdsRef.current : [source.id]; + const sources = ids.flatMap((id) => { + const task = tasks.get(id); + return task ? [task] : []; + }); + const sourceIds = sources.map((t) => t.id); if (targetKey === PINNED_SECTION) { return { indicator: { kind: "section", key: targetKey } as DropIndicator, - apply: () => pinTasks([source.id], true), + apply: () => pinTasks(sourceIds, true), }; } if (targetKey.startsWith("ug:")) { @@ -278,23 +287,33 @@ export function AgentsView() { if (!organize.groups.some((g) => g.id === groupId)) return null; return { indicator: { kind: "section", key: targetKey } as DropIndicator, - apply: () => moveTasksToGroup([source.id], groupId), + apply: () => moveTasksToGroup(sourceIds, groupId), }; } if (targetKey.startsWith("g:")) { - if (sectionOfTask(source, organize) === targetKey) return null; - if (statusSection(taskGroupStatus(source)) !== targetKey) return null; + // A status group takes the tasks of its status that are elsewhere. + const movable = sources.filter( + (t) => sectionOfTask(t, organize) !== targetKey && statusSection(taskGroupStatus(t)) === targetKey, + ); + if (!movable.length) return null; return { indicator: { kind: "section", key: targetKey } as DropIndicator, - apply: () => moveTasksToStatusGroup([source.id]), + apply: () => moveTasksToStatusGroup(movable.map((t) => t.id)), }; } if (searchingRef.current) return null; const target = tasks.get(targetKey); - if (!target || !canReorderTask(source, target, organize)) return null; + if (!target || sourceIds.includes(target.id)) return null; + const movable = sources.filter((t) => canReorderTask(t, target, organize)); + if (!movable.length) return null; return { indicator: { kind: "row", key: targetKey, position } as DropIndicator, - apply: () => reorderTask(source.id, target.id, position), + apply: () => + reorderTasks( + movable.map((t) => t.id), + target.id, + position, + ), }; }; const update = () => { @@ -383,11 +402,26 @@ export function AgentsView() { setHistoryOpen(false); void executeAction("agents.openTask", task); }; + // A click or arrow key in the list opens the session but keeps focus in the list, so its + // shortcuts (Delete) still act on the selection; Enter and double-click focus the session. + const previewTask = (task: string) => { + if (inline) showTask(task); + else void executeAction("agents.openTask", { task, focus: false }); + }; const dockedTitle = docked ? (tasks.get(docked)?.title ?? docked) : null; const dragTask = (e: ReactPointerEvent, task: string, source: HTMLElement = e.currentTarget) => { suppressClickRef.current = false; if (e.button !== 0 || e.ctrlKey || e.metaKey || e.shiftKey) return; cancelDragRef.current?.(); + // A selected row drags the whole selection, in list order. + const current = selectedRef.current; + draggedIdsRef.current = + current.size > 1 && current.has(task) + ? roots + .flatMap((n) => (n.kind === "group" ? n.group.tasks : n.kind === "task" ? [n.task] : n.tasks)) + .map((t) => t.id) + .filter((id, i, all) => current.has(id) && all.indexOf(id) === i) + : [task]; cancelDragRef.current = startPointerDrag( e, source, @@ -478,7 +512,7 @@ export function AgentsView() { if (e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey) return; if ((e.target as Element).closest("button, input, textarea, [data-tree-toggle]")) return; const key = (e.target as Element).closest("[data-tree-key]")?.dataset.treeKey; - if (key && tasks.has(key)) showTask(key); + if (key && tasks.has(key)) previewTask(key); }} onFocus={() => setFocusedTaskList(() => [...selectedRef.current])} onBlur={(e) => { @@ -554,7 +588,7 @@ export function AgentsView() { lead?.kind === "task" && sel.has(lead.task.id) ) - showTask(lead.task.id); + previewTask(lead.task.id); }} onActivate={(n) => n.kind === "task" && showTask(n.task.id)} onContextMenu={(n, sel, e) => { diff --git a/src/features/agents/store.ts b/src/features/agents/store.ts index c548ed681f..57f8d1f75a 100644 --- a/src/features/agents/store.ts +++ b/src/features/agents/store.ts @@ -57,6 +57,7 @@ import { withQuote } from "./conversation"; import { EMPTY_ORGANIZE, PINNED_SECTION, + canReorderTask, compactOrder, customSection, loadOrganize, @@ -1184,7 +1185,8 @@ export function useAgentCommands( return extra.length > 0 ? [...filtered, ...extra] : filtered; } -export function openTask(task: string) { +/** Opens the task's session; `focus: false` opens it in the editor without taking focus (a click in the task list). */ +export function openTask(task: string, options: { focus?: boolean } = {}) { if (routeToWindow(task)) return; forgetClosed(task); if (useAgents.getState().sessionLocation === "toolWindow") { @@ -1192,13 +1194,13 @@ export function openTask(task: string) { return; } useAgents.setState({ lastTask: task, homeOpen: false, lastComposer: task }); - openTaskInEditor(task); + openTaskInEditor(task, options.focus ?? true); } -function openTaskInEditor(task: string) { +function openTaskInEditor(task: string, focus = true) { // The title rides along so a restored tab has it before the tasks load. const title = useAgents.getState().tasks.get(task)?.title; - void editorService().openInput({ kind: SESSION_KIND, key: sessionKey(task), data: { task, title } }, { focus: true }); + void editorService().openInput({ kind: SESSION_KIND, key: sessionKey(task), data: { task, title } }, { focus }); } function showDockedTask(task: string) { @@ -2189,10 +2191,27 @@ export function moveTasksToStatusGroup(tasks: readonly string[]) { }); } -/** Places `sourceId` before or after `targetId` (moving it into the target's section when needed). */ -export function reorderTask(sourceId: string, targetId: string, position: "before" | "after") { - const tasks = useAgents.getState().tasks.values(); - changeOrganize((organize) => reorderTaskInOrganize(organize, tasks, sourceId, targetId, position)); +/** + * Places `sourceIds` (in list order) before or after `targetId`, keeping their relative order. + * Tasks that can't go beside the target (another status than its status group) stay where they are. + */ +export function reorderTasks(sourceIds: readonly string[], targetId: string, position: "before" | "after") { + const tasks = [...useAgents.getState().tasks.values()]; + changeOrganize((organize) => { + let next = organize; + // Before: each goes right before the target. After: each goes after the one placed last. + let anchor = targetId; + const byId = new Map(tasks.map((t) => [t.id, t])); + for (const id of sourceIds) { + if (id === targetId) continue; + const source = byId.get(id); + const target = byId.get(anchor); + if (!source || !target || !canReorderTask(source, target, next)) continue; + next = reorderTaskInOrganize(next, tasks, id, anchor, position); + if (position === "after") anchor = id; + } + return next; + }); } /** Reorders a custom group before or after another custom group. */ diff --git a/src/features/agents/taskActions.ts b/src/features/agents/taskActions.ts index eb93a3f1df..e9e97fe0ca 100644 --- a/src/features/agents/taskActions.ts +++ b/src/features/agents/taskActions.ts @@ -285,6 +285,11 @@ export const taskActions: Action[] = [ hidden: true, run: ({ arg }) => { if (typeof arg === "string") openTask(arg); + // `{ task, focus: false }`: a click in the task list opens the session and keeps focus there. + else if (arg && typeof arg === "object" && typeof (arg as { task?: unknown }).task === "string") { + const { task, focus } = arg as { task: string; focus?: unknown }; + openTask(task, { focus: focus !== false }); + } }, }, { @@ -396,6 +401,8 @@ export const taskActions: Action[] = [ title: "Delete Agent Tasks", category: "Agents", hidden: true, + // Without an argument the shortcut deletes the task list's selection. + keyWhen: "agentTaskListFocus", run: ({ arg }) => confirmDelete(resolveTasks(arg)), }, { diff --git a/src/platform/keymaps/intellij-macos.ts b/src/platform/keymaps/intellij-macos.ts index 8a85ab86ec..981510c72b 100644 --- a/src/platform/keymaps/intellij-macos.ts +++ b/src/platform/keymaps/intellij-macos.ts @@ -495,6 +495,7 @@ export const intellijMacos: Record = { "agents.sendToAgent": [], // Agents task list (when it has focus) "agents.archiveTasks": ["Meta+Shift+E"], + "agents.deleteTasks": ["Delete", "Meta+Backspace"], // Database tool window (when the tree has focus; `db.openConsole` anywhere). "db.openConsole": ["Meta+Shift+L"], "db.newDataSource": [], diff --git a/src/platform/keymaps/intellij-windows.ts b/src/platform/keymaps/intellij-windows.ts index 1c251e4ec3..a9c4f02b66 100644 --- a/src/platform/keymaps/intellij-windows.ts +++ b/src/platform/keymaps/intellij-windows.ts @@ -493,6 +493,7 @@ export const intellijWindows: Record = { "agents.sendToAgent": [], // Agents task list (when it has focus) "agents.archiveTasks": ["Ctrl+Shift+E"], + "agents.deleteTasks": ["Delete"], // Database tool window (when the tree has focus; `db.openConsole` anywhere). "db.openConsole": ["Ctrl+Shift+Q"], "db.newDataSource": [], diff --git a/src/platform/keymaps/vscode-macos.ts b/src/platform/keymaps/vscode-macos.ts index d57d6a1d20..cabe47ee6a 100644 --- a/src/platform/keymaps/vscode-macos.ts +++ b/src/platform/keymaps/vscode-macos.ts @@ -528,6 +528,7 @@ export const vscodeMacos: Record = { "agents.sendToAgent": [], // Agents task list (when it has focus) "agents.archiveTasks": ["Meta+Shift+E"], + "agents.deleteTasks": ["Meta+Backspace"], // Python Console: VS Code's Shift+Enter would shadow typing in Python files, so unbound. "python.console.executeSelection": [], // Search fields (find bar, Find in Files): last, so they win over editor keys while one is focused. diff --git a/src/platform/keymaps/vscode-windows.ts b/src/platform/keymaps/vscode-windows.ts index a73bda3a8f..0b9c49e505 100644 --- a/src/platform/keymaps/vscode-windows.ts +++ b/src/platform/keymaps/vscode-windows.ts @@ -45,6 +45,7 @@ export const vscodeWindows: Record = { "project.rename": ["F2"], "project.delete": ["Delete"], "db.drop": ["Delete"], + "agents.deleteTasks": ["Delete"], "project.copyAbsolutePath": ["Alt+Shift+C"], "project.open": [], "project.openInRightSplit": ["Ctrl+Enter"], diff --git a/src/ui/Tree.tsx b/src/ui/Tree.tsx index bdaf5b22c2..b589434a8e 100644 --- a/src/ui/Tree.tsx +++ b/src/ui/Tree.tsx @@ -749,7 +749,17 @@ export function Tree(props: TreeProps) { endSearch(); if (e.shiftKey) selectIndex(i, "range"); else if (e.metaKey || e.ctrlKey) selectIndex(i, "toggle"); - else selectIndex(i); + else if (multiSelect && selected.size > 1 && selected.has(rows[i]!.key)) { + // Pressing a row of a multi-selection keeps the selection so a drag carries all of it; + // a release without moving (a plain click) narrows it to the row. + const x0 = e.clientX; + const y0 = e.clientY; + const up = (u: globalThis.MouseEvent) => { + window.removeEventListener("mouseup", up, true); + if (Math.abs(u.clientX - x0) < 4 && Math.abs(u.clientY - y0) < 4) selectIndex(i); + }; + window.addEventListener("mouseup", up, true); + } else selectIndex(i); }; const leadRow = leadIndex >= 0 ? rows[leadIndex] : undefined; From f47a83828cbd514878920e338365ccda20760f1a Mon Sep 17 00:00:00 2001 From: Muu Date: Mon, 30 Nov 2026 19:58:05 +0800 Subject: [PATCH 12/46] feat(structure): temporarily enable filters to find matches (#6934) With Narrow down on typing on, a File Structure query that matches nothing now turns on the unchecked filters (Show fields, Show non-public, Show inherited members) one at a time until a match appears. Filters enabled this way are restored as the query gets shorter and when the popup closes, and are never saved; a checkbox the user changes by hand keeps its new state, and the cascade stops right after a backspace restores a filter. Co-authored-by: muutot <92625353+muutot@users.noreply.github.com> --- e2e/fileStructureLayout.spec.ts | 87 ++++++++++ .../search/__tests__/fileStructure.test.tsx | 151 +++++++++++++++++- .../search/structure/StructureView.tsx | 111 +++++++++++-- src/features/search/structure/store.ts | 41 ++++- 4 files changed, 369 insertions(+), 21 deletions(-) diff --git a/e2e/fileStructureLayout.spec.ts b/e2e/fileStructureLayout.spec.ts index b9cb4828b9..ca649b2030 100644 --- a/e2e/fileStructureLayout.spec.ts +++ b/e2e/fileStructureLayout.spec.ts @@ -202,6 +202,93 @@ test("File Structure prefers matches inside the caret symbol", async ({ workbenc await expect(tree.getByRole("treeitem", { name: "load", exact: true })).toHaveAttribute("aria-selected", "false"); }); +test("File Structure auto-enables temporary filters without saving them", async ({ workbench: page }) => { + await openFromTree(page, "build.gradle.kts"); + await stubDesktop(page); + await page.evaluate(async () => { + const optionsPath = "/src/features/search/structure/store.ts"; + const { useStructureOptions } = await import(/* @vite-ignore */ optionsPath); + useStructureOptions.setState({ showFields: false, showNonPublic: false, showInherited: false, narrowDown: true }); + const range = { start: { line: 0, col: 0 }, end: { line: 1, col: 1 } }; + const symbol = (name: string, kind: string, visibility?: string) => ({ + name, + kind, + visibility, + range, + selection_range: range, + children: [], + }); + window.__ipc.handlers.doc_outline = () => [ + { + ...symbol("Container", "class"), + children: [ + symbol("hiddenField", "field"), + symbol("hiddenMethod", "method", "private"), + symbol("visible", "method"), + ], + }, + ]; + window.__ipc.handlers.lsp_type_hierarchy = () => []; + const actionsPath = "/src/platform/actions.ts"; + const { executeAction } = await import(/* @vite-ignore */ actionsPath); + await executeAction("navigate.fileStructure"); + }); + + const dialog = page.getByRole("dialog", { name: "File Structure" }); + const filter = dialog.getByRole("textbox", { name: "Filter symbols" }); + const tree = dialog.getByRole("tree", { name: "Symbols" }); + const fields = dialog.getByRole("checkbox", { name: "Show fields" }); + const nonPublic = dialog.getByRole("checkbox", { name: "Show non-public" }); + const readOptions = () => + page.evaluate(async () => { + const path = "/src/features/search/structure/store.ts"; + const { useStructureOptions } = await import(/* @vite-ignore */ path); + const { showFields, showNonPublic, showInherited } = useStructureOptions.getState(); + return { showFields, showNonPublic, showInherited }; + }); + + await expect(fields).not.toBeChecked(); + await expect(nonPublic).not.toBeChecked(); + await filter.fill("hiddenField"); + await expect(fields).toBeChecked(); + await expect(nonPublic).not.toBeChecked(); + await expect(tree.getByRole("treeitem", { name: "hiddenField", selected: true })).toBeVisible(); + expect(await readOptions()).toEqual({ showFields: false, showNonPublic: false, showInherited: false }); + + await nonPublic.check(); + expect(await readOptions()).toEqual({ showFields: false, showNonPublic: true, showInherited: false }); + const saved = await page.evaluate(() => localStorage.getItem("openidea.structure.options.v1")); + await filter.press("End"); + await filter.press("Backspace"); + await expect(filter).toHaveValue("hiddenFiel"); + await expect(fields).not.toBeChecked(); + await expect(nonPublic).toBeChecked(); + await expect(tree.getByRole("treeitem", { name: "hiddenField", exact: true })).toBeHidden(); + expect(await readOptions()).toEqual({ showFields: false, showNonPublic: true, showInherited: false }); + + await filter.fill("hiddenField"); + await expect(fields).toBeChecked(); + await fields.uncheck(); + await expect(fields).not.toBeChecked(); + await filter.press("Escape"); + await expect(filter).toHaveValue(""); + await expect(fields).not.toBeChecked(); + await filter.press("Escape"); + await expect(dialog).toBeHidden(); + expect(await readOptions()).toEqual({ showFields: false, showNonPublic: true, showInherited: false }); + expect(await page.evaluate(() => localStorage.getItem("openidea.structure.options.v1"))).toBe(saved); + + await page.evaluate(async () => { + const path = "/src/platform/actions.ts"; + const { executeAction } = await import(/* @vite-ignore */ path); + await executeAction("navigate.fileStructure"); + }); + await expect(dialog).toBeVisible(); + await expect(dialog.getByRole("checkbox", { name: "Show fields" })).not.toBeChecked(); + await expect(dialog.getByRole("checkbox", { name: "Show non-public" })).toBeChecked(); + expect(await page.evaluate(() => localStorage.getItem("openidea.structure.options.v1"))).toBe(saved); +}); + test("F4 jumps to the filtered File Structure symbol", async ({ workbench: page }) => { await openFromTree(page, "build.gradle.kts"); await stubDesktop(page); diff --git a/src/features/search/__tests__/fileStructure.test.tsx b/src/features/search/__tests__/fileStructure.test.tsx index 6580b2634f..d65355b405 100644 --- a/src/features/search/__tests__/fileStructure.test.tsx +++ b/src/features/search/__tests__/fileStructure.test.tsx @@ -1,4 +1,4 @@ -import { afterEach, describe, expect, it, vi } from "vitest"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { act, fireEvent, render, screen, waitFor } from "@testing-library/react"; import type { OutlineItem } from "@/platform/ipc"; @@ -16,10 +16,17 @@ const { FileStructureOverlay, useFileStructurePopup } = await import("../structu const { useOutline, useStructureOptions } = await import("../structure/store"); const { useTracking } = await import("../common/tracking"); -const item = (name: string, kind: OutlineItem["kind"], line: number, children: OutlineItem[] = []): OutlineItem => ({ +const item = ( + name: string, + kind: OutlineItem["kind"], + line: number, + children: OutlineItem[] = [], + visibility?: OutlineItem["visibility"], +): OutlineItem => ({ name, detail: null, kind, + visibility, range: { start: { line, col: 0 }, end: { line: line + 1, col: 1 } }, selection_range: { start: { line, col: 4 }, end: { line, col: 4 + name.length } }, children, @@ -61,6 +68,19 @@ function openFunctions(narrowDown: boolean) { return input; } +beforeEach(() => { + useStructureOptions.setState({ + alphabetical: false, + narrowDown: true, + showFields: true, + showNonPublic: true, + showInherited: false, + sortByVisibility: false, + showOnlyWidgets: false, + }); + useOutline.setState({ inheritedSupported: false, inherited: null, flutter: null }); +}); + afterEach(() => { act(() => useFileStructurePopup.setState({ open: false })); useTracking.setState({ caret: null }); @@ -186,6 +206,133 @@ describe("File Structure popup", () => { expect(useFileStructurePopup.getState().open).toBe(false); }); + describe("temporary filters", () => { + const filteredItems = () => [ + item("Container", "class", 0, [ + item("hiddenField", "field", 2), + item("hiddenMethod", "method", 4, [], "private"), + item("visible", "method", 6), + ]), + ]; + + it("auto-enables only the applicable filter needed for a match, without persisting it", () => { + useStructureOptions.setState({ showFields: false, showNonPublic: false }); + const saved = localStorage.getItem("openidea.structure.options.v1"); + const input = open(filteredItems()); + const fields = screen.getByRole("checkbox", { name: "Show fields" }); + const nonPublic = screen.getByRole("checkbox", { name: "Show non-public" }); + expect(fields).not.toBeChecked(); + expect(nonPublic).not.toBeChecked(); + + fireEvent.change(input, { target: { value: "hiddenField" } }); + expect(fields).toBeChecked(); + expect(nonPublic).not.toBeChecked(); + expect(screen.getByRole("treeitem", { name: "hiddenField", selected: true })).toBeVisible(); + expect(useStructureOptions.getState()).toMatchObject({ showFields: false, showNonPublic: false }); + expect(localStorage.getItem("openidea.structure.options.v1")).toBe(saved); + + fireEvent.keyDown(input, { key: "Escape" }); + expect(fields).not.toBeChecked(); + fireEvent.keyDown(input, { key: "Escape" }); + expect(useFileStructurePopup.getState().open).toBe(false); + act(() => useFileStructurePopup.setState({ open: true })); + expect(screen.getByLabelText("Filter symbols")).toHaveValue(""); + expect(screen.getByRole("checkbox", { name: "Show fields" })).not.toBeChecked(); + expect(useStructureOptions.getState().showFields).toBe(false); + }); + + it("tries unchecked filters one at a time until a match appears, then restores all on Escape", () => { + useStructureOptions.setState({ showFields: false, showNonPublic: false }); + const input = open(filteredItems()); + const fields = screen.getByRole("checkbox", { name: "Show fields" }); + const nonPublic = screen.getByRole("checkbox", { name: "Show non-public" }); + + fireEvent.change(input, { target: { value: "hiddenMethod" } }); + expect(fields).toBeChecked(); + expect(nonPublic).toBeChecked(); + expect(screen.getByRole("treeitem", { name: "hiddenMethod", selected: true })).toBeVisible(); + expect(useStructureOptions.getState()).toMatchObject({ showFields: false, showNonPublic: false }); + + fireEvent.keyDown(input, { key: "Escape" }); + expect(input).toHaveValue(""); + expect(fields).not.toBeChecked(); + expect(nonPublic).not.toBeChecked(); + expect(screen.getByRole("treeitem", { name: "visible" })).toBeVisible(); + }); + + it("does not immediately re-enable a restored filter after backspace", () => { + useStructureOptions.setState({ showFields: false, showNonPublic: false }); + const input = open(filteredItems()); + const fields = screen.getByRole("checkbox", { name: "Show fields" }); + fireEvent.change(input, { target: { value: "hiddenField" } }); + expect(fields).toBeChecked(); + + fireEvent.change(input, { target: { value: "hiddenFiel" } }); + expect(fields).not.toBeChecked(); + expect(screen.getByText("No symbols")).toBeInTheDocument(); + expect(useStructureOptions.getState().showFields).toBe(false); + }); + + it("does not auto-enable filters when Narrow down on typing is off", () => { + useStructureOptions.setState({ showFields: false, showNonPublic: false }); + const input = open(filteredItems()); + act(() => useStructureOptions.setState({ narrowDown: false })); + const fields = screen.getByRole("checkbox", { name: "Show fields" }); + const nonPublic = screen.getByRole("checkbox", { name: "Show non-public" }); + + fireEvent.change(input, { target: { value: "hiddenField" } }); + expect(fields).not.toBeChecked(); + expect(nonPublic).not.toBeChecked(); + expect(screen.queryByRole("treeitem", { name: "hiddenField" })).toBeNull(); + expect(useStructureOptions.getState()).toMatchObject({ showFields: false, showNonPublic: false }); + }); + + it("restores an auto-enabled filter on backspace without reverting a manual checkbox change", () => { + useStructureOptions.setState({ showFields: false, showNonPublic: false }); + const input = open(filteredItems()); + const fields = screen.getByRole("checkbox", { name: "Show fields" }); + const nonPublic = screen.getByRole("checkbox", { name: "Show non-public" }); + fireEvent.change(input, { target: { value: "hiddenField" } }); + expect(fields).toBeChecked(); + + fireEvent.click(nonPublic); + expect(useStructureOptions.getState().showNonPublic).toBe(true); + fireEvent.change(input, { target: { value: "hiddenFielX" } }); + expect(fields).toBeChecked(); // Same-length edits do not trigger IDEA's backspace restore. + fireEvent.change(input, { target: { value: "visible" } }); + expect(fields).not.toBeChecked(); + expect(nonPublic).toBeChecked(); + expect(screen.getByRole("treeitem", { name: "visible", selected: true })).toBeVisible(); + expect(screen.queryByRole("treeitem", { name: "hiddenField" })).toBeNull(); + expect(useStructureOptions.getState()).toMatchObject({ showFields: false, showNonPublic: true }); + + fireEvent.keyDown(input, { key: "Escape" }); + fireEvent.keyDown(input, { key: "Escape" }); + act(() => useFileStructurePopup.setState({ open: true })); + expect(screen.getByRole("checkbox", { name: "Show fields" })).not.toBeChecked(); + expect(screen.getByRole("checkbox", { name: "Show non-public" })).toBeChecked(); + }); + + it("temporarily enables Show inherited members and restores it when the query gets shorter", () => { + const input = open([item("Container", "class", 0, [item("own", "method", 2)])]); + const inherited = [{ item: item("inheritedNeedle", "method", 40), path: "/lib/Base.kt", owner: "Base" }]; + act(() => useOutline.setState({ inheritedSupported: true, inherited: new Map([["0:4", inherited]]) })); + const checkbox = screen.getByRole("checkbox", { name: "Show inherited members" }); + expect(checkbox).not.toBeChecked(); + + fireEvent.change(input, { target: { value: "inheritedNeedle" } }); + expect(checkbox).toBeChecked(); + expect(screen.getByRole("treeitem", { name: /^inheritedNeedle/, selected: true })).toBeVisible(); + expect(useStructureOptions.getState().showInherited).toBe(false); + + fireEvent.change(input, { target: { value: "own" } }); + expect(checkbox).not.toBeChecked(); + expect(screen.getByRole("treeitem", { name: "own", selected: true })).toBeVisible(); + expect(screen.queryByRole("treeitem", { name: /^inheritedNeedle/ })).toBeNull(); + expect(useStructureOptions.getState().showInherited).toBe(false); + }); + }); + it("offers Show inherited members only when the server knows type hierarchies", () => { open(); expect(screen.queryByLabelText("Show inherited members")).toBeNull(); diff --git a/src/features/search/structure/StructureView.tsx b/src/features/search/structure/StructureView.tsx index d8a660e72b..9b9a8e8232 100644 --- a/src/features/search/structure/StructureView.tsx +++ b/src/features/search/structure/StructureView.tsx @@ -33,7 +33,16 @@ import { widgetLetter, type OutlineNode, } from "./outline"; -import { useCollapsedStructure, useLiveOutline, useOutline, useOutlineNodes, useStructureOptions } from "./store"; +import { + getOutlineNodes, + releaseInheritedMembers, + requestInheritedMembers, + useCollapsedStructure, + useLiveOutline, + useOutline, + useOutlineNodes, + useStructureOptions, +} from "./store"; import styles from "./StructureView.module.css"; import { tx } from "@/platform/i18n"; @@ -301,8 +310,30 @@ export function FileStructureOverlay() { const POPUP_ROW = 22; +type TemporaryFilter = "showFields" | "showNonPublic" | "showInherited"; +interface AutoFilter { + key: TemporaryFilter; + queryLength: number; +} +interface PopupFilters { + showFields: boolean; + showNonPublic: boolean; + showInherited: boolean; +} +const TEMPORARY_FILTERS: readonly TemporaryFilter[] = ["showFields", "showNonPublic", "showInherited"]; + +function effectivePopupFilters(options: PopupFilters, autoFilters: readonly AutoFilter[]): PopupFilters { + const enabled = (key: TemporaryFilter) => autoFilters.some((entry) => entry.key === key); + return { + showFields: options.showFields || enabled("showFields"), + showNonPublic: options.showNonPublic || enabled("showNonPublic"), + showInherited: options.showInherited || enabled("showInherited"), + }; +} + function FileStructureDialog() { useLiveOutline(); + useEffect(() => () => releaseInheritedMembers(), []); const rowHeight = useRowHeight(POPUP_ROW); const path = useOutline((s) => s.path); const items = useOutline((s) => s.items); @@ -313,8 +344,13 @@ function FileStructureDialog() { const showNonPublic = useStructureOptions((s) => s.showNonPublic); const showInherited = useStructureOptions((s) => s.showInherited); const inheritedSupported = useOutline((s) => s.inheritedSupported); - const nodes = useOutlineNodes(); const [query, setQuery] = useState(""); + const [autoFilters, setAutoFilters] = useState([]); + const effectiveOptions = useMemo( + () => effectivePopupFilters({ showFields, showNonPublic, showInherited }, autoFilters), + [showFields, showNonPublic, showInherited, autoFilters], + ); + const nodes = useOutlineNodes(false, effectiveOptions); const [showOptions, setShowOptions] = useState(false); // IDEA opens the popup fully expanded. const [collapsed, setCollapsed] = useState>(() => new Set()); @@ -351,7 +387,10 @@ function FileStructureDialog() { else tree.current?.clearSelection(); }, [query, hasQuery, caretKey, filter.preferred, filter.nodes]); - const close = () => useFileStructurePopup.setState({ open: false }); + const close = () => { + releaseInheritedMembers(); + useFileStructurePopup.setState({ open: false }); + }; const choose = (node: OutlineNode | undefined) => { if (!node || !path) return; close(); @@ -365,6 +404,53 @@ function FileStructureDialog() { return next; }); + const availableFilters: Record = { + showFields: hasFields(items ?? []), + showNonPublic: hasVisibility(items ?? []), + showInherited: inheritedSupported, + }; + const changeQuery = (nextQuery: string) => { + setQuery(nextQuery); + setCollapsed(new Set()); + let nextAuto = autoFilters; + if (nextQuery.length < query.length) { + // IDEA restores every auto-click whose query was at least this long, newest first. + nextAuto = autoFilters.filter((entry) => entry.queryLength < nextQuery.length); + if (nextAuto.length !== autoFilters.length) { + if ( + autoFilters.some((entry) => entry.key === "showInherited") && + !nextAuto.some((entry) => entry.key === "showInherited") + ) + releaseInheritedMembers(); + setAutoFilters(nextAuto); + return; + } + } + if (!nextQuery.trim() || !narrowDown) { + setAutoFilters(nextAuto); + return; + } + const persisted = useStructureOptions.getState(); + let options = effectivePopupFilters(persisted, nextAuto); + const hasMatch = () => filterOutline(getOutlineNodes(false, options), nextQuery, narrowDown).best !== null; + if (!hasMatch()) { + for (const key of TEMPORARY_FILTERS) { + if (options[key] || !availableFilters[key]) continue; + nextAuto = [{ key, queryLength: nextQuery.length }, ...nextAuto]; + options = effectivePopupFilters(persisted, nextAuto); + if (key === "showInherited") requestInheritedMembers(); + if (hasMatch()) break; + } + } + setAutoFilters(nextAuto); + }; + const changeFilter = (key: TemporaryFilter, value: boolean) => { + // A manual edit takes ownership of the checkbox; later backspaces must not undo it. + setAutoFilters((entries) => entries.filter((entry) => entry.key !== key)); + if (key === "showInherited") releaseInheritedMembers(); + useStructureOptions.setState({ [key]: value }); + }; + const onKeyDown = (e: KeyboardEvent) => { const lead = tree.current?.leadKey() ?? null; const node = lead ? byKey.get(lead) : undefined; @@ -377,7 +463,7 @@ function FileStructureDialog() { // The first Esc clears the filter, the next one closes the popup. if (!query) return; e.stopPropagation(); - setQuery(""); + changeQuery(""); break; case "ArrowDown": case "ArrowUp": { @@ -437,22 +523,22 @@ function FileStructureDialog() { {(hasFields(items ?? []) || !showFields) && ( useStructureOptions.setState({ showFields: v })} + checked={effectiveOptions.showFields} + onChange={(v) => changeFilter("showFields", v)} /> )} {hasVisibility(items ?? []) && ( useStructureOptions.setState({ showNonPublic: v })} + checked={effectiveOptions.showNonPublic} + onChange={(v) => changeFilter("showNonPublic", v)} /> )} {inheritedSupported && ( useStructureOptions.setState({ showInherited: v })} + checked={effectiveOptions.showInherited} + onChange={(v) => changeFilter("showInherited", v)} /> )}
@@ -496,10 +582,7 @@ function FileStructureDialog() { aria-label={tx("Filter symbols")} spellCheck={false} autoComplete="off" - onChange={(e) => { - setQuery(e.target.value); - setCollapsed(new Set()); - }} + onChange={(e) => changeQuery(e.target.value)} onKeyDown={onKeyDown} /> {hasQuery && !narrowDown && !filter.best && filter.nodes.length > 0 && ( diff --git a/src/features/search/structure/store.ts b/src/features/search/structure/store.ts index 44a7a93a7b..62a9d56b8b 100644 --- a/src/features/search/structure/store.ts +++ b/src/features/search/structure/store.ts @@ -47,6 +47,8 @@ let consumers = 0; let stop: (() => void) | null = null; let seq = 0; let flutterSeq = 0; +let reloadOutline: (() => void) | null = null; +let inheritedRequest: { doc: number; path: string } | null = null; /** A backend document id for `path` while `fn` runs (open editors are reused). */ async function withDoc(path: string, fn: (doc: number) => Promise): Promise { @@ -99,16 +101,31 @@ async function loadInherited(doc: number, path: string, items: readonly OutlineI ? true : await probeHierarchy(doc, types); if (my !== seq) return; - if (!supported || !useStructureOptions.getState().showInherited) { + const requested = inheritedRequest?.doc === doc && inheritedRequest.path === path; + if (!supported || !(useStructureOptions.getState().showInherited || requested)) { + if (requested) inheritedRequest = null; useOutline.setState({ inheritedSupported: supported, inherited: null }); return; } + useOutline.setState({ inheritedSupported: true }); const deps = inheritedDeps(path, doc, language === "python"); const entries = await Promise.all( types.map(async (t) => [typeKey(t), await inheritedMembers(path, t, deps).catch(() => [])] as const), ); - if (my === seq) - useOutline.setState({ inheritedSupported: true, inherited: new Map(entries.filter(([, m]) => m.length)) }); + if (my === seq) useOutline.setState({ inherited: new Map(entries.filter(([, m]) => m.length)) }); +} + +/** Loads inherited members for a temporary popup filter without changing persisted options. */ +export function requestInheritedMembers() { + const { doc, path, inherited } = useOutline.getState(); + if (doc === null || path === null) return; + inheritedRequest = { doc, path }; + if (inherited === null) reloadOutline?.(); +} + +/** Ends a popup's temporary inherited-member request when its filter is restored or it closes. */ +export function releaseInheritedMembers() { + inheritedRequest = null; } async function loadFlutter(doc: number, language: string) { @@ -153,6 +170,7 @@ function start(): () => void { if (!ctx) { seq++; flutterSeq++; + inheritedRequest = null; useOutline.setState({ path: null, doc: null, @@ -167,6 +185,7 @@ function start(): () => void { } void load(ctx.doc, ctx.path, ctx.language); }; + reloadOutline = reloadNow; reloadNow(); const unsubActive = useEditorRegistry.subscribe((s, prev) => { if (s.active?.ctx.doc !== prev.active?.ctx.doc || s.active?.ctx.path !== prev.active?.ctx.path) reloadNow(); @@ -188,6 +207,8 @@ function start(): () => void { return () => { clearTimeout(timer); flutterSeq++; + if (reloadOutline === reloadNow) reloadOutline = null; + inheritedRequest = null; unsubFlutter(); unsubActive(); unsubInherited(); @@ -268,6 +289,8 @@ const outlinePreferences = (s: StructureOptions) => ({ showOnlyWidgets: s.showOnlyWidgets, }); +type OutlinePreferences = ReturnType; + function outlineNodes( items: OutlineState["items"], flutter: OutlineState["flutter"], @@ -285,12 +308,20 @@ function outlineNodes( return flutter && options.showOnlyWidgets ? onlyWidgets(nodes) : nodes; } -export function useOutlineNodes(widgets = false) { +/** Snapshot builder for query-event transitions, which cannot call hooks. */ +export function getOutlineNodes(widgets = false, overrides?: Partial) { + const { items, flutter, inheritedSupported, inherited } = useOutline.getState(); + const options = { ...outlinePreferences(useStructureOptions.getState()), ...overrides }; + return outlineNodes(items, widgets ? flutter : null, inheritedSupported ? inherited : null, options); +} + +export function useOutlineNodes(widgets = false, overrides?: Partial) { const items = useOutline((s) => s.items); const flutter = useOutline((s) => (widgets ? s.flutter : null)); const inherited = useOutline((s) => (s.inheritedSupported ? s.inherited : null)); const options = useStructureOptions(useShallow(outlinePreferences)); - return useMemo(() => outlineNodes(items, flutter, inherited, options), [items, flutter, inherited, options]); + const effective = useMemo(() => (overrides ? { ...options, ...overrides } : options), [options, overrides]); + return useMemo(() => outlineNodes(items, flutter, inherited, effective), [items, flutter, inherited, effective]); } function collapseStructure() { From 2b7a18ffd7f2fce5c21107143ff9113b78915f74 Mon Sep 17 00:00:00 2001 From: l0ng-ai Date: Mon, 30 Nov 2026 20:04:14 +0800 Subject: [PATCH 13/46] fix(search): start Find in Files from the selection in its preview (#7033) Find in Files and Search Everywhere took the selection only from the active editor tab, so text selected in the Find in Files preview (or another focused editor, such as a diff pane) was ignored when the action ran again. The focused editor's selection now comes first, then the active editor's. Fixes #6992 --- .../search/__tests__/selectionText.test.ts | 30 +++++++++++++++++++ src/features/search/index.ts | 10 +++++-- 2 files changed, 38 insertions(+), 2 deletions(-) create mode 100644 src/features/search/__tests__/selectionText.test.ts diff --git a/src/features/search/__tests__/selectionText.test.ts b/src/features/search/__tests__/selectionText.test.ts new file mode 100644 index 0000000000..2384e1096a --- /dev/null +++ b/src/features/search/__tests__/selectionText.test.ts @@ -0,0 +1,30 @@ +import { afterEach, expect, it } from "vitest"; +import { EditorSelection, EditorState } from "@codemirror/state"; +import { EditorView } from "@codemirror/view"; +import { _setActiveEditor, type TextEditorHandle } from "@/editor/api"; +import { editorSelectionText } from "../index"; + +const views: EditorView[] = []; +const view = (doc: string, from: number, to: number) => { + const v = new EditorView({ + state: EditorState.create({ doc, selection: EditorSelection.single(from, to) }), + parent: document.body, + }); + views.push(v); + return v; +}; +afterEach(() => { + _setActiveEditor(null); + views.splice(0).forEach((v) => v.destroy()); +}); + +it("takes the selection of the focused editor, such as the Find in Files preview, over the active one", () => { + const main = view("val first = 1", 4, 9); + _setActiveEditor({ view: main } as unknown as TextEditorHandle); + expect(editorSelectionText()).toBe("first"); + const preview = view("fun second() {}", 4, 10); + preview.contentDOM.focus(); + expect(editorSelectionText()).toBe("second"); + preview.contentDOM.blur(); + expect(editorSelectionText()).toBe("first"); +}); diff --git a/src/features/search/index.ts b/src/features/search/index.ts index 4d615d2345..a1b378fc4a 100644 --- a/src/features/search/index.ts +++ b/src/features/search/index.ts @@ -3,6 +3,7 @@ * Recent Files / Recent Locations, Find / Replace in Files + the Find tool * window, the Structure tool window + File Structure popup, and bookmarks. */ +import { EditorView } from "@codemirror/view"; import { lazyComponent, lazyWhen } from "@/ui"; import { activeEditor, focusedCellEditor, registerEditorContribution } from "@/editor/api"; import { executeAction, registerActions } from "@/platform/actions"; @@ -82,8 +83,13 @@ async function removeMissingBookmarks(removed: readonly string[]) { } /** Single-line editor selection, used to prefill search fields. */ -function editorSelectionText(): string | null { - const view = activeEditor()?.view; +/** + * The single-line selection a search starts from: the focused editor's (a Find in Files preview, + * a diff pane), else the active editor's, as IDEA reads it from the editor in the action's context. + */ +export function editorSelectionText(): string | null { + const focused = document.activeElement?.closest(".cm-editor"); + const view = (focused instanceof HTMLElement ? EditorView.findFromDOM(focused) : null) ?? activeEditor()?.view; if (!view) return null; const { from, to } = view.state.selection.main; if (from === to || to - from > 200) return null; From baab92c804f6f8b41edd857d5f1037cde7474eff Mon Sep 17 00:00:00 2001 From: Muu Date: Mon, 30 Nov 2026 20:08:11 +0800 Subject: [PATCH 14/46] feat(vcs): create patches from selected historical files (#6981) Git Log and File History changed files get Create Patch and Copy as Patch to Clipboard, in the toolbar and the context menu. Only the selected repository-relative paths are exported, as path-filtered revision diffs with Git's empty tree on the missing side of additions and deletions and both names for renames. The existing patch dialog, base directory defaults, reverse option and clipboard flow are reused; empty, malformed, no-op, mixed-repository and external-repository selections are disabled. Co-authored-by: muutot <92625353+muutot@users.noreply.github.com> --- e2e/fileHistoryActions.spec.ts | 113 +++++++++++++++++ src/features/vcs/__tests__/historyOps.test.ts | 7 ++ src/features/vcs/__tests__/logPanes.test.tsx | 83 ++++++++++++ src/features/vcs/__tests__/logPatch.test.ts | 118 ++++++++++++++++++ src/features/vcs/log/CommitDetails.tsx | 30 +++++ src/features/vcs/logChanges.ts | 62 ++++++++- src/features/vcs/logPaneActions.ts | 24 ++++ src/features/vcs/patches.tsx | 54 +++++++- src/platform/keymaps/ideaParity.test.ts | 2 + src/platform/keymaps/intellij-macos.ts | 2 + src/platform/keymaps/intellij-windows.ts | 2 + src/platform/keymaps/vscode-macos.ts | 2 + 12 files changed, 493 insertions(+), 6 deletions(-) create mode 100644 src/features/vcs/__tests__/logPatch.test.ts diff --git a/e2e/fileHistoryActions.spec.ts b/e2e/fileHistoryActions.spec.ts index e9bc56660a..bcf3374c7f 100644 --- a/e2e/fileHistoryActions.spec.ts +++ b/e2e/fileHistoryActions.spec.ts @@ -99,3 +99,116 @@ test("File History opens its revision and compares only that file with the worki .poll(async () => ipcCalls(page, "vcs_file_at")) .toContainEqual({ path: `${ROOT}/src/old-name.ts`, rev: REVISION }); }); + +test("File History creates and copies a patch for only the selected changed file", async ({ workbench: page }) => { + const parent = "b".repeat(40); + const selectedPath = "src/selected.ts"; + const otherPath = "src/other.ts"; + const patch = `diff --git a/${selectedPath} b/${selectedPath}\n`; + await stubDesktop(page); + await page.evaluate( + async ({ root, path, revision, parent, selectedPath, otherPath }) => { + const h = window.__ipc.handlers; + h.vcs_roots = () => [{ root, head: "main", headCommit: revision, operation: null }]; + h.vcs_branch_info = () => ({ + head: "main", + headCommit: revision, + upstream: null, + ahead: 0, + behind: 0, + operation: null, + }); + h.vcs_branches = () => []; + h.vcs_status = () => []; + h.vcs_log = ({ query }) => + (query as { path?: string }).path + ? [ + { + id: revision, + shortId: revision.slice(0, 8), + parents: [parent], + refs: [], + author: "Author", + email: "author@example.com", + timeMs: 1, + summary: "Export selected history file", + message: "Export selected history file", + historyPath: selectedPath, + }, + ] + : []; + h.vcs_log_refs = () => ({}); + h.vcs_log_users = () => ["Author "]; + h.vcs_log_details_batch = () => []; + h.vcs_commit_files = () => [ + { path: selectedPath, kind: "modified", oldPath: null }, + { path: otherPath, kind: "modified", oldPath: null }, + ]; + h.vcs_create_patch = ({ source }) => { + const paths = (source as { paths?: string[] }).paths ?? []; + return paths.map((entry) => `diff --git a/${entry} b/${entry}\n`).join(""); + }; + h.vcs_write_patch = () => null; + h.clipboard_write_text = () => null; + + const projectModule = "/src/platform/project.ts"; + const { useProject } = await import(/* @vite-ignore */ projectModule); + useProject.setState((state: { settings: Record }) => ({ + settings: { + ...state.settings, + vcs: { confirmation: { onPatchCreated: "no" } }, + }, + })); + const storeModule = "/src/features/vcs/store.ts"; + const { useVcs } = await import(/* @vite-ignore */ storeModule); + useVcs.setState({ available: true, root, repo: root, roots: [root], branchesLoaded: true, statusLoaded: true }); + const contextModule = "/src/platform/context.ts"; + const { setContext } = await import(/* @vite-ignore */ contextModule); + setContext("vcsAvailable", true); + const actionsModule = "/src/platform/actions.ts"; + const { executeAction } = await import(/* @vite-ignore */ actionsModule); + await executeAction("vcs.showHistory", { path }); + }, + { root: ROOT, path: `${ROOT}/${selectedPath}`, revision: REVISION, parent, selectedPath, otherPath }, + ); + + const row = page.getByRole("listbox", { name: "Commits" }).getByRole("option", { + name: /Export selected history file/, + }); + await expect(row).toBeVisible(); + await row.click(); + const tree = page.getByRole("tree", { name: "Changed files" }); + const selected = tree.getByText("selected.ts", { exact: true }); + await expect(selected).toBeVisible(); + await expect(tree.getByText("other.ts", { exact: true })).toBeVisible(); + const toolbar = page.getByRole("toolbar", { name: "Changed files" }); + const create = toolbar.getByRole("button", { name: "Create Patch…", exact: true }); + await expect(create).toBeDisabled(); + await selected.click(); + await expect(create).toBeEnabled(); + await create.click(); + + const dialog = page.getByRole("dialog", { name: "Create Patch", exact: true }); + await expect(dialog.getByRole("textbox", { name: "Base directory" })).toHaveValue(ROOT); + const destination = await dialog.getByRole("textbox", { name: "Patch file" }).inputValue(); + expect(destination).toBe(`${ROOT}/Export_selected_history_file.patch`); + await dialog.getByRole("button", { name: "Create", exact: true }).click(); + const source = { from: "revisions", before: parent, after: REVISION, paths: [selectedPath] }; + await expect.poll(() => ipcCalls(page, "vcs_create_patch")).toEqual([{ repo: ROOT, base: ROOT, source }]); + await expect + .poll(() => ipcCalls(page, "vcs_write_patch")) + .toEqual([expect.objectContaining({ path: destination, patch })]); + + await selected.click({ button: "right" }); + await page + .getByRole("menu", { name: "Context menu" }) + .getByRole("menuitem", { name: "Copy as Patch to Clipboard", exact: true }) + .click(); + await expect.poll(() => ipcCalls(page, "clipboard_write_text")).toEqual([{ text: patch }]); + await expect + .poll(() => ipcCalls(page, "vcs_create_patch")) + .toEqual([ + { repo: ROOT, base: ROOT, source }, + { repo: ROOT, base: null, source }, + ]); +}); diff --git a/src/features/vcs/__tests__/historyOps.test.ts b/src/features/vcs/__tests__/historyOps.test.ts index 2998cced93..8f7d395d8b 100644 --- a/src/features/vcs/__tests__/historyOps.test.ts +++ b/src/features/vcs/__tests__/historyOps.test.ts @@ -308,6 +308,13 @@ describe("Git Log commit actions", () => { "Fix_crash_on_start.patch", ); expect(suggestedPatchName({ kind: "commits", commits: [commit("a"), commit("b")] }, "x")).toBe("2_commits.patch"); + expect( + suggestedPatchName({ kind: "logChanges", changes: [], commits: [commit("Fix: historical file!")] }, "x"), + ).toBe("Fix_historical_file.patch"); + expect(suggestedPatchName({ kind: "logChanges", changes: [], commits: [commit("a"), commit("b")] }, "x")).toBe( + "2_commits.patch", + ); + expect(suggestedPatchName({ kind: "logChanges", changes: [], commits: [] }, "Changes")).toBe("0_files.patch"); expect(suggestedPatchName({ kind: "changes", files: [] }, "///")).toBe("changes.patch"); }); }); diff --git a/src/features/vcs/__tests__/logPanes.test.tsx b/src/features/vcs/__tests__/logPanes.test.tsx index a0fede6be9..2567d4cf85 100644 --- a/src/features/vcs/__tests__/logPanes.test.tsx +++ b/src/features/vcs/__tests__/logPanes.test.tsx @@ -42,10 +42,12 @@ import { graphOptionsMenu } from "../log/FilterBar"; import { EMPTY_TREE, assignLineStats, + canCreatePatchFromLogChanges, filesUnder, filterPatch, flatFileNodes, lineStatRanges, + logPatchRanges, toLogChanges, useLogChanges, } from "../logChanges"; @@ -122,6 +124,78 @@ describe("changed files model", () => { expect(rootFile!.statsFrom).toBe(EMPTY_TREE); }); + it("builds path-filtered historical patch ranges, including empty trees and both rename paths", () => { + const previous = useVcs.getState(); + useVcs.setState({ root: "/repo", repo: "/repo", roots: ["/repo"] }); + try { + const older: Commit = { ...commit, id: "a".repeat(40), parents: ["9".repeat(40)], timeMs: 1 }; + const newer: Commit = { ...commit, id: "b".repeat(40), parents: [older.id], timeMs: 2 }; + const changes = [ + ...toLogChanges([{ path: "added.ts", kind: "added", oldPath: null }], older, "/repo"), + ...toLogChanges([{ path: "edited.ts", kind: "modified", oldPath: null }], newer, "/repo"), + ...toLogChanges([{ path: "new.ts", kind: "renamed", oldPath: "old.ts" }], newer, "/repo"), + ...toLogChanges([{ path: "deleted.ts", kind: "deleted", oldPath: null }], newer, "/repo"), + ]; + const paths = ["edited.ts", "new.ts", "old.ts"]; + expect(canCreatePatchFromLogChanges(changes)).toBe(true); + expect(logPatchRanges(changes)).toEqual([ + { repo: "/repo", before: EMPTY_TREE, after: older.id, paths: ["added.ts"] }, + { repo: "/repo", before: older.id, after: newer.id, paths }, + { repo: "/repo", before: older.id, after: EMPTY_TREE, paths: ["deleted.ts"] }, + ]); + expect(logPatchRanges(changes, true)).toEqual([ + { repo: "/repo", before: older.id, after: EMPTY_TREE, paths: ["added.ts"] }, + { repo: "/repo", before: newer.id, after: older.id, paths }, + { repo: "/repo", before: EMPTY_TREE, after: older.id, paths: ["deleted.ts"] }, + ]); + + const other = { ...changes[1]!, repo: "/other" }; + useVcs.setState({ roots: ["/repo", "/other"] }); + expect(canCreatePatchFromLogChanges([changes[0]!, other])).toBe(false); + expect(logPatchRanges([changes[0]!, other])).toEqual([]); + const ambiguous = { ...changes[0]!, repo: null }; + expect(canCreatePatchFromLogChanges([ambiguous])).toBe(false); + expect(canCreatePatchFromLogChanges([{ ...changes[0]!, readOnly: true }])).toBe(true); + expect(canCreatePatchFromLogChanges([{ ...changes[0]!, repo: "/external", readOnly: true }])).toBe(false); + expect(canCreatePatchFromLogChanges([{ ...changes[0]!, oldPath: 42 as unknown as string }])).toBe(false); + expect(canCreatePatchFromLogChanges([{ ...changes[0]!, before: newer.id, after: newer.id }])).toBe(false); + expect(canCreatePatchFromLogChanges([])).toBe(false); + } finally { + useVcs.setState(previous); + } + }); + + it("enables changed-file patch actions and menu rows only for an applicable selection", () => { + const previous = useVcs.getState(); + useVcs.setState({ root: "/repo", repo: "/repo", roots: ["/repo", "/other"] }); + const files = toLogChanges( + [ + { path: "a.ts", kind: "modified", oldPath: null }, + { path: "b.ts", kind: "modified", oldPath: null }, + ], + commit, + "/repo", + ); + const dispose = registerLogPaneActions(); + try { + for (const id of ["vcs.log.changes.createPatch", "vcs.log.changes.copyPatch"]) { + const action = getAction(id)!; + expect(action.enabled!({ ctx: {}, arg: [] })).toBe(false); + expect(action.enabled!({ ctx: {}, arg: files })).toBe(true); + expect(action.enabled!({ ctx: {}, arg: [{ ...files[0]!, repo: "/other" }] })).toBe(true); + expect(action.enabled!({ ctx: {}, arg: [{ ...files[0]!, repo: "/external" }] })).toBe(false); + const item = (changes: ReturnType) => + changesMenu(changes).find((entry) => "action" in entry && entry.action === id); + expect(item(files)).toMatchObject({ arg: files, disabled: false }); + expect(item([])).toMatchObject({ disabled: true }); + expect(item([{ ...files[0]!, repo: "/external" }])).toMatchObject({ disabled: true }); + } + } finally { + dispose(); + useVcs.setState(previous); + } + }); + it("asks for one numstat per revision pair and matches a rename by either name", () => { const files = toLogChanges( [ @@ -265,6 +339,8 @@ describe("rename label", () => { describe("changed files pane", () => { it("shows the files flat or by directory and shares the selection with its actions", async () => { + const previous = useVcs.getState(); + useVcs.setState({ root: "/repo", repo: "/repo", roots: ["/repo"] }); vcsCommitFiles.mockResolvedValue({ status: "ok", data: [ @@ -275,10 +351,16 @@ describe("changed files pane", () => { useGitLog.setState({ commits: [commit], selected: commit.id, selection: [commit.id] }); const { unmount } = render(); expect(await screen.findByText("src")).toBeInTheDocument(); + const createPatch = screen.getByRole("button", { name: "Create Patch…" }); + const copyPatch = screen.getByRole("button", { name: "Copy as Patch to Clipboard" }); + expect(createPatch).toBeDisabled(); + expect(copyPatch).toBeDisabled(); fireEvent.mouseDown(screen.getByText("a.ts")); expect(useLogChanges.getState().selected.map((c) => c.path)).toEqual(["src/a.ts"]); expect(useLogChanges.getState().commits).toEqual([commit]); expect(screen.getByRole("button", { name: "Show Diff" })).toBeEnabled(); + expect(createPatch).toBeEnabled(); + expect(copyPatch).toBeEnabled(); useLogOptions.setState({ groupByDirectory: false }); expect(await screen.findByText("b.ts")).toBeInTheDocument(); @@ -286,6 +368,7 @@ describe("changed files pane", () => { expect(screen.getAllByText("src")).toHaveLength(2); unmount(); expect(useLogChanges.getState().selected).toEqual([]); + useVcs.setState(previous); }); it("shows added and deleted lines when the log option is on", async () => { diff --git a/src/features/vcs/__tests__/logPatch.test.ts b/src/features/vcs/__tests__/logPatch.test.ts new file mode 100644 index 0000000000..c160ef07ae --- /dev/null +++ b/src/features/vcs/__tests__/logPatch.test.ts @@ -0,0 +1,118 @@ +import type { Commit, PatchSource } from "@/bindings"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +const mocks = vi.hoisted(() => ({ + createPatch: vi.fn(), + writeClipboardText: vi.fn(), + openDialog: vi.fn(), + notify: vi.fn(), +})); + +vi.mock("@/platform/ipc", async (importOriginal) => { + const real = await importOriginal(); + return { + ...real, + commands: { + ...real.commands, + vcsCreatePatch: (repo: string | null, source: PatchSource, base: string | null) => + mocks.createPatch(repo, source, base), + }, + }; +}); +vi.mock("@/platform/clipboard", async (importOriginal) => ({ + ...(await importOriginal()), + writeClipboardText: mocks.writeClipboardText, +})); +vi.mock("../dialogs", async (importOriginal) => ({ + ...(await importOriginal()), + openDialog: mocks.openDialog, +})); +vi.mock("@/workbench/contributions", async (importOriginal) => ({ + ...(await importOriginal()), + notifications: () => ({ notify: mocks.notify }), +})); + +import { EMPTY_TREE, toLogChanges } from "../logChanges"; +import { copyLogChangesAsPatch } from "../patches"; +import { useVcs } from "../store"; + +const commit = (id: string, parents: string[], timeMs: number): Commit => ({ + id: id.repeat(40), + shortId: id.repeat(8), + parents, + author: "A", + email: "a@example.com", + timeMs, + summary: `Commit ${id}`, + message: `Commit ${id}`, + refs: [], +}); + +const originalVcs = useVcs.getState(); + +beforeEach(() => { + mocks.createPatch.mockReset(); + mocks.writeClipboardText.mockReset(); + mocks.openDialog.mockReset(); + mocks.notify.mockReset(); + mocks.writeClipboardText.mockResolvedValue(undefined); + useVcs.setState({ root: "/repo", repo: "/repo", roots: ["/repo"] }); +}); + +afterEach(() => useVcs.setState(originalVcs)); + +describe("Git Log changed-file patches", () => { + it("copies exactly the selected revision/path ranges, with both names of a rename", async () => { + const older = commit("a", ["9".repeat(40)], 1); + const newer = commit("b", [older.id], 2); + const changes = [ + ...toLogChanges([{ path: "added.ts", kind: "added", oldPath: null }], older, "/repo"), + ...toLogChanges([{ path: "edited.ts", kind: "modified", oldPath: null }], newer, "/repo"), + ...toLogChanges([{ path: "new.ts", kind: "renamed", oldPath: "old.ts" }], newer, "/repo"), + ]; + mocks.createPatch.mockImplementation(async (_repo: string, source: PatchSource) => ({ + status: "ok" as const, + data: source.from === "revisions" ? `patch ${source.before} ${source.after} ${source.paths.join(",")}\n` : "", + })); + await copyLogChangesAsPatch(changes); + + expect(mocks.createPatch.mock.calls).toEqual([ + ["/repo", { from: "revisions", before: EMPTY_TREE, after: older.id, paths: ["added.ts"] }, null], + [ + "/repo", + { + from: "revisions", + before: older.id, + after: newer.id, + paths: ["edited.ts", "new.ts", "old.ts"], + }, + null, + ], + ]); + expect(mocks.writeClipboardText).toHaveBeenCalledExactlyOnceWith( + `patch ${EMPTY_TREE} ${older.id} added.ts\npatch ${older.id} ${newer.id} edited.ts,new.ts,old.ts\n`, + ); + expect(mocks.openDialog).not.toHaveBeenCalled(); + }); + + it("does not touch the clipboard for empty, mixed-repository or external read-only selections", async () => { + const c = commit("c", ["9".repeat(40)], 1); + const files = toLogChanges([{ path: "a.ts", kind: "modified", oldPath: null }], c, "/repo"); + await copyLogChangesAsPatch([]); + await copyLogChangesAsPatch([files[0]!, { ...files[0]!, repo: "/other" }]); + await copyLogChangesAsPatch([{ ...files[0]!, repo: "/external", readOnly: true }]); + expect(mocks.createPatch).not.toHaveBeenCalled(); + expect(mocks.writeClipboardText).not.toHaveBeenCalled(); + }); + + it("leaves the clipboard untouched when Git returns an empty patch", async () => { + const c = commit("c", ["9".repeat(40)], 1); + const files = toLogChanges([{ path: "a.ts", kind: "modified", oldPath: null }], c, "/repo"); + mocks.createPatch.mockResolvedValue({ status: "ok", data: "" }); + await copyLogChangesAsPatch(files); + expect(mocks.writeClipboardText).not.toHaveBeenCalled(); + expect(mocks.notify).toHaveBeenCalledWith( + expect.objectContaining({ group: "vcs", level: "info", title: "No changes to create a patch from" }), + ); + }); +}); diff --git a/src/features/vcs/log/CommitDetails.tsx b/src/features/vcs/log/CommitDetails.tsx index 3e4c7910dd..11bd04ea86 100644 --- a/src/features/vcs/log/CommitDetails.tsx +++ b/src/features/vcs/log/CommitDetails.tsx @@ -40,6 +40,7 @@ import { buildFileTree, dirKeys, type FileTreeNode } from "../fileTree"; import styles from "../GitLog.module.css"; import { canApplySelectedChanges, + canCreatePatchFromLogChanges, canOpenRepositoryVersion, absolutePath, changesArg, @@ -412,6 +413,22 @@ export function CommitDetails({ commits, fileHistory = false }: { commits: Commi actionArg={chosenChanges} disabled={!chosenChanges.length} /> + + { return assignLineStats(files, loaded); } +/** One repository's selected historical files between the same two revisions. */ +export interface LogPatchRange { + repo: string; + before: string; + after: string; + paths: string[]; +} + +/** + * The repository a historical patch can safely use. A missing row repository is + * unambiguous only when the project has one root; otherwise callers must retain it. + */ +export function logPatchRepository(changes: readonly LogChange[]): string | null { + if (!changes.length) return null; + const state = useVcs.getState(); + const fallback = state.roots.length === 1 ? state.roots[0]! : state.roots.length ? null : (state.repo ?? state.root); + const repo = changes[0]!.repo ?? fallback; + if (!repo || changes.some((change) => (change.repo ?? fallback) !== repo)) return null; + return state.roots.length && !state.roots.includes(repo) ? null : repo; +} + +/** Create Patch is an export: empty, malformed, read-only external and mixed-repository selections cannot use it. */ +export function canCreatePatchFromLogChanges(changes: readonly LogChange[]): boolean { + if (!changes.length || !logPatchRepository(changes)) return false; + return ( + changes.every( + (change) => + typeof change.path === "string" && + change.path.length > 0 && + (change.oldPath === null || (typeof change.oldPath === "string" && change.oldPath.length > 0)) && + (change.before === null || (typeof change.before === "string" && change.before.length > 0)) && + (change.after === null || (typeof change.after === "string" && change.after.length > 0)) && + (change.before !== null || change.after !== null), + ) && changes.some((change) => (change.before ?? EMPTY_TREE) !== (change.after ?? EMPTY_TREE)) + ); +} + +/** + * Path-filtered revision diffs for exactly the selected rows. Added and deleted + * files use Git's empty tree on their missing side; renames include both names. + * Reversing swaps each range's endpoints, including the empty tree. + */ +export function logPatchRanges(changes: readonly LogChange[], reverse = false): LogPatchRange[] { + if (!canCreatePatchFromLogChanges(changes)) return []; + const repo = logPatchRepository(changes)!; + const ranges = new Map(); + for (const change of changes) { + const before = (reverse ? change.after : change.before) ?? EMPTY_TREE; + const after = (reverse ? change.before : change.after) ?? EMPTY_TREE; + if (before === after) continue; + const key = `${before}\0${after}`; + let range = ranges.get(key); + if (!range) ranges.set(key, (range = { repo, before, after, paths: [] })); + for (const path of change.oldPath ? [change.path, change.oldPath] : [change.path]) { + if (path && !range.paths.includes(path)) range.paths.push(path); + } + } + return [...ranges.values()]; +} + /** Files without directory grouping: by name, each node's path shown next to it. */ export function flatFileNodes(files: readonly F[], relPath: (f: F) => string): FileTreeNode[] { return files diff --git a/src/features/vcs/logPaneActions.ts b/src/features/vcs/logPaneActions.ts index 93e022245b..312f8f8fcb 100644 --- a/src/features/vcs/logPaneActions.ts +++ b/src/features/vcs/logPaneActions.ts @@ -18,6 +18,7 @@ import { import { isFavoriteBranch } from "./branches"; import { applySelectedChanges, + canCreatePatchFromLogChanges, canOpenRepositoryVersion, changesArg, compareChangesWithLocal, @@ -32,6 +33,7 @@ import { logOptions } from "./logOptions"; import { goToRef, selectedCommits, toggleCherryHighlight, updateLogOptions, useGitLog } from "./logStore"; import { commitKey, commitRepo } from "./multiRoot"; import { dropSelectedChanges, extractSelectedChanges } from "./rebase"; +import { copyLogChangesAsPatch, showCreatePatchForLogChanges } from "./patches"; import { openRevisionFile } from "./revisionInput"; import { currentRepoRoot, focusRepo } from "./store"; import { showCompareBranches, type BranchComparisonTarget, type BranchComparisonData } from "./CompareBranches"; @@ -301,6 +303,28 @@ export function registerLogPaneActions(): () => void { } }, }, + { + id: "vcs.log.changes.createPatch", + title: "Create Patch…", + category: "Git Log", + icon: "patch", + when: LOG, + hidden: true, + keyWhen: "vcsLogChangesFocus", + enabled: ({ arg }) => canCreatePatchFromLogChanges(changesArg(arg)), + run: ({ arg }) => showCreatePatchForLogChanges(changesArg(arg), useLogChanges.getState().commits), + }, + { + id: "vcs.log.changes.copyPatch", + title: "Copy as Patch to Clipboard", + category: "Git Log", + icon: "copy", + when: LOG, + hidden: true, + keyWhen: "vcsLogChangesFocus", + enabled: ({ arg }) => canCreatePatchFromLogChanges(changesArg(arg)), + run: ({ arg }) => copyLogChangesAsPatch(changesArg(arg)), + }, { id: "vcs.log.changes.getFromRevision", title: "Get from Revision", diff --git a/src/features/vcs/patches.tsx b/src/features/vcs/patches.tsx index 19262abd9a..a72b0d2cdc 100644 --- a/src/features/vcs/patches.tsx +++ b/src/features/vcs/patches.tsx @@ -1,5 +1,6 @@ import { readClipboardPlainText, writeClipboardText } from "@/platform/clipboard"; import { commitRepo } from "./multiRoot"; +import { canCreatePatchFromLogChanges, logPatchRanges, logPatchRepository, type LogChange } from "./logChanges"; /** Create Patch… (from local changes or commits) and Apply Patch… (file or clipboard, with a preview). */ import { useCallback, useEffect, useId, useMemo, useRef, useState } from "react"; import type { @@ -68,15 +69,20 @@ import { useDiffSource } from "./diffSource"; export type PatchOrigin = | { kind: "changes"; files: FileStatus[]; staging?: readonly StagingPatchEntry[] } | { kind: "commits"; commits: Commit[] } + | { kind: "logChanges"; changes: LogChange[]; commits: Commit[] } | { kind: "shelf"; entry: ShelvedChangeList; path?: string }; /** File name IDEA suggests: the change list or commit subject, sanitised. */ export function suggestedPatchName(origin: PatchOrigin, listName: string): string { const base = - origin.kind === "commits" + origin.kind === "commits" || origin.kind === "logChanges" ? origin.commits.length === 1 ? origin.commits[0]!.summary - : `${origin.commits.length} commits` + : origin.commits.length > 1 + ? `${origin.commits.length} commits` + : origin.kind === "logChanges" + ? `${origin.changes.length} files` + : "0 commits" : origin.kind === "shelf" ? origin.entry.name : listName; @@ -160,6 +166,38 @@ export function showCreatePatchForCommits(commits: Commit[]) { openDialog((close) => ); } +async function createLogChangesPatch(changes: readonly LogChange[], reverse: boolean, base: string | null) { + const patches = await Promise.all( + logPatchRanges(changes, reverse).map(({ repo, before, after, paths }) => + call(commands.vcsCreatePatch(repo, { from: "revisions", before, after, paths }, base)), + ), + ); + return patches.join(""); +} + +export function showCreatePatchForLogChanges(changes: LogChange[], commits: Commit[]) { + if (!canCreatePatchFromLogChanges(changes)) return; + openDialog((close) => ); +} + +/** Copy the selected historical files as a patch directly, without the Create Patch dialog. */ +export async function copyLogChangesAsPatch(changes: readonly LogChange[]) { + if (!canCreatePatchFromLogChanges(changes)) return; + await runOp( + tx("Create patch"), + async () => { + const patch = await createLogChangesPatch(changes, false, null); + if (!patch) { + noPatchChanges(); + return false; + } + await writeClipboardText(patch); + return true; + }, + { success: (copied) => (copied ? "Patch copied to the clipboard" : ""), refresh: false }, + ); +} + export function showCreatePatchForShelf(entry: ShelvedChangeList, path?: string) { openDialog((close) => ); } @@ -220,7 +258,11 @@ function CreatePatchDialog({ origin, onClose }: { origin: PatchOrigin; onClose: const root = useVcs((s) => s.root) ?? ""; const roots = useVcs((s) => s.roots); const [repo] = useState(() => - origin.kind === "commits" ? (commitRepo(origin.commits[0]!) ?? currentRepoRoot()) : currentRepoRoot(), + origin.kind === "commits" + ? (commitRepo(origin.commits[0]!) ?? currentRepoRoot()) + : origin.kind === "logChanges" + ? (logPatchRepository(origin.changes) ?? currentRepoRoot()) + : currentRepoRoot(), ); const listName = useChangelists((s) => activeList(s.state).name); const [selected, setSelected] = useState( @@ -254,7 +296,7 @@ function CreatePatchDialog({ origin, onClose }: { origin: PatchOrigin; onClose: setPending(true); setError(""); const source: PatchSource | null = - origin.kind === "shelf" + origin.kind === "shelf" || origin.kind === "logChanges" ? null : origin.kind === "changes" ? localPatchSource(origin, selected, reverse) @@ -273,7 +315,9 @@ function CreatePatchDialog({ origin, onClose }: { origin: PatchOrigin; onClose: ? await call( commands.vcsShelfPatch(origin.entry.id, origin.path ?? null, baseInput === null ? null : directory), ) - : await call(commands.vcsCreatePatch(origin.kind === "commits" ? repo : null, source!, directory)); + : origin.kind === "logChanges" + ? await createLogChangesPatch(origin.changes, reverse, directory) + : await call(commands.vcsCreatePatch(origin.kind === "commits" ? repo : null, source!, directory)); if (!patch) { noPatchChanges(); return false; diff --git a/src/platform/keymaps/ideaParity.test.ts b/src/platform/keymaps/ideaParity.test.ts index 510533d4a7..332a5978c8 100644 --- a/src/platform/keymaps/ideaParity.test.ts +++ b/src/platform/keymaps/ideaParity.test.ts @@ -122,6 +122,8 @@ describe("IDEA keymap parity", () => { // Vcs.Log.GoToRef: Find in the Git Log table. ["vcs.log.goToRef", ["Meta+F"], ["Ctrl+F"]], ["vcs.log.maximizeCommitMessage", [], []], + ["vcs.log.changes.createPatch", [], []], + ["vcs.log.changes.copyPatch", [], []], ["vcs.log.refresh", ["Meta+R"], ["Ctrl+F5"]], ["vcs.log.focusTextFilter", ["Ctrl+L"], ["Ctrl+L"]], // Back / Forward also carry the mouse side buttons (``). diff --git a/src/platform/keymaps/intellij-macos.ts b/src/platform/keymaps/intellij-macos.ts index 981510c72b..02000be9ee 100644 --- a/src/platform/keymaps/intellij-macos.ts +++ b/src/platform/keymaps/intellij-macos.ts @@ -389,6 +389,8 @@ export const intellijMacos: Record = { "vcs.addToVcs": ["Meta+Alt+A"], "vcs.showDiff": ["Meta+D"], "vcs.log.changes.showDiff": ["Meta+D"], + "vcs.log.changes.createPatch": [], + "vcs.log.changes.copyPatch": [], "vcs.showDiffInNewWindow": [], "vcs.nextChange": ["Ctrl+Alt+Shift+Down"], "vcs.prevChange": ["Ctrl+Alt+Shift+Up"], diff --git a/src/platform/keymaps/intellij-windows.ts b/src/platform/keymaps/intellij-windows.ts index a9c4f02b66..b3db88f98b 100644 --- a/src/platform/keymaps/intellij-windows.ts +++ b/src/platform/keymaps/intellij-windows.ts @@ -383,6 +383,8 @@ export const intellijWindows: Record = { "vcs.addToVcs": ["Ctrl+Alt+A"], "vcs.showDiff": ["Ctrl+D"], "vcs.log.changes.showDiff": ["Ctrl+D"], + "vcs.log.changes.createPatch": [], + "vcs.log.changes.copyPatch": [], "vcs.showDiffInNewWindow": [], "vcs.nextChange": ["Ctrl+Alt+Shift+Down"], "vcs.prevChange": ["Ctrl+Alt+Shift+Up"], diff --git a/src/platform/keymaps/vscode-macos.ts b/src/platform/keymaps/vscode-macos.ts index cabe47ee6a..bd735a2a1f 100644 --- a/src/platform/keymaps/vscode-macos.ts +++ b/src/platform/keymaps/vscode-macos.ts @@ -402,6 +402,8 @@ export const vscodeMacos: Record = { "vcs.addToVcs": [], "vcs.showDiff": [], "vcs.log.changes.showDiff": [], + "vcs.log.changes.createPatch": [], + "vcs.log.changes.copyPatch": [], "vcs.showDiffInNewWindow": [], "vcs.nextChange": ["Alt+F5"], "vcs.prevChange": ["Alt+Shift+F5"], From ee9b50179e136a687ae78371eb027d7fb7789f3b Mon Sep 17 00:00:00 2001 From: LU XIANGRUI <1078666705@qq.com> Date: Mon, 30 Nov 2026 21:15:11 +0900 Subject: [PATCH 15/46] feat(welcome): import recent projects and groups from a JetBrains IDE (#6979) Import Recent Projects from JetBrains IDE (Welcome screen more menu, File > Manage IDE Settings) reads the IDE's options/recentProjects.xml and merges its recent projects and project groups into OpenIDEA's. Entries keep their custom or display name and the later of their open and activation times; hidden (LightEdit) entries are skipped, $USER_HOME$ and $APPLICATION_CONFIG_DIR$ are expanded, and projects whose folder is gone are skipped and counted. Existing entries and groups are kept, a taken group name gets a number, and importing twice adds nothing. Import Settings from JetBrains IDE lists the recent projects as a row of its confirmation and merges them too. Closes #6970 Co-authored-by: wildcatDownstairs <26499420+wildcatDownstairs@users.noreply.github.com> --- Cargo.lock | 1 + crates/ide-host/src/menu.rs | 1 + crates/ide-workspace/Cargo.toml | 1 + crates/ide-workspace/src/recent.rs | 349 +++++++++++++++++- src-tauri/src/commands/app.rs | 31 ++ src-tauri/src/menu.rs | 1 + src-tauri/tests/commands.snap | 1 + src/bindings.ts | 15 + .../__tests__/importFromJetBrainsIde.test.tsx | 62 +++- .../jetbrainsSettingsImport.test.tsx | 30 ++ .../jetbrainsTemplatesImport.test.tsx | 1 + src/features/app/jetbrainsSettings.tsx | 35 +- src/features/app/projectActions.ts | 69 +++- src/features/welcome/ProjectsPage.tsx | 7 + src/platform/locales/en.json | 1 + src/platform/locales/text/en.json | 8 + src/platform/locales/text/zh.json | 7 + src/platform/locales/zh.json | 1 + 18 files changed, 594 insertions(+), 27 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 8b19cd0c07..0e01cf43a2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5116,6 +5116,7 @@ dependencies = [ "ide-text", "ide-vfs", "parking_lot 0.12.5", + "quick-xml 0.42.0", "semver", "serde", "serde_json", diff --git a/crates/ide-host/src/menu.rs b/crates/ide-host/src/menu.rs index 65eeca5483..d80bb212cd 100644 --- a/crates/ide-host/src/menu.rs +++ b/crates/ide-host/src/menu.rs @@ -277,6 +277,7 @@ pub fn spec(os: Os) -> Vec { act("file.exportSettings", "Export Settings…"), act("file.importSettings", "Import Settings…"), act("file.importJetBrainsSettings", "Import Settings from JetBrains IDE…"), + act("file.importJetBrainsRecentProjects", "Import Recent Projects from JetBrains IDE…"), act("file.syncSettings", "Sync Settings Now"), ], ), diff --git a/crates/ide-workspace/Cargo.toml b/crates/ide-workspace/Cargo.toml index f3e8d275e5..f4d324b079 100644 --- a/crates/ide-workspace/Cargo.toml +++ b/crates/ide-workspace/Cargo.toml @@ -24,6 +24,7 @@ globset.workspace = true uuid.workspace = true zip.workspace = true encoding_rs.workspace = true +quick-xml = "0.42" [target.'cfg(windows)'.dependencies] winreg = "0.56" diff --git a/crates/ide-workspace/src/recent.rs b/crates/ide-workspace/src/recent.rs index 7db02c3cd7..5a027f892b 100644 --- a/crates/ide-workspace/src/recent.rs +++ b/crates/ide-workspace/src/recent.rs @@ -162,6 +162,127 @@ fn is_missing(path: &Path) -> bool { path.is_absolute() && !text.contains("://") && !wsl && !path.exists() } +fn folder_name(path: &Path) -> String { + path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| path.display().to_string()) +} + +/// What importing a JetBrains IDE's recent projects did (or, as a preview, would do). +#[derive(Clone, Debug, Default, PartialEq, Serialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct JetBrainsRecentImport { + /// Projects added to the recent projects. + pub imported: u32, + /// Projects left out because their folder no longer exists. + pub missing: u32, + /// Project groups added. + pub groups: u32, +} + +/// A recent project as a JetBrains IDE keeps it in `options/recentProjects.xml`. +#[derive(Debug, Default, PartialEq)] +struct JetBrainsRecent { + path: String, + name: Option, + opened_at_ms: f64, + /// Opened but not listed (LightEdit, a file opened alone): the IDE does not show it. + hidden: bool, +} + +#[derive(Debug, Default, PartialEq)] +struct JetBrainsGroup { + name: String, + paths: Vec, + expanded: bool, +} + +/// The `RecentProjectsManager` state: `additionalInfo` entries (path → `RecentProjectMetaInfo`) and +/// `groups` (`ProjectGroup` with `name`, `expanded` and its `projects`). +fn parse_jetbrains_recent(xml: &str) -> (Vec, Vec) { + use quick_xml::{Reader, XmlVersion, events::Event}; + let mut reader = Reader::from_str(xml); + let (mut projects, mut groups) = (Vec::new(), Vec::new()); + let mut project: Option = None; + let mut group: Option = None; + loop { + let (tag, empty) = match reader.read_event() { + Ok(Event::Start(tag)) => (tag, false), + Ok(Event::Empty(tag)) => (tag, true), + Ok(Event::End(tag)) => { + match tag.local_name().as_ref() { + "entry" => projects.extend(project.take()), + "ProjectGroup" => groups.extend(group.take()), + _ => {} + } + continue; + } + Ok(Event::Eof) | Err(_) => break, + _ => continue, + }; + let attr = |key: &str| { + tag.attributes() + .flatten() + .find(|a| a.key.as_ref() == key) + .and_then(|a| a.normalized_value(XmlVersion::Implicit1_0).ok().map(|v| v.into_owned())) + }; + match tag.local_name().as_ref() { + "entry" if !empty && group.is_none() => { + project = attr("key").map(|path| JetBrainsRecent { path, ..Default::default() }); + } + "RecentProjectMetaInfo" => { + if let Some(p) = &mut project { + p.hidden = attr("hidden").as_deref() == Some("true"); + } + } + "ProjectGroup" if !empty => group = Some(JetBrainsGroup::default()), + "option" => { + let (name, value) = (attr("name"), attr("value")); + if let Some(g) = &mut group { + match (name.as_deref(), value) { + (Some("name"), Some(v)) => g.name = v, + (Some("expanded"), Some(v)) => g.expanded = v == "true", + // `