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

..
32 Коміти
Автор SHA1 Повідомлення Дата
l0ng-ai 45d34ac638 fix(editor): keep indent guides in the indentation with a proportional font (#3634)
Guides were placed at multiples of ch (the width of "0"), while indentation is made of spaces, which are narrower in a proportional font, so guides drifted into the code the deeper the block. The guides plugin now measures the editor font's space width (--openidea-space) and places guides, and the indent of code lens rows, by it. Monospace fonts render as before.
2026-11-16 12:28:53 +08:00
LU XIANGRUIтаwildcatDownstairs 7709897dbb fix(project): ask about trust before opening the project window (#3663)
Opening an untrusted project in a new window created the window first and asked inside it, where the splash gave way after its 4 s limit to the Welcome screen under the question.

Entry points that may create a window (Open…, Open in New Window, recent projects, dropped folders, clone, plugin requests) now ask in the current window first and create the window only after Trust or Preview; Don't Open creates none. A launch without an originating window (openidea <path>, Dock drop) keeps the splash up under the dialog until the answer. WSL folders are still asked about by their remote window.

Closes #3648

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-16 12:26:51 +08:00
LU XIANGRUIтаwildcatDownstairs da3b00518f fix(editor): take a hidden tab's tooltips off the page with its view (#3662)
A slow Go to Implementation left its "Finding navigation target…" hint on the page after the target opened in another tab. Editor tooltips are parented to document.body, outside the view, so hiding a tab left any open tooltip (hint, hover, completion) behind, and the pending-hint cleanup skipped detached views.

Each tab now has its own tooltip layer that leaves and returns with its view, and hint cleanup and timeouts also run on hidden views.

Closes #3647

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-16 12:24:53 +08:00
l0ng-ai 87e4dcf42b feat(agents): toggle sending the current file and selection as IDE context (#3664)
A toolbar button in the agent composer turns IDE context on or off (on by default, remembered). While on, each message carries the focused editor's file, or its selected lines as a line-range mention, unless the draft already references that file.

Closes #3633
2026-11-16 12:22:56 +08:00
l0ng-ai c860649b13 test(app): mock invoke for the system notification in the update checks (#3661)
Balloons are mirrored to a system notification since #3606, which calls invoke; the update-check test's @tauri-apps/api/core mock had none, so 28 cases failed on main.
2026-11-16 12:13:33 +08:00
LU XIANGRUIтаwildcatDownstairs 07afe43d0d feat(settings): import keymaps, terminal font, tabs and indents and more editor options from JetBrains (#3650)
Import Settings from a JetBrains IDE now also brings over the keymaps (the IDE's active one becomes current), the terminal font, Tabs and Indents of the current code style scheme, console soft wrap and about 45 more EditorSettings / CodeInsightSettings options. The IDEA keymap parser moves to src/platform so the import can use it, and now accepts the lower-case key names IDEA writes in user keymaps (every non-letter shortcut of a user keymap was dropped before, also in Settings › Keymap › Import).

Closes #3649

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-16 12:12:21 +08:00
Muuтаmuutot 8ca2e089a3 fix(vcs): highlight diff viewers with the editor's syntax and semantic colours (#3653)
Diff viewers used a trimmed highlight style (14 tag groups), loaded languages straight from @codemirror/language-data (missing the editor's own modes, tag patches and the data-language attribute that language-scoped colour schemes key on), and had no semantic-token layer. They now use the editor's highlight style and language pipeline, and panes showing an open document get semantic highlighting.

Co-authored-by: muutot <[email protected]>
2026-11-16 12:10:24 +08:00
terwerтаterwer 41a8fbc591 fix(agents): read Codex session metadata from rollout payloads (#3659)
Current Codex rollouts start with a top-level session_meta record whose id and cwd live in payload; the scanner read them from the outer object and silently skipped every such session in the external-session import list. Read the payload, keeping the nested and unwrapped forms.

Closes #3655

Co-authored-by: terwer <[email protected]>
2026-11-16 12:07:54 +08:00
LU XIANGRUIтаwildcatDownstairs 3a0536eafc fix(menu): keep the menu usable while a Settings window is in front (#3657)
On macOS the backend treated the Settings window as modal and dropped every menu item except Quit, Settings, Project Structure and New Projects Settings, while still showing them enabled. Items chosen with Settings in front now run in its project window, which is brought forward; once what the action opened closes (or right away if it opened nothing) Settings comes back to the front. The project window pushes its menu enablement once on blur, so editor-only items grey out, and enablement pushed by other windows no longer overrides the front window's.

Closes #3625

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-16 12:07:09 +08:00
kevinh 9cbdde526b fix(vcs): update and roll back a project whose submodules changed (#3656)
git status lists submodules at another commit or with changes inside among the superproject's changes, but git stash leaves them in place, so the stash added no entry and Update Project (merge, rebase, checkout, reset) failed with "could not save the local changes". A stash that adds no entry now means there was nothing to put aside. Rollback of a submodule entry, or of a folder containing one, now runs git restore --recurse-submodules --worktree: the submodule goes back to the recorded commit with its tracked files restored; untracked files are kept.

Closes #3632

Co-authored-by: kevinh458 <[email protected]>
2026-11-16 12:02:43 +08:00
l0ng-ai 2878eb8d87 feat(sdk): add a JDK from disk in Project Structure › SDKs (#3660)
The SDKs list offered only Download JDK…. The toolbar's + now also has Add JDK from Disk…: the picked folder is checked to be a JDK home and kept in the global languages.java.addedJdks, which detection lists from then on, so it appears in every JDK picker. − removes a JDK added this way.

Closes #3628
2026-11-16 12:00:30 +08:00
l0ng-ai 2e764d74f8 fix(debugger): end a program suspended at a breakpoint at once on Stop (#3658)
For adapters without a terminate request (Delve, java-debug), Stop sent SIGTERM and waited up to 10 s. A program suspended in the debugger cannot act on SIGTERM (on macOS not even SIGKILL while debugserver holds it), so Stop sat in "stopping" for the full wait. When the session is suspended, Stop now kills the program's tree, sends disconnect with terminateDebuggee so the adapter ends it, and skips the wait for shutdown output. A running program still gets SIGTERM first.

Fixes #3623
2026-11-16 11:48:55 +08:00
l0ng-ai 92dd70f08b fix(tools): install debugpy when the project's Python has no pip (#3654)
debugpy's private copy was made with python -m pip of the selected interpreter; a uv-made virtualenv has no pip, so the install failed with "No module named pip". The copy is a universal wheel: when the interpreter has no pip, pip runs through uv tool run pip, or another Python on PATH that has it.

Fixes #3619
2026-11-16 11:25:25 +08:00
l0ng-ai 484bbfc704 fix(ui): paint tree row tints as full-width bands (#3652)
File colours, excluded folders and data source colours were painted as the row's own background: inset from the tree's edges, rounded per row, or dropped under hover and selection, so a run of tinted rows read as a ragged stack. The tint is now a full-width band under the row; hover and selection stay rounded on top. Excluded folders and data source colours share the rowTint path.

Fixes #3616
2026-11-16 11:16:55 +08:00
Deng Liuтаdengliu 0b097808f1 fix(agents): increase process-run step indentation and align running tool icons (#3636)
Expanded process runs and turn folds read nearly flat: the guide line sat left of the summary chevron, nested chevrons indented by only a few pixels, and tool rows without output yet had no chevron slot, so their icon jumped right once output arrived. The guide now drops from the parent chevron's centre, tool calls after a thought indent under it, expanded output indents with its row, and output-less tool rows reserve the chevron's width.

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

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

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

Co-authored-by: guoyucode <[email protected]>
2026-11-16 11:04:29 +08:00
acaoтаamphetamlne 17e11b7904 fix(lsp): bound and cancel Go module deprecation queries (#3333)
The go.mod deprecation query (go list -m -u) could wait indefinitely on a proxy or toolchain download, and superseded checks kept running. Bound it to 60 s and 8 MiB of stdout; a new check of the same document, closing it, revoking execution permission or shutting down cancels it. A supervisor task kills and reaps the process tree even if the caller is dropped; failed or cancelled checks publish nothing.

Co-authored-by: amphetamlne <[email protected]>
2026-11-16 11:01:05 +08:00
acaoтаamphetamlne 22aa1edd61 fix(editor): discard obsolete inlay hint responses (#3253)
Inlay hint requests only checked whether the document had changed, so an older response (e.g. for the previous viewport) could replace newer hints, or restore hints after they were disabled. A refresh or destroy now bumps a generation; work that is no longer wanted is skipped after document sync, before applying results and before marking the server unavailable.

Co-authored-by: amphetamlne <[email protected]>
2026-11-16 10:59:48 +08:00
acaoтаamphetamlne 07c862c785 fix(workspace): detect marked environments before directory-name skips (#3241)
Root detection skipped dot-prefixed and conventional directory names (.venv, venv, .conda) before checking the pyvenv.cfg / conda-meta markers, so those environments were never recorded as excluded roots and their packages could reach the index and VFS walk. Check the markers first; the name-based skip still stops traversal.

Co-authored-by: amphetamlne <[email protected]>
2026-11-16 10:58:53 +08:00
l0ng-ai b60dad7076 feat(languages): Gherkin feature files (#3645)
.feature files are recognised as Gherkin: syntax colours for keywords in every Gherkin language, tags, tables, doc strings and outline placeholders; line comments, two-space indentation, a file icon, and folding of each section, step argument and doc string by indentation.

Part of #797
2026-11-16 10:56:23 +08:00
l0ng-ai 148e45745a feat(database): compare the structure of two schemas (#3644)
Compare Structure picks a source and a target schema, reads their tables with columns, indexes and foreign keys, and shows the differences as a tree (only in source, only in target, different), hiding identical items on request. Checked differences become the migration script that makes the target match the source in the target dialect; changes a dialect cannot express are left as comments. The script is copied or opened in a console of the target; nothing is run.

Closes #2694
2026-11-16 10:52:21 +08:00
l0ng-ai 3287061ea1 feat(database): SQL in MyBatis mapper XML (#3641)
The statements of <select>, <insert>, <update>, <delete> and <sql> in a MyBatis mapper are highlighted as SQL in the data source dialect and get completion, unresolved table/column inspections, Go to Declaration and Quick Documentation against the data source of the file SQL resolution scope (or the only data source). The SQL tools read the mapper with everything but the statements blanked out, so offsets stay the file own; parameters, entities, CDATA, selectKey, comments and the dynamic tags where/set/trim/foreach are read the way MyBatis builds the SQL.

Closes #2457
2026-11-16 10:44:48 +08:00
l0ng-ai 223beeb374 chore(debugger): drop an unused re-export of openAttachPopup (#3639)
pnpm knip failed on main: actions.ts re-exported openAttachPopup, which every caller imports from ./attachPopup directly.
2026-11-16 10:39:30 +08:00
l0ng-ai 8b9ad2e9d1 feat(database): SQL resolution scopes (#3638)
Settings › Languages & Frameworks › SQL Resolution Scopes maps project folders and files to a data source and schema (project settings, database.resolutionScopes). SQL files in a mapped folder resolve against its data source for completion, inspections, navigation and the console toolbar, unless another data source is picked in the toolbar; the deepest row wins and the Project row applies elsewhere. Contributed settings pages can start on the project scope (defaultScope).

Part of #2457
2026-11-16 10:38:58 +08:00
l0ng-ai a5306bade3 feat(database): show query results in the editor under their statements (#3635)
The database console toolbar gets an In-Editor Results toggle (also the db.toggleInEditorResults action, saved as database.inEditorResults). While it is on, each result set of a run shows in the editor under the statement that produced it, with the result tab grid, toolbar, paging, editing and export, and a close button instead of Pin. Running a statement again replaces its result; deleting the statement drops it. Results follow edits of the text, keep their place when the console is reopened and can be resized by dragging their bottom edge. With the toggle off, results go to the Services view as before.

Closes #2956
2026-11-16 10:30:55 +08:00
itcodesтаsliencio aa8822d9a3 feat(debugger): attach to a running Unity Editor (#2919)
Unity projects get a debug-only "Unity Editor" run configuration, selected by default. Debug opens a picker of local Unity Editor processes with the current project first; Run > Attach to Unity Process is also available. The tool installer fetches the pinned Unity Debugger 3.0.1 adapter with SHA-256 verification, and the session reports ready once the Mono runtime is up. A missing Mono executable on macOS and Linux is reported in the picker.

Refs #1436

Co-authored-by: sliencio <[email protected]>
2026-11-16 10:16:50 +08:00
l0ng-ai 5fca9c9ed0 docs(readme): rename the WeChat group QR image so the new code shows up 2026-11-16 10:11:00 +08:00
Gabriel Gondim 83805734bf feat(notifications): system notifications for balloons while OpenIDEA is in the background (#3606)
Settings › Appearance & Behavior › Notifications › Enable system notifications (global, on by default): a balloon shown while no OpenIDEA window is focused also goes to the OS notification centre with the same title and text, in the UI language; clicking it focuses the window that raised it. Agents emit an Attention event (finished / needs input / failed, de-duplicated) that raises the usual in-IDE notification, so they reach the OS through the same path. Adds tauri-plugin-notification.

Closes #3531

Co-authored-by: GGVidal <[email protected]>
2026-11-16 10:09:54 +08:00
l0ng-ai 0b3d1d67d9 docs(readme): update the WeChat group QR code 2026-11-16 10:08:39 +08:00
l0ng-ai 53a26b95a4 feat(build): read Eclipse projects without a build tool (#3630)
Eclipse projects without Maven or Gradle: .classpath source folders become Source / Test roots and its output folder is excluded; builds use the .classpath libraries and the web content folder (WST component or a conventional folder holding WEB-INF/web.xml) as the Web facet when none is configured; a web project with no artifacts gets <name>:war exploded for Build Artifacts and Tomcat.

Part of #3571
2026-11-16 10:02:16 +08:00
165 змінених файлів з 6918 додано та 460 видалено

No files matched your search

Бінарний файл не відображається.

Після

Ширина:  |  Висота:  |  Розмір: 160 KiB

Бінарний файл не відображається.

До

Ширина:  |  Висота:  |  Розмір: 86 KiB

Створено
+131 -6
Переглянути файл
@@ -199,7 +199,7 @@ dependencies = [
"wayland-backend",
"wayland-client",
"wayland-protocols",
"zbus",
"zbus 5.19.0",
]
[[package]]
@@ -5722,6 +5722,20 @@ dependencies = [
"serde_repr",
]
[[package]]
name = "mac-notification-sys"
version = "0.6.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fd604973958ddcc11b561193c0fb96ba146506ef2f231ef2e7c35fd2cbc9beca"
dependencies = [
"cc",
"log",
"objc2 0.6.5",
"objc2-foundation 0.3.2",
"time",
"uuid",
]
[[package]]
name = "mach2"
version = "0.6.0"
@@ -5994,6 +6008,20 @@ dependencies = [
"windows-sys 0.60.2",
]
[[package]]
name = "notify-rust"
version = "4.19.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "57da5b5d3b7809bf71858da5a2818c3404ca4688c02c8abecdda0fcdec235df3"
dependencies = [
"futures-lite",
"log",
"mac-notification-sys",
"serde",
"tauri-winrt-notification",
"zbus 6.3.0",
]
[[package]]
name = "notify-types"
version = "2.1.0"
@@ -6666,6 +6694,7 @@ dependencies = [
"tauri-build",
"tauri-plugin-dialog",
"tauri-plugin-mcp-bridge",
"tauri-plugin-notification",
"tauri-plugin-opener",
"tauri-plugin-single-instance",
"tauri-plugin-updater",
@@ -8153,7 +8182,7 @@ dependencies = [
"once_cell",
"serde",
"sha2 0.11.1",
"zbus",
"zbus 5.19.0",
]
[[package]]
@@ -9429,6 +9458,26 @@ dependencies = [
"windows-core",
]
[[package]]
name = "tauri-plugin-notification"
version = "2.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "14a226bfb8189ec4ab2c1936e66330ad06c44d9f6c54a674338208491dee177f"
dependencies = [
"log",
"notify-rust",
"rand 0.10.3",
"serde",
"serde_json",
"serde_repr",
"tauri",
"tauri-plugin",
"thiserror 2.0.21",
"time",
"url",
"zbus 5.19.0",
]
[[package]]
name = "tauri-plugin-opener"
version = "2.7.2"
@@ -9448,7 +9497,7 @@ dependencies = [
"thiserror 2.0.21",
"url",
"windows",
"zbus",
"zbus 5.19.0",
]
[[package]]
@@ -9464,7 +9513,7 @@ dependencies = [
"tokio",
"tracing",
"windows-sys 0.61.2",
"zbus",
"zbus 5.19.0",
]
[[package]]
@@ -9647,6 +9696,17 @@ dependencies = [
"toml 1.1.8+spec-1.1.0",
]
[[package]]
name = "tauri-winrt-notification"
version = "0.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f37a6c354fd28fc9e322ed9bd47e3959576dad28c9d58ea1cf888cce1c7ccb36"
dependencies = [
"thiserror 2.0.21",
"windows",
"windows-version",
]
[[package]]
name = "tempfile"
version = "3.27.0"
@@ -12137,11 +12197,38 @@ dependencies = [
"uuid",
"windows-sys 0.61.2",
"winnow 1.0.4",
"zbus_macros",
"zbus_macros 5.19.0",
"zbus_names",
"zvariant",
]
[[package]]
name = "zbus"
version = "6.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6b4aae740b23927ceabed962431abab2cdefb9f7f885e5bbab062da09bf580e4"
dependencies = [
"async-trait",
"bitflags 2.13.2",
"endi",
"futures-core",
"hex",
"libc",
"ordered-stream",
"rustix",
"serde",
"serde_repr",
"socket2",
"uds_windows",
"uuid",
"windows-sys 0.61.2",
"winnow 1.0.4",
"zbus_macros 6.3.0",
"zbus_utils",
"zcheapstr",
"zruntime",
]
[[package]]
name = "zbus-secret-service-keyring-store"
version = "1.0.1"
@@ -12150,7 +12237,7 @@ checksum = "74801d001b9e7729adb4f1825b67b398185fed424749aa3d8bacf70417137d9a"
dependencies = [
"keyring-core",
"secret-service",
"zbus",
"zbus 5.19.0",
]
[[package]]
@@ -12168,6 +12255,18 @@ dependencies = [
"zvariant_utils",
]
[[package]]
name = "zbus_macros"
version = "6.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "37c9dd4beaf145c16fcb2902862f50da86e54aed13dd368ddf64a1d17e6b8529"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.9",
"zbus_utils",
]
[[package]]
name = "zbus_names"
version = "4.3.5"
@@ -12179,6 +12278,19 @@ dependencies = [
"zvariant",
]
[[package]]
name = "zbus_utils"
version = "6.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "af55e52da295311b368c45bcae221f020e28e97a2420360170ce389218e76ec7"
dependencies = [
"proc-macro2",
"quote",
"serde",
"syn 3.0.9",
"winnow 1.0.4",
]
[[package]]
name = "zcheapstr"
version = "1.1.0"
@@ -12335,6 +12447,19 @@ dependencies = [
"simd-adler32",
]
[[package]]
name = "zruntime"
version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ce6a55d4f521760475a30f7b96779508fe8c40dc834478709454dd1d5f0ebc72"
dependencies = [
"futures-core",
"futures-io",
"rustix",
"socket2",
"windows-sys 0.61.2",
]
[[package]]
name = "zune-core"
version = "0.5.3"
+1 -1
Переглянути файл
@@ -68,7 +68,7 @@ the [official plugins](plugins/official). The plugin API is still a preview.
- [Discord](https://discord.gg/2Zy4yn7gP) — questions, feedback and release news.
- WeChat group — scan to join:
<img src=".github/assets/wechat-group.png" alt="WeChat group QR code" width="200">
<img src=".github/assets/wechat-group-3.png" alt="WeChat group QR code" width="200">
- Contributing: see [CONTRIBUTING.md](CONTRIBUTING.md) and the [contributor docs](https://openidea.sh/en/contribute/setup).
+1 -1
Переглянути файл
@@ -68,7 +68,7 @@ Eklentileri Ayarlar › Eklentiler (Settings › Plugins) bölümünden kur ya d
- [Discord](https://discord.gg/2Zy4yn7gP): sorular, geri bildirim ve sürüm haberleri.
- WeChat grubu, katılmak için kodu okut:
<img src=".github/assets/wechat-group.png" alt="WeChat grubu QR kodu" width="200">
<img src=".github/assets/wechat-group-3.png" alt="WeChat grubu QR kodu" width="200">
- Katkıda bulunmak için: [CONTRIBUTING.md](CONTRIBUTING.md) ve [katkıcı belgeleri](https://openidea.sh/en/contribute/setup).
+1 -1
Переглянути файл
@@ -66,7 +66,7 @@ WebAssembly 组件运行;主题、图标主题和语言无需编写代码。
- [Discord](https://discord.gg/2Zy4yn7gP):提问、反馈和版本发布消息。
- 微信群,扫码加入:
<img src=".github/assets/wechat-group.png" alt="微信群二维码" width="200">
<img src=".github/assets/wechat-group-3.png" alt="微信群二维码" width="200">
- 参与贡献:参见 [CONTRIBUTING.md](CONTRIBUTING.md) 和[贡献者文档](https://openidea.sh/zh/contribute/setup)。
+20 -5
Переглянути файл
@@ -134,7 +134,10 @@ fn codex_meta(line: &serde_json::Value) -> Option<(String, Option<String>)> {
let payload =
line.get("payload").filter(|p| p.get("type").and_then(serde_json::Value::as_str) == Some("session_meta"));
let inner = payload.and_then(|p| p.get("payload")).or_else(|| {
line.get("type").and_then(serde_json::Value::as_str).filter(|t| *t == "session_meta").and(Some(line))
line.get("type")
.and_then(serde_json::Value::as_str)
.filter(|t| *t == "session_meta")
.map(|_| line.get("payload").unwrap_or(line))
})?;
let id = inner.get("id").and_then(serde_json::Value::as_str)?.to_owned();
let cwd = inner.get("cwd").and_then(serde_json::Value::as_str).map(str::to_owned);
@@ -293,16 +296,28 @@ mod tests {
assert_eq!(sessions[0].title, "hello there");
}
#[test]
fn codex_meta_accepts_current_and_legacy_shapes() {
let meta = json!({"id": "thread-1", "cwd": "/work/app"});
for line in [
json!({"type": "session_meta", "payload": meta}),
json!({"payload": {"type": "session_meta", "payload": meta}}),
json!({"type": "session_meta", "id": "thread-1", "cwd": "/work/app"}),
] {
assert_eq!(codex_meta(&line), Some(("thread-1".to_owned(), Some("/work/app".to_owned()))));
}
}
#[test]
fn lists_codex_rollouts_with_meta() {
let tmp = tempfile::tempdir().unwrap();
write(
&tmp.path().join("sessions/2026/01/02/rollout-01.jsonl"),
&[
json!({"timestamp": "t", "payload": {"type": "session_meta",
"payload": {"id": "thread-1", "cwd": "/work/app"}}}),
json!({"timestamp": "t", "payload": {"type": "user_message",
"payload": {"message": "add tests"}}}),
json!({"timestamp": "t", "type": "session_meta",
"payload": {"id": "thread-1", "cwd": "/work/app"}}),
json!({"timestamp": "t", "type": "event_msg",
"payload": {"type": "user_message", "message": "add tests"}}),
],
);
write(&tmp.path().join("sessions/notes.jsonl"), &[json!({"nope": true})]);
+32 -1
Переглянути файл
@@ -135,6 +135,8 @@ struct Shared {
/// [`IDLE_RELEASE`], in milliseconds (shorter in tests).
idle_release_ms: AtomicU64,
mcp_servers_hook: RwLock<Option<Arc<McpServersFn>>>,
/// Monotonic id for [`AgentEvent::Attention`] episodes.
attention_seq: AtomicU64,
}
/// What an agent offered in its last session, for the New Task page.
@@ -417,6 +419,7 @@ impl AgentManager {
probes: Mutex::new(HashMap::new()),
idle_release_ms: AtomicU64::new(IDLE_RELEASE.as_millis() as u64),
mcp_servers_hook: RwLock::new(None),
attention_seq: AtomicU64::new(0),
});
shared.paths.catalogs.subscribe(&shared);
let mut tasks = HashMap::new();
@@ -1695,6 +1698,28 @@ impl Task {
self.emit_task();
}
fn emit_attention(&self, reason: AgentAttentionReason) {
let n = self.shared.attention_seq.fetch_add(1, Ordering::Relaxed);
let tag = match reason {
AgentAttentionReason::Finished => "finished",
AgentAttentionReason::Input => "input",
AgentAttentionReason::Failed => "failed",
};
self.shared.emit(AgentEvent::Attention {
task: self.id.clone(),
event_id: format!("{}:{tag}:{n}", self.id),
reason,
});
}
/// After NeedsInput + optional auto-approve: notify only when the user must still answer.
fn emit_attention_if_input_pending(&self) {
let waiting = !self.permissions.lock().is_empty() && self.state.lock().task.status == AgentStatus::NeedsInput;
if waiting {
self.emit_attention(AgentAttentionReason::Input);
}
}
fn persist(&self) {
// Held from snapshot to rename, so saves land in order and none follows a delete.
let deleted = self.deleted.lock();
@@ -1797,8 +1822,11 @@ impl Task {
}
match (next, result) {
(Some(queued), _) => prompt = queued.prompt,
(None, Ok(_)) => {
(None, Ok(stop)) => {
self.set_status(AgentStatus::Ready, None);
if stop != "cancelled" {
self.emit_attention(AgentAttentionReason::Finished);
}
return self.release_when_idle();
}
(None, Err(failure)) => return self.fail(failure),
@@ -1869,6 +1897,7 @@ impl Task {
}
None => self.set_status(AgentStatus::Failed, Some(failure.message)),
}
self.emit_attention(AgentAttentionReason::Failed);
}
/// Adds `prompt` to the running turn when the agent takes that; gives it back otherwise.
@@ -2500,6 +2529,7 @@ impl Task {
self.permissions.lock().insert(id, tx);
self.set_status(AgentStatus::NeedsInput, None);
self.approve_pending();
self.emit_attention_if_input_pending();
let answer = rx.recv().ok().flatten();
let answers = answer
@@ -2583,6 +2613,7 @@ impl Task {
});
self.permissions.lock().insert(id, tx);
self.set_status(AgentStatus::NeedsInput, None);
self.emit_attention_if_input_pending();
let reply = rx.recv().ok().flatten();
let (response, chosen) = elicitation::answer(&form, reply.as_deref());
self.settle(entry, chosen);
+15
Переглянути файл
@@ -5,6 +5,15 @@ use serde::{Deserialize, Serialize};
use specta::Type;
use std::collections::BTreeMap;
/// Why a task needs the user's attention (native / in-app notify).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum AgentAttentionReason {
Finished,
Input,
Failed,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum AgentStatus {
@@ -666,6 +675,12 @@ pub enum AgentEvent {
},
/// The installed or configured agent providers changed.
Providers,
/// The task needs attention once (finished turn, explicit input, or failure).
Attention {
task: String,
event_id: String,
reason: AgentAttentionReason,
},
}
pub use ide_core::settings::{AgentMcpServer, McpTransport};
+174
Переглянути файл
@@ -3619,3 +3619,177 @@ async fn ephemeral_tasks_deny_write_permissions() {
);
mgr.shutdown();
}
fn attention_reasons(events: &[AgentEvent]) -> Vec<AgentAttentionReason> {
events
.iter()
.filter_map(|e| match e {
AgentEvent::Attention { reason, .. } => Some(*reason),
_ => None,
})
.collect()
}
/// `wait_for(Ready/Failed/…)` can return after status is written but before the
/// following `emit_attention` runs on the agent thread — poll the sink instead.
async fn wait_for_attention(events: &Mutex<Vec<AgentEvent>>, reason: AgentAttentionReason) {
for _ in 0..500 {
if attention_reasons(&events.lock()).contains(&reason) {
return;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
panic!("never saw Attention::{reason:?}: {:?}", *events.lock());
}
#[tokio::test(flavor = "multi_thread")]
async fn attention_finished_not_cancelled() {
let tmp = tempfile::tempdir().unwrap();
let agent = Arc::new(FakeAgent::default());
let mgr = manager(tmp.path(), agent.clone());
let events = Arc::new(Mutex::new(Vec::<AgentEvent>::new()));
let sink = events.clone();
mgr.subscribe(Arc::new(move |e| sink.lock().push(e)));
let done = mgr
.create(NewAgentTask {
project_root: None,
prompt: text("again"),
provider: "claude".into(),
config: Vec::new(),
isolation: Isolation::Local,
base: None,
})
.await
.unwrap();
wait_for(&mgr, &done.id, AgentStatus::Ready).await;
wait_for_attention(&events, AgentAttentionReason::Finished).await;
events.lock().clear();
let cancelled = mgr
.create(NewAgentTask {
project_root: None,
prompt: text("wait"),
provider: "claude".into(),
config: Vec::new(),
isolation: Isolation::Local,
base: None,
})
.await
.unwrap();
wait_for(&mgr, &cancelled.id, AgentStatus::Running).await;
mgr.cancel(&cancelled.id, None).unwrap();
wait_for(&mgr, &cancelled.id, AgentStatus::Ready).await;
// Give a late Finished emission a chance; cancellation must not produce one.
tokio::time::sleep(Duration::from_millis(50)).await;
assert!(
!attention_reasons(&events.lock()).contains(&AgentAttentionReason::Finished),
"cancelled must not notify finished: {:?}",
*events.lock()
);
mgr.shutdown();
}
#[tokio::test(flavor = "multi_thread")]
async fn attention_failed() {
let tmp = tempfile::tempdir().unwrap();
let agent = Arc::new(FakeAgent {
request_error: Some((codes::INTERNAL_ERROR, "boom".into())),
auth_on_new: true,
..Default::default()
});
let mgr = manager(tmp.path(), agent);
let events = Arc::new(Mutex::new(Vec::<AgentEvent>::new()));
let sink = events.clone();
mgr.subscribe(Arc::new(move |e| sink.lock().push(e)));
let task = mgr
.create(NewAgentTask {
project_root: None,
prompt: text("Fix"),
provider: "claude".into(),
config: Vec::new(),
isolation: Isolation::Local,
base: None,
})
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Failed).await;
wait_for_attention(&events, AgentAttentionReason::Failed).await;
mgr.shutdown();
}
#[tokio::test(flavor = "multi_thread")]
async fn attention_input_not_auto_bypass() {
let tmp = tempfile::tempdir().unwrap();
let agent = Arc::new(FakeAgent::default());
let mgr = manager(tmp.path(), agent);
let events = Arc::new(Mutex::new(Vec::<AgentEvent>::new()));
let sink = events.clone();
mgr.subscribe(Arc::new(move |e| sink.lock().push(e)));
let asked = mgr
.create(NewAgentTask {
project_root: None,
prompt: text("Fix"),
provider: "claude".into(),
config: Vec::new(),
isolation: Isolation::Local,
base: None,
})
.await
.unwrap();
wait_for(&mgr, &asked.id, AgentStatus::NeedsInput).await;
wait_for_attention(&events, AgentAttentionReason::Input).await;
events.lock().clear();
mgr.cancel(&asked.id, None).unwrap();
wait_for(&mgr, &asked.id, AgentStatus::Ready).await;
let bypassed = mgr
.create(NewAgentTask {
project_root: None,
prompt: text("Fix"),
provider: "cursor".into(),
config: vec![AgentConfigChoice { id: config::CURSOR_APPROVAL.into(), value: "bypass".into() }],
isolation: Isolation::Local,
base: None,
})
.await
.unwrap();
wait_for(&mgr, &bypassed.id, AgentStatus::Ready).await;
tokio::time::sleep(Duration::from_millis(50)).await;
assert!(
!attention_reasons(&events.lock()).contains(&AgentAttentionReason::Input),
"auto-bypass must not notify input: {:?}",
*events.lock()
);
mgr.shutdown();
}
#[tokio::test(flavor = "multi_thread")]
async fn attention_not_emitted_on_restore() {
let tmp = tempfile::tempdir().unwrap();
let agent = Arc::new(FakeAgent::default());
let mgr = manager(tmp.path(), agent);
let task = mgr
.create(NewAgentTask {
project_root: None,
prompt: text("again"),
provider: "claude".into(),
config: Vec::new(),
isolation: Isolation::Local,
base: None,
})
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
mgr.shutdown();
let restored = manager(tmp.path(), Arc::new(FakeAgent::default()));
let events = Arc::new(Mutex::new(Vec::<AgentEvent>::new()));
let sink = events.clone();
let tasks = restored.subscribe(Arc::new(move |e| sink.lock().push(e)));
assert!(tasks.iter().any(|t| t.id == task.id));
tokio::time::sleep(Duration::from_millis(50)).await;
assert!(attention_reasons(&events.lock()).is_empty(), "snapshot restore must not re-notify: {:?}", *events.lock());
restored.shutdown();
}
+14 -1
Переглянути файл
@@ -71,6 +71,8 @@ pub struct Settings {
pub scopes: Vec<NamedScope>,
/// Appearance & Behavior › File Colors.
pub file_colors: FileColorSettings,
/// Database › Query Execution, Languages & Frameworks › SQL Resolution Scopes.
pub database: DatabaseSettings,
/// Plugin settings (`[contributes.settings]`): plugin id → its values by key.
#[specta(type = BTreeMap<String, BTreeMap<String, specta_typescript::Unknown>>)]
pub plugins: BTreeMap<String, serde_json::Map<String, serde_json::Value>>,
@@ -508,6 +510,7 @@ impl Default for Settings {
agent_security: AgentSecuritySettings::default(),
scopes: Vec::new(),
file_colors: FileColorSettings::default(),
database: DatabaseSettings::default(),
plugins: BTreeMap::new(),
}
}
@@ -647,13 +650,20 @@ impl Default for DateFormatSettings {
pub struct NotificationSettings {
pub balloons: bool,
pub sound: bool,
/// Mirror balloon notifications to the OS when no OpenIDEA window is focused.
#[serde(default = "default_true")]
pub system_notifications: bool,
/// Group id → display; groups not listed use their default.
pub groups: BTreeMap<String, NotificationGroupSettings>,
}
fn default_true() -> bool {
true
}
impl Default for NotificationSettings {
fn default() -> Self {
Self { balloons: true, sound: false, groups: BTreeMap::new() }
Self { balloons: true, sound: false, system_notifications: true, groups: BTreeMap::new() }
}
}
@@ -1337,6 +1347,9 @@ pub struct JavaSettings {
pub jdtls_vm_args: String,
/// Share one JDT LS across builds in an ordinary project window; other windows remain separate.
pub jdtls_shared: bool,
/// JDK homes added by hand (Platform Settings › SDKs › Add JDK from Disk…), listed with the
/// detected ones.
pub added_jdks: Vec<String>,
/// Build Tools › Maven.
pub maven: MavenSettings,
/// Build Tools › Gradle.
+24
Переглянути файл
@@ -241,6 +241,30 @@ impl Default for LogLevelColors {
}
}
/// Database settings: Query Execution and SQL Resolution Scopes.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct DatabaseSettings {
/// A console's result sets show under the statements that produced them, in the editor,
/// instead of in the Services view's result tabs.
pub in_editor_results: bool,
/// Languages & Frameworks › SQL Resolution Scopes: the data source SQL in a file or folder
/// resolves against (completion, inspections, navigation), most specific path first.
pub resolution_scopes: Vec<SqlResolutionScope>,
}
/// One row of SQL Resolution Scopes.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct SqlResolutionScope {
/// Project-relative file or folder, `/`-separated; empty for the whole project.
pub path: String,
/// Data source id.
pub data_source: String,
/// Schema unqualified names resolve in; empty for the data source's default.
pub schema: String,
}
/// Build, Execution, Deployment › Console.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
+6
Переглянути файл
@@ -120,6 +120,12 @@ fn builtin(adapter: &str) -> Option<DebuggerConfig> {
"stdio",
"Install GDB 14 or newer (apt install gdb, dnf install gdb, brew install gdb)",
),
"unity" => cfg(
"unity-debug",
&[],
"stdio",
"Install Unity Debugger in Settings > Language Servers, or configure the unity-debug tool path",
),
"rdbg" => cfg("rdbg", &["-O", "--port", PORT_PLACEHOLDER, "-c"], "tcp", "gem install debug"),
// A jdtls bundle: the session is started through jdtls and reached via `debugServer`.
"java-debug" => cfg(
+1
Переглянути файл
@@ -12,6 +12,7 @@ use std::path::Path;
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum AttachKind {
Unity,
Java,
Node,
Python,
+25 -3
Переглянути файл
@@ -19,6 +19,7 @@ mod jvm_memory;
pub mod kotlin;
pub mod kotlin_lsp;
mod session;
pub mod unity;
use adapter::{AdapterLauncher, AdapterSpec, ProcessLauncher};
use connection::{Connection, DapError};
@@ -1121,6 +1122,16 @@ impl DebugManager {
let _ = tokio::time::timeout(INIT_TIMEOUT, initialized.wait_for(|v| *v)).await;
}
if s.adapter == "unity" {
if launch_result.is_none()
&& let Some(launch) = launch.as_mut()
{
launch.await?;
launch_result = Some(());
}
unity::wait_for_threads(s).await?;
}
// A fresh adapter has no breakpoints, so a file with none enabled needs no request; the
// others go out together, as VS Code sends them, instead of one round trip per file.
let (files, idle): (Vec<_>, Vec<_>) = self
@@ -1202,6 +1213,10 @@ impl DebugManager {
if let Some(link) = s.jdwp_link.lock().as_ref() {
link.release();
}
if s.adapter == "unity" {
unity::settle_startup(s).await;
s.emit(ide_core::event::DebugEvent::Initialized);
}
Ok(())
}
@@ -1229,11 +1244,18 @@ impl DebugManager {
// rdbg's terminate exits the Ruby process without terminating its children.
let graceful =
terminate && s.request == "launch" && s.adapter != "rdbg" && s.supports("supportsTerminateRequest");
// A program suspended in the debugger cannot act on SIGTERM, and on macOS not even die of
// SIGKILL while the debugger holds it: it is killed (with what it started) and the adapter
// is told to end it. A killed program has no shutdown output to wait for.
let killed = own_terminate && !graceful && s.suspended.get();
if killed {
crate::session::signal_debuggee(s, true).await;
}
if !s.conn.is_closed() {
if graceful {
let _ = s.conn.request_timeout("terminate", json!({ "restart": false }), SHUTDOWN_TIMEOUT).await;
}
if !graceful && !own_terminate {
if !graceful && (!own_terminate || killed) {
let _ = s
.conn
.request_timeout(
@@ -1244,7 +1266,7 @@ impl DebugManager {
.await;
}
}
if own_terminate && !graceful {
if own_terminate && !graceful && !killed {
// Signal before anything else: waiting on a request the adapter may not answer
// would delay the shutdown the console is supposed to show.
crate::session::signal_debuggee(s, false).await;
@@ -1263,7 +1285,7 @@ impl DebugManager {
// lets Run start again into an occupied port, so wait for the program first — with the
// connection still open, so a second Stop can find the session and kill it.
crate::session::wait_for_debuggee(s, terminate).await;
if terminate && s.request == "launch" {
if terminate && s.request == "launch" && !killed {
// The adapter reports `terminated` only after it has drained the program's console
// (java-debug waits up to 5 s for the pump): closing before that drops the last
// shutdown lines from the console.
+15 -2
Переглянути файл
@@ -17,7 +17,7 @@ use std::process::Stdio;
use std::sync::Arc;
use std::sync::Weak;
use std::sync::atomic::{AtomicBool, AtomicI64, Ordering};
use std::time::Duration;
use std::time::{Duration, Instant};
use tokio::io::{AsyncRead, AsyncReadExt};
use tokio::process::Child;
use tokio::sync::{mpsc, watch};
@@ -116,6 +116,7 @@ pub(crate) struct Session {
pub jvm_memory: tokio::sync::Mutex<crate::JvmMemoryState>,
/// Used only by a kotlin-lsp session: see [`Session::kotlin_lsp_quirks`].
pub(crate) quirks: kotlin_lsp::Quirks,
pub(crate) unity_startup_activity: Mutex<Instant>,
}
/// Which threads of the program are suspended: each from its `stopped` event until a
@@ -270,6 +271,7 @@ impl Session {
kotlin_mirror: Mutex::new(None),
jvm_memory: tokio::sync::Mutex::default(),
quirks: kotlin_lsp::Quirks::default(),
unity_startup_activity: Mutex::new(Instant::now()),
}
}
@@ -716,6 +718,15 @@ pub(crate) async fn event_loop(
}
async fn on_event(mgr: &Arc<DebugManager>, s: &Arc<Session>, event: &str, mut body: Value) {
if s.adapter == "unity"
&& event == "output"
&& body
.get("output")
.and_then(Value::as_str)
.is_some_and(|text| text.starts_with("Loaded assembly:") || text.starts_with("Resolved pending breakpoint"))
{
*s.unity_startup_activity.lock() = Instant::now();
}
if let Some(mirror) = s.kotlin_mirror.lock().as_ref() {
mirror.translate(&mut body);
}
@@ -724,7 +735,9 @@ async fn on_event(mgr: &Arc<DebugManager>, s: &Arc<Session>, event: &str, mut bo
match event {
"initialized" => {
s.initialized.send_replace(true);
s.emit(DebugEvent::Initialized);
if s.adapter != "unity" {
s.emit(DebugEvent::Initialized);
}
}
"stopped" => {
let all = body.get("allThreadsStopped").and_then(Value::as_bool).unwrap_or(false);
+93 -2
Переглянути файл
@@ -158,6 +158,7 @@ struct Script {
/// `launch`, and a `configurationDone` sent while it runs is refused with `notStopped`.
gdb15_starts_at_launch: bool,
launch_after_configuration: bool,
empty_thread_responses: usize,
/// Requests of the adapter's own (js-debug's `setCustomBreakpoints`…) answered with an empty body.
accept: &'static [&'static str],
/// Requests of the adapter's own answered with a body and followed by events.
@@ -198,6 +199,7 @@ impl Default for Script {
close_during_startup: false,
gdb15_starts_at_launch: false,
launch_after_configuration: false,
empty_thread_responses: 0,
accept: &[],
custom: None,
}
@@ -244,6 +246,8 @@ async fn fake_adapter<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(stream
let mut held: Vec<Value> = Vec::new();
let mut stopped = false;
let mut running = false;
let mut thread_requests = 0;
let mut unity = false;
macro_rules! send {
($v:expr) => {{
let mut v: Value = $v;
@@ -268,13 +272,14 @@ async fn fake_adapter<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(stream
}
match msg["command"].as_str().unwrap_or_default() {
"initialize" => {
unity = msg["arguments"]["adapterID"] == "unity";
if let Some(delay) = script.delay_initialize {
tokio::time::sleep(delay).await;
}
ok!(
msg,
json!({
"supportsConfigurationDoneRequest": true,
"supportsConfigurationDoneRequest": !unity,
"supportsCompletionsRequest": true,
"supportsTerminateRequest": script.supports_terminate,
"supportsSetVariable": true,
@@ -293,8 +298,15 @@ async fn fake_adapter<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(stream
// defers it sends late).
send!(json!({"type": "event", "event": "initialized"}));
}
if unity {
send!(json!({"type": "event", "event": "initialized"}));
}
}
"launch" | "attach" => {
if unity {
ok!(msg, Value::Null);
continue;
}
if script.gdb15_starts_at_launch {
// GDB 15 starts the program here and answers `launch` right away.
running = true;
@@ -448,7 +460,14 @@ async fn fake_adapter<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(stream
tokio::time::sleep(Duration::from_millis(50)).await;
ok!(msg, json!({"threads": [{"id": 1, "name": "\"main\"@1"}]}));
}
"threads" => ok!(msg, json!({"threads": [{"id": 1, "name": "MainThread"}]})),
"threads" => {
thread_requests += 1;
if thread_requests <= script.empty_thread_responses {
ok!(msg, json!({"threads": []}));
} else {
ok!(msg, json!({"threads": [{"id": 1, "name": "MainThread"}]}));
}
}
"stackTrace" => ok!(
msg,
json!({"stackFrames": [
@@ -508,6 +527,14 @@ async fn fake_adapter<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(stream
}
}
"disconnect" => {
// Like Delve: the adapter ends the program it launched.
#[cfg(unix)]
if msg["arguments"]["terminateDebuggee"] == true
&& let Some(pid) = script.debuggee_pid
{
// SAFETY: plain syscall on the test's own child process.
unsafe { libc::kill(pid as i32, libc::SIGKILL) };
}
ok!(msg, Value::Null);
let _ = w.lock().await.shutdown().await;
break;
@@ -878,6 +905,32 @@ async fn stop_terminates_and_disconnects() {
assert!(h.manager.threads(id).await.is_err());
}
#[tokio::test]
async fn unity_attach_waits_for_mono_and_disconnects_without_terminating_editor() {
let h = harness(Script { empty_thread_responses: 2, ..Script::default() });
h.manager.set_breakpoints(PathBuf::from("/p/a.cs"), vec![bp(4)]).await.unwrap();
let start = h.start(LaunchConfig {
adapter: "unity".into(),
request: "attach".into(),
program: None,
extra_json: Some(json!({ "name": "Unity Editor (42)", "__exceptionOptions": [] }).to_string()),
..config()
});
let ready = async {
h.wait_event(|e| matches!(e, DebugEvent::Initialized)).await;
let commands = h.commands();
let before_breakpoints = commands.iter().take_while(|c| *c != "setBreakpoints");
assert!(before_breakpoints.filter(|c| *c == "threads").count() >= 3);
assert!(commands.iter().any(|c| c == "setBreakpoints"));
};
let (id, ()) = tokio::join!(start, ready);
let id = id.unwrap();
assert_eq!(h.request("attach")["arguments"]["name"], "Unity Editor (42)");
h.manager.stop(id).await.unwrap();
assert!(!h.commands().iter().any(|c| c == "launch" || c == "terminate"));
assert_eq!(h.request("disconnect")["arguments"]["terminateDebuggee"], false);
}
#[tokio::test]
async fn concurrent_sessions_are_independent() {
let h = harness(Script::default());
@@ -2274,6 +2327,44 @@ async fn stop_waits_for_the_launched_program_to_exit() {
h.wait_event(|e| matches!(e, DebugEvent::Terminated)).await;
}
/// Delve and other adapters without `terminate`: a program stopped at a breakpoint cannot
/// handle the SIGTERM Stop sends, so Stop has the adapter end it instead of waiting out the grace period.
#[cfg(unix)]
#[tokio::test]
async fn stop_kills_a_program_suspended_at_a_breakpoint_at_once() {
let mut child = std::process::Command::new("python3")
.args(["-c", "import signal,time; signal.signal(signal.SIGTERM, signal.SIG_IGN); time.sleep(30)"])
.spawn()
.unwrap();
let pid = child.id();
let exited = Arc::new(AtomicBool::new(false));
{
let exited = exited.clone();
std::thread::spawn(move || {
let _ = child.wait();
exited.store(true, Ordering::Release);
});
}
let h = harness(Script { debuggee_pid: Some(pid), supports_terminate: false, ..Default::default() });
let id = h.start(config()).await.unwrap();
h.wait_event(|e| matches!(e, DebugEvent::Stopped { .. })).await;
let session = h.manager.session(id).unwrap();
while session.debuggee_pid.load(Ordering::Acquire) != i64::from(pid) {
tokio::time::sleep(Duration::from_millis(10)).await;
}
tokio::time::sleep(Duration::from_millis(200)).await; // let the program install its trap
let started = Instant::now();
h.manager.stop(id).await.unwrap();
let elapsed = started.elapsed();
assert!(elapsed < Duration::from_secs(3), "stop waited {elapsed:?} for a suspended program");
assert_eq!(h.request("disconnect")["arguments"]["terminateDebuggee"], true);
let deadline = Instant::now() + Duration::from_secs(2);
while !exited.load(Ordering::Acquire) {
assert!(Instant::now() < deadline, "the suspended program was left running");
tokio::time::sleep(Duration::from_millis(10)).await;
}
}
#[cfg(unix)]
#[tokio::test]
async fn a_second_stop_kills_the_program_instead_of_waiting() {
+187
Переглянути файл
@@ -0,0 +1,187 @@
//! Lists the Unity Editors to attach to through UnityDebug's discovery (`unity-debug list`).
use crate::{
adapter,
attach::{AttachKind, AttachableProcess},
};
use ide_core::{IdeError, IdeResult};
use std::{path::PathBuf, process::Stdio, time::Duration};
/// Waits until Mono reports its threads.
pub(crate) async fn wait_for_threads(session: &crate::session::Session) -> IdeResult<()> {
tokio::time::timeout(Duration::from_secs(20), async {
loop {
let body = session.conn.request_timeout("threads", serde_json::json!({}), Duration::from_secs(5)).await?;
if body.get("threads").and_then(serde_json::Value::as_array).is_some_and(|t| !t.is_empty()) {
return Ok(());
}
tokio::time::sleep(Duration::from_millis(100)).await;
}
})
.await
.map_err(|_| {
IdeError::unavailable(
"Unity debugger did not become ready. Enable Editor Attaching and Debug Mode in Unity, then retry.",
)
})?
}
// Mono binds breakpoints asynchronously and resumes threads itself during startup: wait for that burst to end.
pub(crate) async fn settle_startup(session: &crate::session::Session) {
*session.unity_startup_activity.lock() = std::time::Instant::now();
let _ = tokio::time::timeout(Duration::from_secs(3), async {
while session.unity_startup_activity.lock().elapsed() < Duration::from_secs(1) {
tokio::time::sleep(Duration::from_millis(50)).await;
}
})
.await;
}
pub fn require_runtime(cwd: &std::path::Path) -> IdeResult<()> {
if cfg!(unix) && ide_core::tool_path::find_command("mono", &ide_core::tool_path::search_path(), cwd).is_none() {
return Err(IdeError::unavailable(
"Unity Debugger requires Mono. Install Mono, make sure mono is on PATH, then refresh the Unity process list.",
));
}
Ok(())
}
const NOT_INSTALLED: &str = "debug adapter `unity` not found. Install Unity Debugger in Settings > Language Servers or configure the unity-debug tool path";
pub async fn editors(command: Option<String>, cwd: PathBuf) -> IdeResult<Vec<AttachableProcess>> {
require_runtime(&cwd)?;
let command = command.unwrap_or_else(|| "unity-debug".into());
let lookup = command.clone();
let dir = cwd.clone();
let binary = tokio::task::spawn_blocking(move || adapter::resolve_binary(&lookup, &dir))
.await
.map_err(|e| IdeError::internal(e.to_string()))?
.ok_or_else(|| IdeError::unavailable(NOT_INSTALLED))?;
let mut cmd = tokio::process::Command::new(binary);
ide_core::process::prepare(cmd.as_std_mut());
cmd.arg("list")
.current_dir(&cwd)
.env("PATH", ide_core::tool_path::search_path())
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.kill_on_drop(true);
let out = tokio::time::timeout(Duration::from_secs(15), cmd.output())
.await
.map_err(|_| {
IdeError::unavailable("Unity process discovery timed out. Check that Unity Editor is responsive.")
})?
.map_err(|e| IdeError::unavailable(format!("Cannot start Unity process discovery: {e}")))?;
if !out.status.success() {
return Err(IdeError::unavailable(format!(
"Unity process discovery failed: {}",
String::from_utf8_lossy(&out.stderr).trim()
)));
}
let mut rows = parse_editors(&String::from_utf8_lossy(&out.stdout));
#[cfg(windows)]
if !rows.is_empty() {
match editor_process_ids() {
Ok(editors) => rows.retain(|p| editors.contains(&p.pid)),
Err(error) => tracing::warn!(%error, "Unity process filtering failed; using adapter discovery results"),
}
}
// The Editor of the open project comes first; the user picks which one to attach to.
let path = cwd.join("Library/EditorInstance.json");
let pid = std::fs::File::open(path).ok().and_then(|file| {
use std::io::Read;
let json: serde_json::Value = serde_json::from_reader(file.take(4096)).ok()?;
json.get("process_id")?.as_u64().and_then(|n| u32::try_from(n).ok())
});
for row in &mut rows {
if Some(row.pid) == pid {
row.command_line = cwd.to_string_lossy().into_owned();
}
}
rows.sort_by_key(|p| Some(p.pid) != pid);
Ok(rows)
}
#[cfg(windows)]
fn editor_process_ids() -> IdeResult<std::collections::HashSet<u32>> {
use std::collections::HashMap;
use windows_sys::Win32::{
Foundation::{CloseHandle, INVALID_HANDLE_VALUE},
System::Diagnostics::ToolHelp::{
CreateToolhelp32Snapshot, PROCESSENTRY32W, Process32FirstW, Process32NextW, TH32CS_SNAPPROCESS,
},
};
let mut unity = HashMap::new();
// The adapter also finds the asset import worker processes: keep the Unity processes whose parent isn't Unity.
unsafe {
let snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if snapshot == INVALID_HANDLE_VALUE {
return Err(std::io::Error::last_os_error().into());
}
let mut entry = PROCESSENTRY32W { dwSize: std::mem::size_of::<PROCESSENTRY32W>() as u32, ..std::mem::zeroed() };
let mut found = Process32FirstW(snapshot, &mut entry);
if found == 0 {
let error = std::io::Error::last_os_error();
CloseHandle(snapshot);
return Err(error.into());
}
while found != 0 {
let end = entry.szExeFile.iter().position(|c| *c == 0).unwrap_or(entry.szExeFile.len());
let name = String::from_utf16_lossy(&entry.szExeFile[..end]);
if name.eq_ignore_ascii_case("Unity.exe") {
unity.insert(entry.th32ProcessID, entry.th32ParentProcessID);
}
found = Process32NextW(snapshot, &mut entry);
}
CloseHandle(snapshot);
}
Ok(unity.iter().filter_map(|(&pid, parent)| (!unity.contains_key(parent)).then_some(pid)).collect())
}
pub fn parse_editors(output: &str) -> Vec<AttachableProcess> {
let mut editors = Vec::new();
for line in output.lines() {
let line = line.trim().trim_start_matches('\u{feff}');
if !line.starts_with("Unity Editor (") {
continue;
}
// 3.0.1 prints `Unity Editor (Unity) (123)`; later versions append the project name.
let Some((name, pid, project)) = line.match_indices(" (").find_map(|(at, _)| {
let (id, project) = line[at + 2..].split_once(')')?;
let pid = id.parse::<u32>().ok().filter(|n| *n > 0)?;
Some((&line[..at], pid, project))
}) else {
continue;
};
if editors.iter().any(|p: &AttachableProcess| p.pid == pid) {
continue;
}
editors.push(AttachableProcess {
pid,
name: "Unity Editor".into(),
command_line: if project.trim().is_empty() { name.into() } else { project.trim().into() },
kind: AttachKind::Unity,
adapter: "unity".into(),
host: None,
port: None,
});
}
editors.sort_by(|a, b| a.command_line.cmp(&b.command_line).then(a.pid.cmp(&b.pid)));
editors
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_editor_ids_and_projects_without_mistaking_players_or_logs_for_editors() {
let rows = parse_editors(
"\u{feff}Unity Editor (Unity) (42) Game (Test)\r\nUnity Editor (7) My Game\nUnity Editor (42) duplicate\nWindowsPlayer (123) Player\nUnity Hub (44)\nUnity Editor (invalid)\nUnity Editor (0)\nlog text",
);
assert_eq!(rows.len(), 2);
assert_eq!((rows[0].pid, rows[0].command_line.as_str()), (42, "Game (Test)"));
assert_eq!(rows[1].pid, 7);
assert!(rows.iter().all(|p| p.kind == AttachKind::Unity && p.adapter == "unity"));
}
}
+187
Переглянути файл
@@ -0,0 +1,187 @@
//! Attaches to a real Unity Editor, with its own temporary project and Editor instance.
//! OPENIDEA_UNITY_EDITOR=<Unity.exe> OPENIDEA_UNITY_ADAPTER=<UnityDebug.exe>
//! cargo test -p ide-dap --test unity -- --ignored --nocapture
use ide_core::{IdeEvent, SharedSink, event::DebugEvent};
use ide_dap::{Breakpoint, DebugManager, LaunchConfig, SessionOwner, StepKind};
use ide_language::LanguageRegistry;
use parking_lot::Mutex;
use std::{collections::BTreeMap, path::PathBuf, sync::Arc, time::Duration};
const SCRIPT: &str = r#"using System.IO;
using UnityEditor;
using UnityEngine;
[InitializeOnLoad]
public static class OpenIdeaAttachProbe
{
static readonly string Root = Directory.GetParent(Application.dataPath).FullName;
static OpenIdeaAttachProbe()
{
EditorApplication.update += Tick;
}
static void Tick()
{
if (EditorApplication.isCompiling || EditorApplication.isUpdating) return;
if (!File.Exists(Path.Combine(Root, "ready")))
File.WriteAllText(Path.Combine(Root, "ready"), System.Diagnostics.Process.GetCurrentProcess().Id.ToString());
if (File.Exists(Path.Combine(Root, "exit"))) { EditorApplication.Exit(0); return; }
if (!File.Exists(Path.Combine(Root, "go"))) return;
File.Delete(Path.Combine(Root, "go"));
int result = Hit(41);
File.WriteAllText(Path.Combine(Root, "done"), result.ToString());
}
static int Hit(int seed)
{
int answer = seed + 1;
return answer;
}
}
"#;
async fn stopped(events: &Mutex<Vec<IdeEvent>>, expected_reason: &str) -> i64 {
for _ in 0..600 {
if let Some(thread) = events.lock().iter().find_map(|e| match e {
IdeEvent::Debug { event: DebugEvent::Stopped { thread_id, reason, .. }, .. }
if reason == expected_reason =>
{
Some(*thread_id)
}
_ => None,
}) {
return thread;
}
tokio::time::sleep(Duration::from_millis(50)).await;
}
let events = events.lock();
panic!("No breakpoint/step event: {:?}", &events[events.len().saturating_sub(16)..]);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[ignore = "needs a licensed Unity Editor and the Unity DAP adapter"]
async fn real_editor_attach_breakpoint_step_variables_and_detach() {
let editor = std::env::var("OPENIDEA_UNITY_EDITOR").expect("OPENIDEA_UNITY_EDITOR");
let adapter = std::env::var("OPENIDEA_UNITY_ADAPTER").expect("OPENIDEA_UNITY_ADAPTER");
let target = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../target").canonicalize().unwrap();
// Keep the Editor log for diagnosing a failure.
let root = tempfile::Builder::new().prefix("unity-dap-smoke-").tempdir_in(target).unwrap().keep();
let root = root.to_string_lossy().trim_start_matches(r"\\?\").replace('\\', "/");
let root = PathBuf::from(root);
std::fs::create_dir_all(root.join("Assets/Editor")).unwrap();
std::fs::create_dir(root.join("ProjectSettings")).unwrap();
std::fs::create_dir(root.join("Packages")).unwrap();
std::fs::write(
root.join("ProjectSettings/ProjectVersion.txt"),
format!(
"m_EditorVersion: {}\n",
PathBuf::from(&editor).ancestors().nth(2).and_then(|p| p.file_name()).unwrap().to_string_lossy()
),
)
.unwrap();
std::fs::write(root.join("Packages/manifest.json"), r#"{"dependencies":{}}"#).unwrap();
let source = root.join("Assets/Editor/OpenIdeaAttachProbe.cs");
std::fs::write(&source, SCRIPT).unwrap();
let mut command = tokio::process::Command::new(&editor);
ide_core::process::prepare(command.as_std_mut());
// The test project has no packages: skip the package manager.
command
.args(["-batchmode", "-nographics", "-noUpm", "-debugCodeOptimization", "-projectPath"])
.arg(&root)
.arg("-logFile")
.arg(root.join("Editor.log"))
.current_dir(&root)
.kill_on_drop(true);
let mut child = command.spawn().unwrap();
let pid = child.id().unwrap();
eprintln!("Isolated Unity pid {pid}, project {}", root.display());
for _ in 0..1200 {
if root.join("ready").exists() {
break;
}
assert!(child.try_wait().unwrap().is_none(), "Unity exited; inspect {}/Editor.log", root.display());
tokio::time::sleep(Duration::from_millis(100)).await;
}
assert!(root.join("ready").exists(), "Editor failed to load the test script");
let rows = ide_dap::unity::editors(Some(adapter.clone()), root.clone()).await.unwrap();
assert!(rows.iter().any(|p| p.pid == pid), "test Editor absent: {rows:?}");
let events: Arc<Mutex<Vec<IdeEvent>>> = Arc::default();
let saved = events.clone();
let sink: SharedSink = Arc::new(move |event| saved.lock().push(event));
let manager = DebugManager::new(Arc::new(LanguageRegistry::from_configs(Vec::new())));
let line = SCRIPT.lines().position(|l| l.contains("int answer =")).unwrap() as u32;
manager
.set_breakpoints(
source.clone(),
vec![Breakpoint { line, condition: None, hit_condition: None, log_message: None, enabled: true }],
)
.await
.unwrap();
let start = || {
manager.start_with(
LaunchConfig {
name: format!("Unity Editor ({pid})"),
adapter: "unity".into(),
request: "attach".into(),
program: None,
args: vec![],
cwd: Some(root.clone().into()),
env: BTreeMap::new(),
extra_json: Some(
serde_json::json!({ "name": format!("Unity Editor ({pid})"), "__exceptionOptions": [] })
.to_string(),
),
},
SessionOwner::new("smoke", sink.clone()),
|_| Some(adapter.clone()),
)
};
let session = start().await.unwrap();
eprintln!("Attached; breakpoint states: {:?}", manager.breakpoint_states(&source));
// Mono is ready to run once the start returns.
assert!(!manager.threads(session).await.unwrap().is_empty());
std::fs::write(root.join("go"), "").unwrap();
let thread = stopped(&events, "breakpoint").await;
let frames = manager.stack_trace(session, thread).await.unwrap();
assert!(!frames.is_empty(), "Empty breakpoint stack: {:?}", events.lock());
assert_eq!(frames[0].line, line);
let scopes = manager.scopes(session, frames[0].id).await.unwrap();
let variables = manager.variables(session, scopes[0].variables_reference).await.unwrap();
assert!(variables.iter().any(|v| v.name == "seed" && v.value == "41"), "{variables:?}");
assert_eq!(manager.evaluate(session, Some(frames[0].id), "seed + 1".into()).await.unwrap().value, "42");
events.lock().clear();
manager.step(session, thread, StepKind::Over).await.unwrap();
let thread = stopped(&events, "step").await;
let frames = manager.stack_trace(session, thread).await.unwrap();
assert!(!frames.is_empty(), "Empty step stack: {:?}", events.lock());
assert!(frames[0].line > line);
// Detaching at a breakpoint resumes the Editor.
manager.stop(session).await.unwrap();
verify_resumed(&root, &mut child).await;
// Attaching again to the same Editor hits the existing breakpoint.
std::fs::remove_file(root.join("done")).unwrap();
events.lock().clear();
let session = start().await.unwrap_or_else(|error| {
let events = events.lock();
panic!("Reattach failed: {error:?}, recent events: {:?}", &events[events.len().saturating_sub(12)..]);
});
std::fs::write(root.join("go"), "").unwrap();
let thread = stopped(&events, "breakpoint").await;
assert_eq!(manager.stack_trace(session, thread).await.unwrap()[0].line, line);
manager.stop(session).await.unwrap();
verify_resumed(&root, &mut child).await;
std::fs::write(root.join("exit"), "").unwrap();
assert!(tokio::time::timeout(Duration::from_secs(30), child.wait()).await.unwrap().unwrap().success());
eprintln!("Verified discovery, attachment, breakpoint, locals, evaluation, step, detach and reattachment");
}
async fn verify_resumed(root: &std::path::Path, child: &mut tokio::process::Child) {
let path = root.join("done");
for _ in 0..100 {
assert!(child.try_wait().unwrap().is_none(), "disconnect terminated the Unity Editor");
if std::fs::read_to_string(&path).is_ok_and(|text| text == "42") {
return;
}
tokio::time::sleep(Duration::from_millis(100)).await;
}
panic!("Unity did not complete the script after disconnect: {:?}", std::fs::read_to_string(path));
}
+9
Переглянути файл
@@ -190,6 +190,7 @@ impl Host {
open_locks: Default::default(),
};
host.apply_proxy();
host.apply_added_jdks();
ops::agent::move_user_mcp_values(&host);
host
}
@@ -564,3 +565,11 @@ mod tests {
host.close_project("main");
}
}
impl Host {
/// Lists the JDKs added by hand (global Settings › SDKs) with the detected ones.
pub fn apply_added_jdks(&self) {
let homes = self.global_settings.effective().languages.java.added_jdks;
ide_sdk::java::set_added_jdks(homes.into_iter().map(PathBuf::from));
}
}
+45
Переглянути файл
@@ -12,6 +12,25 @@ use std::path::PathBuf;
/// Starts a session owned by this window: its events (and those of child sessions) go here only.
pub async fn debug_start(host: &Host, window: &str, config: LaunchConfig) -> IdeResult<DebugSessionId> {
host.require_trust(window)?;
let unity_pid = if config.adapter == "unity" {
if config.request != "attach" {
return Err(ide_core::IdeError::invalid("Unity debugging only supports attachment to a running Editor"));
}
let arguments = launch_arguments(&config)?;
let pid = arguments["name"]
.as_str()
.and_then(|name| name.strip_prefix("Unity Editor ("))
.and_then(|name| name.strip_suffix(')'))
.and_then(|pid| pid.parse::<u32>().ok());
if let Some(pid) = pid {
require_unity_editor(pid)?;
}
let cwd = config.cwd.as_ref().map(|path| path.as_ref()).unwrap_or_else(|| std::path::Path::new("."));
unity::require_runtime(cwd)?;
pid
} else {
None
};
let mut config = match_java_debug_encoding(start_java_attach_listener(config, cfg!(windows)), cfg!(windows));
if config.adapter == "debugpy"
&& config.request == "launch"
@@ -100,12 +119,26 @@ pub async fn debug_start(host: &Host, window: &str, config: LaunchConfig) -> Ide
let server_port = debug_server_port(&config);
let result = host.debugger.start_with(config, owner, custom).await;
flush_output();
if result.is_err()
&& let Some(pid) = unity_pid
{
require_unity_editor(pid)?;
}
if let (Ok(id), Some(port)) = (&result, server_port) {
attach_jvm_inspector(host, window, *id, port);
}
result
}
fn require_unity_editor(pid: u32) -> IdeResult<()> {
if !ide_core::process::process_alive(pid) {
return Err(ide_core::IdeError::unavailable(format!(
"Unity Editor (PID {pid}) is no longer running. Refresh the Unity process list and select a running Editor."
)));
}
Ok(())
}
/// The port of the java-debug server this machine's jdtls started; `debugServer` as `host:port`
/// names an adapter on another machine, whose jdtls is not ours to ask.
fn debug_server_port(config: &LaunchConfig) -> Option<u16> {
@@ -460,6 +493,17 @@ pub async fn debug_free_port(host: &Host, window: &str) -> IdeResult<u16> {
ide_dap::adapter::free_port().map_err(ide_core::IdeError::from)
}
pub async fn debug_unity_processes(host: &Host, window: &str) -> IdeResult<Vec<attach::AttachableProcess>> {
host.require_trust(window)?;
let project = host.project(window)?;
if ide_workspace::unity::detect(&project.root).is_none() {
return Err(ide_core::IdeError::invalid("Open a Unity project before attaching to the Editor"));
}
let command = ide_sdk::apply::tool_command(&project.root, &project.settings.effective(), "unity-debug")
.map(|p| p.to_string_lossy().into_owned());
unity::editors(command, project.root.clone()).await
}
/// Remote JVM Debug in listen mode: waits (cancellable through `request`) for the remote
/// JVM to connect to `host:port`; returns the loopback port java-debug attaches to.
pub async fn debug_listen_for_jvm(
@@ -664,6 +708,7 @@ pub(crate) fn register(d: &mut Dispatcher) {
});
d.add("debug_attachable_processes", |c| async move { debug_attachable_processes(&c.host, &c.window).await });
d.add("debug_free_port", |c| async move { debug_free_port(&c.host, &c.window).await });
d.add("debug_unity_processes", |c| async move { debug_unity_processes(&c.host, &c.window).await });
d.add("debug_listen_for_jvm", |c| async move {
debug_listen_for_jvm(&c.host, &c.window, c.arg("request")?, c.arg("host")?, c.arg("port")?).await
});
+3
Переглянути файл
@@ -232,6 +232,9 @@ pub fn set_settings(
if key == "ssh" || key.starts_with("ssh.") {
host.ssh.set_configs(host.global_settings.effective().ssh.configs);
}
if key == "languages" || key == "languages.java" || key.starts_with("languages.java.addedJdks") {
host.apply_added_jdks();
}
if is_proxy {
host.apply_proxy();
}
+14
Переглянути файл
@@ -37,6 +37,9 @@ pub struct ProjectInterpreter {
pub async fn sdk_detect(host: &Host, window: &str, kind: SdkKind) -> IdeResult<Vec<Sdk>> {
host.require_trust(window)?;
let project = host.project(window).ok();
if kind == SdkKind::Jdk {
host.apply_added_jdks();
}
let root = project.as_ref().map(|p| p.root.clone());
// The interpreter the project uses is a choice even where detection doesn't look (a
// virtualenv in a subfolder, one picked by path), so it shows by name and version.
@@ -372,9 +375,20 @@ pub async fn sdk_python_pip(
result?
}
/// The JDK whose home is `path` (a macOS bundle too), as the SDK list shows it; `None` when
/// `path` is no JDK home (Add JDK from Disk…).
pub async fn sdk_jdk_at(path: String) -> IdeResult<Option<Sdk>> {
tokio::task::spawn_blocking(move || {
ide_sdk::java::jdk_at(std::path::Path::new(&path)).map(|j| ide_sdk::jdk_sdk(&j))
})
.await
.map_err(join_err)
}
/// Commands of this module the remote server answers.
pub(crate) fn register(d: &mut Dispatcher) {
d.add("sdk_detect", |c| async move { sdk_detect(&c.host, &c.window, c.arg("kind")?).await });
d.add("sdk_jdk_at", |c| async move { sdk_jdk_at(c.arg("path")?).await });
d.add(
"sdk_python_project_interpreters",
|c| async move { sdk_python_project_interpreters(&c.host, &c.window).await },
+8 -3
Переглянути файл
@@ -677,9 +677,14 @@ impl Shared {
}
let previous =
self.setting_snapshots.lock().insert((client.map(str::to_owned), pkg.id().into()), current.clone());
previous
.map(|old| current.into_iter().filter(|(k, v)| old.get(k) != Some(v)).map(|(k, _)| k).collect())
.unwrap_or_default()
match previous {
// First contact since the plugin loaded (fresh install, update,
// re-enable): hand over every current key, so the synthetic
// post-install `settings-changed` wakes the plugin instead of being
// dropped for having no diff yet.
None => current.into_keys().collect(),
Some(old) => current.into_iter().filter(|(k, v)| old.get(k) != Some(v)).map(|(k, _)| k).collect(),
}
}
pub fn status_snapshot(&self, client: &str) -> Vec<super::PluginStatusItem> {
+39 -2
Переглянути файл
@@ -144,7 +144,7 @@ impl Host {
let lsp = LspManager::new(root.clone(), languages.clone(), sink.clone());
crate::plugins::injections::configure_lsp(&lsp);
lsp.set_execution_allowed(trusted.load(Ordering::Acquire));
lsp.set_content_roots(extra_roots.clone());
lsp.set_content_roots(language_server_roots(&root, extra_roots.clone()));
lsp.set_jdtls_import_roots(ide_build::maven_external_roots(
&root,
&settings.effective().languages.java.maven.linked_projects,
@@ -1224,7 +1224,7 @@ impl Project {
return;
}
let (roots, excludes) = (self.content_roots(), self.exclude_globs());
self.lsp.set_content_roots(roots.clone());
self.lsp.set_content_roots(language_server_roots(&self.root, roots.clone()));
self.lsp.set_jdtls_import_roots(ide_build::maven_external_roots(
&self.root,
&self.settings.effective().languages.java.maven.linked_projects,
@@ -1369,6 +1369,22 @@ fn content_roots(settings: &ide_core::settings::Settings, root: &Path, build_cac
extra_content_roots(settings, root, build_cache)
}
/// The content roots plus the projects attached inside this one. The index covers those
/// already, but each is a project of its own (a git worktree under the project, a nested
/// Cargo workspace), so its files get a language server rooted there, not at this root.
fn language_server_roots(root: &Path, mut roots: Vec<PathBuf>) -> Vec<PathBuf> {
if let Ok(Some(workspace)) = ide_workspace::workspace::Workspace::load(root)
&& !workspace.is_container(root)
{
for path in workspace.projects {
if path != root && path.starts_with(root) && !roots.contains(&path) {
roots.push(path);
}
}
}
roots
}
/// The roots a file may navigate into: its own root (the workspace member containing it, or
/// the project root) plus that root's configured dependencies. A workspace member depends
/// only on the roots picked per member in Project Structure › Dependencies —
@@ -2163,4 +2179,25 @@ mod content_roots_tests {
let roots = content_roots(&settings, &root, &tmp.path().join("build"));
assert_eq!(roots, vec![shared, dep]);
}
#[test]
fn projects_attached_inside_the_root_get_their_own_language_server_root() {
let tmp = tempfile::tempdir().unwrap();
let ws = dunce::canonicalize(tmp.path()).unwrap();
let (root, nested, other) = (ws.join("app"), ws.join("app/.wt/feature"), ws.join("other"));
for dir in [&nested, &other] {
std::fs::create_dir_all(dir).unwrap();
}
let settings = ide_core::settings::Settings::default();
let build = ws.join("build");
assert!(super::language_server_roots(&root, content_roots(&settings, &root, &build)).is_empty());
ide_workspace::workspace::Workspace::attach(&root, "app", vec![root.clone(), nested.clone(), other.clone()])
.unwrap();
// The index walks the nested project as part of the root ...
let roots = content_roots(&settings, &root, &build);
assert_eq!(roots, vec![other.clone()]);
// ... while its files go to a language server of its own.
assert_eq!(super::language_server_roots(&root, roots), vec![other, nested]);
}
}
+26 -2
Переглянути файл
@@ -6271,10 +6271,15 @@ fn api14_settings_and_input_events_use_other_and_capture_the_editor() {
assert!(f.host.wait_events(Duration::from_secs(5)));
let received: serde_json::Value = serde_json::from_str(&f.run("api14", "events", None).unwrap().unwrap()).unwrap();
let events = received.as_array().unwrap();
assert_eq!(events.len(), 3, "{received}");
assert_eq!(events.len(), 4, "{received}");
// The first synthetic post hands over the current keys ("enabled": false);
// the second is a real diff to true. Keys come from the recomputed
// snapshot, never from the event payload ("another-plugin-key").
assert_eq!(events[0]["kind"], "settings-changed");
assert_eq!(events[0]["data"], "[\"enabled\"]");
assert_eq!(events[2]["kind"], "input-mode-changed");
assert_eq!(events[1]["kind"], "settings-changed");
assert_eq!(events[1]["data"], "[\"enabled\"]");
assert_eq!(events[3]["kind"], "input-mode-changed");
assert_eq!(events[2]["editor"][0], path);
assert_eq!(events[2]["editor"][1][0], serde_json::json!([0, 0, 0, 0]));
}
@@ -7016,3 +7021,22 @@ fn the_language_server_grant_needs_api_1_9() {
let err = f.host.install_from_dir(&pkg, &Consent::all()).unwrap_err();
assert!(err.message.contains("new in plugin API 1.9"), "{err:?}");
}
/// The UI's synthetic post-install `SettingsChanged([])` reaches a plugin that
/// subscribes to `on-event:settings-changed`, though it carries no keys.
#[test]
fn a_freshly_installed_plugin_gets_the_post_install_settings_event() {
let f = fixture(Limits::default());
f.install(&sample("api14"));
use ide_plugin::WorkbenchEvent as E;
// What refreshEventKinds() posts right after commandsChanged (install).
f.host.post_events(Some("main"), vec![E::SettingsChanged(Vec::new())]);
f.host.flush_events_at(Instant::now() + Duration::from_secs(2));
assert!(f.host.wait_events(Duration::from_secs(5)));
let received: serde_json::Value = serde_json::from_str(&f.run("api14", "events", None).unwrap().unwrap()).unwrap();
let events = received.as_array().unwrap();
assert!(
events.iter().any(|e| e["kind"] == "settings-changed"),
"freshly installed plugin got no post-install event: {received}"
);
}
+2
Переглянути файл
@@ -33,6 +33,7 @@ const BUILTIN: &[(&str, &str)] = &[
("gdscript", include_str!("../../../languages/gdscript.toml")),
("gdshader", include_str!("../../../languages/gdshader.toml")),
("go", include_str!("../../../languages/go.toml")),
("gherkin", include_str!("../../../languages/gherkin.toml")),
("gomod", include_str!("../../../languages/gomod.toml")),
("gowork", include_str!("../../../languages/gowork.toml")),
("godot-resource", include_str!("../../../languages/godot-resource.toml")),
@@ -1057,6 +1058,7 @@ mod tests {
("CMakeLists.txt", "cmake"),
("api.proto", "proto"),
("schema.graphql", "graphql"),
("checkout.feature", "gherkin"),
("schema.prisma", "prisma"),
("main.tf", "terraform"),
("prod.tfvars", "terraform-vars"),
+370 -18
Переглянути файл
@@ -6,11 +6,15 @@
use crate::LspManager;
use crate::server::Server;
use ide_core::{DocId, Pos, Range};
use ide_core::{CancellationToken, DocId, Pos, Range};
use serde::Deserialize;
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::Arc;
use std::sync::atomic::Ordering;
use std::time::Duration;
use tokio::io::AsyncReadExt;
pub(crate) const CHECK_UPGRADES: &str = "gopls.check_upgrades";
/// gopls answers code lenses once it has loaded the module.
@@ -18,6 +22,43 @@ const ATTEMPTS: u32 = 10;
const RETRY: Duration = Duration::from_secs(2);
/// Producer of the deprecation diagnostics (one full set per go.mod).
const DEPRECATIONS: &str = "go-mod-deprecations";
// This optional background check must not wait indefinitely on a proxy or toolchain download.
const QUERY_TIMEOUT: Duration = Duration::from_secs(60);
const OUTPUT_LIMIT: u64 = 8 * 1024 * 1024;
#[derive(Default)]
pub(crate) struct Queries {
generation: u64,
running: HashMap<DocId, (u64, CancellationToken)>,
}
impl Queries {
fn begin(&mut self, doc: DocId) -> (u64, CancellationToken) {
self.cancel(doc);
self.generation += 1;
let cancel = CancellationToken::new();
self.running.insert(doc, (self.generation, cancel.clone()));
(self.generation, cancel)
}
fn finish(&mut self, doc: DocId, generation: u64) {
if self.running.get(&doc).is_some_and(|(current, _)| *current == generation) {
self.running.remove(&doc);
}
}
pub(crate) fn cancel(&mut self, doc: DocId) {
if let Some((_, cancel)) = self.running.remove(&doc) {
cancel.cancel();
}
}
pub(crate) fn cancel_all(&mut self) {
for (_, (_, cancel)) in self.running.drain() {
cancel.cancel();
}
}
}
fn is_go_mod(path: &Path) -> bool {
path.file_name().is_some_and(|n| n == "go.mod")
@@ -66,6 +107,15 @@ impl LspManager {
}
async fn report_deprecated_modules(&self, doc: DocId, server: &Server) {
let (generation, cancel) = self.go_mod_queries.lock().begin(doc);
self.report_deprecated_modules_query(doc, server, &cancel).await;
self.go_mod_queries.lock().finish(doc, generation);
}
async fn report_deprecated_modules_query(&self, doc: DocId, server: &Server, cancel: &CancellationToken) {
if self.shutting_down.load(Ordering::Acquire) || !self.execution_allowed.load(Ordering::Acquire) {
return;
}
let Some((path, text)) = self.docs.lock().get(&doc).map(|d| (d.path.clone(), d.text.as_str().to_owned()))
else {
return;
@@ -78,10 +128,9 @@ impl LspManager {
let search = crate::launch::server_search_path(&config);
let Some(dir) = path.parent().map(Path::to_path_buf) else { return };
let modules: Vec<String> = required.iter().map(|r| r.path.clone()).collect();
let listed = tokio::task::spawn_blocking(move || list_deprecations(&dir, &search, &modules)).await;
let Ok(Some(deprecated)) = listed else { return };
let Some(deprecated) = list_deprecations(&dir, &search, &modules, cancel).await else { return };
// The document changed meanwhile: its own save runs again.
if self.docs.lock().get(&doc).is_none_or(|d| d.text.as_str() != text) {
if cancel.is_cancelled() || self.docs.lock().get(&doc).is_none_or(|d| d.text.as_str() != text) {
return;
}
let items = required
@@ -157,22 +206,100 @@ struct ListedModule {
}
/// `(module, message)` of each deprecated module in `modules`; `None` when `go` failed.
fn list_deprecations(dir: &Path, search: &std::ffi::OsStr, modules: &[String]) -> Option<Vec<(String, String)>> {
let go: PathBuf = ide_core::tool_path::find_command("go", search, dir)?;
let output = ide_core::process::prepare(&mut std::process::Command::new(go))
.args(["list", "-m", "-u", "-e", "-json"])
.args(modules)
.current_dir(dir)
.env("PATH", search)
.stdin(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.output()
.ok()?;
if output.stdout.is_empty() {
tracing::debug!("go list -m -u in {}: {}", dir.display(), output.status);
async fn list_deprecations(
dir: &Path,
search: &std::ffi::OsStr,
modules: &[String],
cancel: &CancellationToken,
) -> Option<Vec<(String, String)>> {
let (dir, search, modules) = (dir.to_path_buf(), search.to_owned(), modules.to_vec());
let command = tokio::task::spawn_blocking(move || {
let go: PathBuf = ide_core::tool_path::find_command("go", &search, &dir)?;
let mut command = Command::new(go);
command.args(["list", "-m", "-u", "-e", "-json"]).args(modules).current_dir(dir).env("PATH", search);
Some(command)
})
.await
.ok()??;
let output = run_query(command, cancel, QUERY_TIMEOUT).await?;
if output.is_empty() {
return None;
}
Some(parse_deprecations(&output.stdout))
tokio::task::spawn_blocking(move || parse_deprecations(&output)).await.ok()
}
async fn run_query(command: Command, cancel: &CancellationToken, timeout: Duration) -> Option<Vec<u8>> {
let cancel = cancel.child_token();
let _cancel_on_drop = cancel.clone().drop_guard();
// The supervisor owns cleanup even if the caller's future is dropped.
tokio::spawn(async move { supervise_query(command, &cancel, timeout).await }).await.ok().flatten()
}
async fn supervise_query(mut command: Command, cancel: &CancellationToken, timeout: Duration) -> Option<Vec<u8>> {
if cancel.is_cancelled() {
return None;
}
ide_core::process::prepare(&mut command);
ide_core::process::own_group(&mut command);
command.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::null());
let mut command = tokio::process::Command::from(command);
command.kill_on_drop(true);
let mut child = command.spawn().ok()?;
#[cfg(windows)]
let job = child.id().and_then(ide_core::process::Job::for_pid);
let stdout = child.stdout.take()?;
let mut reader = tokio::spawn(async move {
let mut output = Vec::new();
stdout.take(OUTPUT_LIMIT + 1).read_to_end(&mut output).await.ok()?;
if output.len() as u64 > OUTPUT_LIMIT {
tracing::debug!("go module query exceeded stdout budget");
return None;
}
Some(output)
});
let deadline = tokio::time::sleep(timeout);
tokio::pin!(deadline);
// Drain before reaping: if a descendant holds stdout open, the root's id
// still belongs to this child when cancellation kills its process tree.
let output = tokio::select! {
biased;
() = cancel.cancelled() => None,
() = &mut deadline => {
tracing::debug!("go module query timed out");
None
},
result = &mut reader => result.ok().flatten(),
};
if let Some(bytes) = output {
let status = tokio::select! {
biased;
() = cancel.cancelled() => None,
() = &mut deadline => {
tracing::debug!("go module query timed out");
None
},
status = child.wait() => Some(status),
};
if let Some(status) = status {
return status.ok().map(|_| bytes);
}
}
// The root is still unreaped here, so its process/group id cannot be reused.
if let Some(pid) = child.id() {
let _ = tokio::task::spawn_blocking(move || {
#[cfg(windows)]
if let Some(job) = job {
job.terminate();
return;
}
ide_core::process::kill_tree_of(pid);
})
.await;
}
let _ = child.start_kill();
let _ = child.wait().await;
reader.abort();
None
}
fn parse_deprecations(json: &[u8]) -> Vec<(String, String)> {
@@ -187,6 +314,231 @@ fn parse_deprecations(json: &[u8]) -> Vec<(String, String)> {
mod tests {
use super::*;
#[test]
fn queries_cancel_only_the_superseded_document() {
let mut queries = Queries::default();
let (first, old) = queries.begin(DocId(1));
let (_, other) = queries.begin(DocId(2));
let (second, new) = queries.begin(DocId(1));
assert!(old.is_cancelled());
assert!(!other.is_cancelled());
assert!(!new.is_cancelled());
queries.finish(DocId(1), first);
assert_eq!(queries.running.len(), 2);
queries.finish(DocId(1), second);
assert_eq!(queries.running.len(), 1);
queries.cancel_all();
assert!(other.is_cancelled());
assert!(queries.running.is_empty());
}
#[test]
fn closing_one_document_does_not_cancel_another() {
let mut queries = Queries::default();
let (_, closed) = queries.begin(DocId(1));
let (_, other) = queries.begin(DocId(2));
queries.cancel(DocId(1));
assert!(closed.is_cancelled());
assert!(!other.is_cancelled());
assert_eq!(queries.running.len(), 1);
}
#[cfg(unix)]
fn shell(script: &str) -> Command {
let mut command = Command::new("sh");
command.args(["-c", script]);
command
}
#[cfg(target_os = "linux")]
async fn assert_stopped(pid: u32) {
tokio::time::timeout(Duration::from_secs(5), async {
while let Ok(stat) = std::fs::read_to_string(format!("/proc/{pid}/stat")) {
if stat.rsplit_once(") ").unwrap().1.split_whitespace().next() == Some("Z") {
break;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await
.unwrap();
}
#[cfg(unix)]
#[tokio::test]
async fn cancelled_query_never_spawns() {
let dir = tempfile::tempdir().unwrap();
let cancel = CancellationToken::new();
cancel.cancel();
let mut command = shell("touch started");
command.current_dir(dir.path());
assert!(run_query(command, &cancel, Duration::from_secs(5)).await.is_none());
assert!(!dir.path().join("started").exists());
}
#[cfg(unix)]
#[tokio::test]
async fn queries_keep_working_directories_and_environments_separate() {
let a = tempfile::tempdir().unwrap();
let b = tempfile::tempdir().unwrap();
std::fs::write(a.path().join("value"), "directory-a").unwrap();
std::fs::write(b.path().join("value"), "directory-b").unwrap();
let mut ca = shell("printf '%s:' \"$QUERY_VALUE\"; cat value");
ca.current_dir(a.path()).env("QUERY_VALUE", "env-a");
let mut cb = shell("printf '%s:' \"$QUERY_VALUE\"; cat value");
cb.current_dir(b.path()).env("QUERY_VALUE", "env-b");
let cancel = CancellationToken::new();
let (a, b) = tokio::join!(
run_query(ca, &cancel, Duration::from_secs(5)),
run_query(cb, &cancel, Duration::from_secs(5)),
);
assert_eq!(a.unwrap(), b"env-a:directory-a");
assert_eq!(b.unwrap(), b"env-b:directory-b");
}
#[cfg(unix)]
#[tokio::test]
async fn timeout_kills_and_reaps_the_query() {
let dir = tempfile::tempdir().unwrap();
let mut command = shell("echo $$ > pid; exec sleep 2");
command.current_dir(dir.path());
let output = run_query(command, &CancellationToken::new(), Duration::from_secs(1)).await;
assert!(output.is_none());
let pid = std::fs::read_to_string(dir.path().join("pid")).unwrap().trim().parse().unwrap();
assert!(!ide_core::process::process_alive(pid));
}
#[cfg(unix)]
#[tokio::test]
async fn cancellation_kills_the_running_query_and_its_child() {
let dir = tempfile::tempdir().unwrap();
let mut command = shell("sleep 30 & echo $$ $! > pids; wait");
command.current_dir(dir.path());
let cancel = CancellationToken::new();
let token = cancel.clone();
let task = tokio::spawn(async move { run_query(command, &token, Duration::from_secs(10)).await });
let pids = dir.path().join("pids");
tokio::time::timeout(Duration::from_secs(5), async {
while !std::fs::read_to_string(&pids).is_ok_and(|s| s.split_whitespace().count() == 2) {
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await
.unwrap();
let text = std::fs::read_to_string(pids).unwrap();
let pids: Vec<u32> = text.split_whitespace().map(|p| p.parse().unwrap()).collect();
cancel.cancel();
assert!(task.await.unwrap().is_none());
assert!(!ide_core::process::process_alive(pids[0]));
// An orphaned child may remain a zombie until the host's init reaps it.
#[cfg(target_os = "linux")]
assert_stopped(pids[1]).await;
#[cfg(not(target_os = "linux"))]
tokio::time::timeout(Duration::from_secs(5), async {
while ide_core::process::process_alive(pids[1]) {
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await
.unwrap();
}
#[cfg(unix)]
#[tokio::test]
async fn dropping_the_caller_still_reaps_its_query() {
let dir = tempfile::tempdir().unwrap();
let mut command = shell("sleep 30 & echo $$ $! > pid; wait");
command.current_dir(dir.path());
let task =
tokio::spawn(async move { run_query(command, &CancellationToken::new(), Duration::from_secs(10)).await });
let file = dir.path().join("pid");
tokio::time::timeout(Duration::from_secs(5), async {
while !std::fs::read_to_string(&file).is_ok_and(|s| s.split_whitespace().count() == 2) {
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await
.unwrap();
let text = std::fs::read_to_string(file).unwrap();
let pids: Vec<u32> = text.split_whitespace().map(|p| p.parse().unwrap()).collect();
let pid = pids[0];
task.abort();
let _ = task.await;
tokio::time::timeout(Duration::from_secs(5), async {
while ide_core::process::process_alive(pid) {
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await
.unwrap();
#[cfg(target_os = "linux")]
assert_stopped(pids[1]).await;
#[cfg(not(target_os = "linux"))]
tokio::time::timeout(Duration::from_secs(5), async {
while ide_core::process::process_alive(pids[1]) {
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await
.unwrap();
}
#[cfg(target_os = "linux")]
#[tokio::test]
async fn timeout_cleans_up_a_child_holding_stdout_after_root_exit() {
let dir = tempfile::tempdir().unwrap();
let mut command = shell("sleep 30 & echo $! > pid; exit 0");
command.current_dir(dir.path());
assert!(run_query(command, &CancellationToken::new(), Duration::from_secs(1)).await.is_none());
let pid = std::fs::read_to_string(dir.path().join("pid")).unwrap();
assert_stopped(pid.trim().parse().unwrap()).await;
}
#[cfg(unix)]
#[tokio::test]
async fn output_at_the_limit_is_not_truncated() {
let output = run_query(shell("head -c 8388608 /dev/zero"), &CancellationToken::new(), Duration::from_secs(5))
.await
.unwrap();
assert_eq!(output.len() as u64, OUTPUT_LIMIT);
}
#[cfg(unix)]
#[tokio::test]
async fn oversized_output_kills_the_query() {
let dir = tempfile::tempdir().unwrap();
let mut command = shell("echo $$ > pid; head -c 8388609 /dev/zero; exec sleep 30");
command.current_dir(dir.path());
assert!(run_query(command, &CancellationToken::new(), Duration::from_secs(5)).await.is_none());
let pid = std::fs::read_to_string(dir.path().join("pid")).unwrap().trim().parse().unwrap();
assert!(!ide_core::process::process_alive(pid));
}
#[cfg(unix)]
#[tokio::test]
async fn preserves_output_from_a_nonzero_exit() {
assert_eq!(
run_query(shell("printf partial; exit 1"), &CancellationToken::new(), Duration::from_secs(5))
.await
.unwrap(),
b"partial"
);
}
#[cfg(unix)]
#[tokio::test]
async fn failed_spawn_does_not_poison_a_following_query() {
assert!(
run_query(Command::new("/no/such/go-query"), &CancellationToken::new(), Duration::from_secs(5))
.await
.is_none()
);
assert_eq!(
run_query(shell("printf ok"), &CancellationToken::new(), Duration::from_secs(5)).await.unwrap(),
b"ok"
);
}
fn at(line: u32, from: u32, to: u32) -> Range {
Range { start: Pos { line, col: from }, end: Pos { line, col: to } }
}
+5
Переглянути файл
@@ -240,6 +240,7 @@ pub struct LspManager {
shown_messages: Mutex<HashSet<(String, String)>>,
/// go.mod files whose upgrades gopls has been asked to check this session.
go_mod_checked: Mutex<HashSet<PathBuf>>,
go_mod_queries: Mutex<go_mod::Queries>,
/// Virtual (non-`file:`) URIs a server returned, by the server that owns them.
virtual_origins: Mutex<HashMap<String, ide_core::ServerId>>,
/// Contents fetched for virtual URIs.
@@ -516,6 +517,7 @@ impl LspManager {
configuration_cache: Arc::new(Mutex::new(Default::default())),
shown_messages: Mutex::new(HashSet::new()),
go_mod_checked: Mutex::new(HashSet::new()),
go_mod_queries: Mutex::new(go_mod::Queries::default()),
virtual_origins: Mutex::new(HashMap::new()),
virtual_docs: Mutex::new(HashMap::new()),
virtual_stamps: Mutex::new(HashMap::new()),
@@ -1393,6 +1395,7 @@ impl LspManager {
}
fn close_document(&self, doc: DocId) {
self.go_mod_queries.lock().cancel(doc);
let (d, compose_removed) = {
let mut docs = self.docs.lock();
let Some(d) = docs.remove(&doc) else { return };
@@ -3713,6 +3716,7 @@ impl LspManager {
pub fn set_execution_allowed(&self, allowed: bool) {
let previous = self.execution_allowed.swap(allowed, Ordering::AcqRel);
if !allowed {
self.go_mod_queries.lock().cancel_all();
for server in self.servers.lock().iter() {
server.start_token().cancel();
}
@@ -4057,6 +4061,7 @@ impl LspManager {
pub async fn shutdown_all(&self) {
self.shutting_down.store(true, Ordering::Release);
self.go_mod_queries.lock().cancel_all();
let _reconfigure = self.reconfigure_lock.lock().await;
let servers: Vec<Arc<Server>> = self.servers.lock().clone();
join_all(servers.iter().map(|s| self.stop_instance(s, true))).await;
+2
Переглянути файл
@@ -885,6 +885,8 @@ pub fn jdk_sdk(j: &crate::java::Jdk) -> Sdk {
"JAVA_HOME"
} else if crate::java::is_downloaded(&j.home) {
"downloaded"
} else if crate::java::is_added(&j.home) {
"added"
} else {
version_managers::manager_of(&j.home).unwrap_or("system")
};
+41
Переглянути файл
@@ -138,6 +138,26 @@ pub fn add_jdk_root(dir: &Path) {
}
}
/// JDK homes added by hand (Settings › SDKs › Add JDK from Disk…).
static ADDED: Mutex<Vec<PathBuf>> = Mutex::new(Vec::new());
/// Sets the JDK homes added by hand; the next scan lists them (a change drops the cached scan).
pub fn set_added_jdks(homes: impl IntoIterator<Item = PathBuf>) {
let homes: Vec<PathBuf> = homes.into_iter().filter(|h| !h.as_os_str().is_empty()).collect();
let mut added = ADDED.lock().unwrap_or_else(|e| e.into_inner());
if *added != homes {
*added = homes;
drop(added);
*JDKS.lock().unwrap_or_else(|e| e.into_inner()) = None;
}
}
/// Whether `home` is a JDK added by hand.
pub fn is_added(home: &Path) -> bool {
let added = ADDED.lock().unwrap_or_else(|e| e.into_inner());
added.iter().any(|h| jdk_at(h).is_some_and(|j| j.home == home))
}
/// Whether `home` lies in a folder registered with [`add_jdk_root`].
pub fn is_downloaded(home: &Path) -> bool {
let roots = EXTRA_ROOTS.lock().unwrap_or_else(|e| e.into_inner());
@@ -190,6 +210,7 @@ fn scan() -> Vec<Jdk> {
for (dir, _) in ide_core::version_managers::installs(ide_core::version_managers::Tool::Java) {
homes.extend([dir.join("Contents/Home"), dir]);
}
homes.extend(ADDED.lock().unwrap_or_else(|e| e.into_inner()).iter().cloned());
let mut out: Vec<Jdk> = Vec::new();
for h in homes {
if let Some(jdk) = jdk_at(&h)
@@ -1364,6 +1385,26 @@ mod tests {
assert!(is_downloaded(&home) && !is_downloaded(Path::new("/elsewhere")));
}
#[test]
fn jdks_added_by_hand_are_listed_until_removed() {
let tmp = tempfile::tempdir().unwrap();
// A macOS bundle picked as its folder: listed by its `Contents/Home`.
let bundle = tmp.path().join("odd place/my-jdk.jdk");
let home = bundle.join("Contents/Home");
std::fs::create_dir_all(home.join("bin")).unwrap();
std::fs::write(home.join("release"), "JAVA_VERSION=\"17.0.9\"\nIMPLEMENTOR=\"Acme\"\n").unwrap();
std::fs::write(home.join("bin").join(crate::exe("java")), "").unwrap();
let home = dunce::canonicalize(&home).unwrap();
set_added_jdks([bundle.clone()]);
assert!(installed_jdks().iter().any(|j| j.home == home && j.major == 17));
assert!(is_added(&home));
let sdk = crate::jdk_sdk(&jdk_at(&bundle).unwrap());
assert_eq!((sdk.name.as_str(), sdk.source.as_str()), ("Acme 17.0.9", "added"));
set_added_jdks(Vec::new());
assert!(!installed_jdks().iter().any(|j| j.home == home));
assert!(!is_added(&home));
}
#[test]
fn jdtls_runs_on_the_chosen_server_jdk() {
let fixtures = tempfile::tempdir().unwrap();
+41 -2
Переглянути файл
@@ -338,6 +338,15 @@ pub fn env_wrapper(bin_dir: &Path, command: &str, target: &Path, env: &[(&str, &
}
pub fn link_executable(bin_dir: &Path, command: &str, target: &Path) -> IdeResult<PathBuf> {
link_executable_with_runtime(bin_dir, command, target, None)
}
pub fn link_executable_with_runtime(
bin_dir: &Path,
command: &str,
target: &Path,
runtime: Option<&str>,
) -> IdeResult<PathBuf> {
fs::create_dir_all(bin_dir)?;
#[cfg(unix)]
{
@@ -347,7 +356,8 @@ pub fn link_executable(bin_dir: &Path, command: &str, target: &Path) -> IdeResul
}
let quoted = target.to_string_lossy().replace('\'', r"'\''");
// A Node script without a shebang (e.g. js-debug's dapDebugServer.js) runs through `node`.
let runner = if target.extension().is_some_and(|e| e == "js") { "node " } else { "" };
let runner = runtime.or_else(|| target.extension().is_some_and(|e| e == "js").then_some("node"));
let runner = runner.map(|r| format!("{r} ")).unwrap_or_default();
fs::write(&link, format!("#!/bin/sh\nexec {runner}'{quoted}' \"$@\"\n"))?;
make_executable(&link)?;
make_executable(target)?;
@@ -356,7 +366,8 @@ pub fn link_executable(bin_dir: &Path, command: &str, target: &Path) -> IdeResul
#[cfg(not(unix))]
{
let link = bin_dir.join(format!("{command}.cmd"));
let runner = if target.extension().is_some_and(|e| e == "js") { "node " } else { "" };
let runner = runtime.or_else(|| target.extension().is_some_and(|e| e == "js").then_some("node"));
let runner = runner.map(|r| format!("{r} ")).unwrap_or_default();
fs::write(&link, format!("@echo off\r\n{runner}\"{}\" %*\r\n", cmd_path(bin_dir, target)))?;
Ok(link)
}
@@ -510,6 +521,34 @@ mod tests {
assert!(dest.join("ok.txt").exists());
}
#[test]
fn unity_vsix_wrapper_preserves_managed_assemblies_and_uses_mono_on_unix() {
let tmp = tempfile::tempdir().unwrap();
let archive = tmp.path().join("unity.vsix");
zip_file(
&archive,
&[
("extension/bin/UnityDebug.exe", b"adapter", 0o644),
("extension/bin/UnityDebug.exe.config", b"runtime config", 0o644),
("extension/bin/Mono.Debugger.Soft.dll", b"dependency", 0o644),
],
);
let dest = tmp.path().join("install with spaces");
extract(&archive, ArchiveKind::Zip, &dest, "unity-debug", &CancellationToken::new()).unwrap();
let target = locate(&dest, &["UnityDebug.exe".into()]).unwrap();
let wrapper =
link_executable_with_runtime(&dest.join("bin"), "unity-debug", &target, cfg!(unix).then_some("mono"))
.unwrap();
let script = fs::read_to_string(wrapper).unwrap();
assert!(script.contains(&*target.to_string_lossy()));
#[cfg(unix)]
assert!(script.contains("exec mono '") && script.contains("\"$@\""));
#[cfg(windows)]
assert!(script.contains("\" %*") && !script.contains("mono "));
assert_eq!(fs::read(target.with_extension("exe.config")).unwrap(), b"runtime config");
assert_eq!(fs::read(target.parent().unwrap().join("Mono.Debugger.Soft.dll")).unwrap(), b"dependency");
}
#[test]
fn zip_symlinks_are_confined_to_the_destination() {
for target in ["../outside", "/tmp/outside", "a/../../outside"] {
+51 -3
Переглянути файл
@@ -1256,6 +1256,42 @@ impl Tools {
Err(IdeError::new(ErrorKind::Io, format!("pip install {package} failed ({status})")))
}
/// A command running pip, before its arguments. The interpreter's own pip when it has one;
/// a virtualenv made by uv has none, so then pip through `uv tool run`, or another Python
/// on `PATH` that has it.
fn pip_command(&self, python: PathBuf, emit: Emit) -> Command {
let has_pip = |python: &Path| {
let mut c = self.python_command(python);
c.args(["-m", "pip", "--version"]);
run_quiet(c, Duration::from_secs(20)).is_some_and(|(ok, _)| ok)
};
let module = |python: &Path| {
let mut c = self.python_command(python);
c.args(["-m", "pip"]);
c
};
if has_pip(&python) {
return module(&python);
}
let note = format!("{} has no pip", python.display());
if let Some(uv) = self.which("uv") {
emit(InstallEvent::Line { text: format!("{note}; running pip with uv") });
// pip runs in uv's own Python: the same private working directory applies.
let mut c = self.python_command(uv);
c.args(["tool", "run", "pip"]);
return c;
}
let other = ["python3", "python"]
.into_iter()
.filter_map(|name| ide_core::tool_path::find_command(name, &self.system_path, &self.root))
.find(|p| *p != python && has_pip(p));
if let Some(other) = other {
emit(InstallEvent::Line { text: format!("{note}; using {}", other.display()) });
return module(&other);
}
module(&python)
}
/// The universal (`py3-none-any`) wheel, so the copy works with every interpreter
/// version a project selects, not just the one that installed it.
fn install_pip_target(
@@ -1269,8 +1305,8 @@ impl Tools {
let _ = std::fs::remove_dir_all(&dir);
let lib = python_lib_dir(&self.root, spec.name);
std::fs::create_dir_all(&lib)?;
let mut c = self.python_command(self.python().expect("checked"));
c.args(["-m", "pip", "install", "--disable-pip-version-check", "--no-deps", "--upgrade", "--target"])
let mut c = self.pip_command(self.python().expect("checked"), emit);
c.args(["install", "--disable-pip-version-check", "--no-deps", "--upgrade", "--target"])
.arg(&lib)
.args(["--only-binary=:all:", "--platform", "any", "--implementation", "py"])
.arg(package);
@@ -1296,6 +1332,14 @@ impl Tools {
cancel: &CancellationToken,
) -> IdeResult<sources::Download> {
match source {
ReleaseSource::Fixed { version, url, sha256 } => Ok(sources::Download {
version: version.into(),
name: url.rsplit('/').next().unwrap_or("download").into(),
url: url.into(),
size: None,
sha256: Some(sha256.into()),
checksum_url: None,
}),
ReleaseSource::GitHub { repo } => match http.get_text(&sources::github_latest_url(repo), cancel) {
Ok(json) => sources::github_pick(&json, assets, self.platform),
Err(e) if e.kind == ErrorKind::Cancelled => Err(e),
@@ -1442,7 +1486,11 @@ impl Tools {
} else {
archive::make_executable(&target)?;
if self.exe_in(&bin, main).as_deref() != Some(target.as_path()) {
archive::link_executable(&bin, main, &target)?;
if spec.name == "unity-debug" && cfg!(unix) {
archive::link_executable_with_runtime(&bin, main, &target, Some("mono"))?;
} else {
archive::link_executable(&bin, main, &target)?;
}
}
}
self.write_manifest(spec.name, &Manifest { version: Some(dl.version.clone()), source: Some(dl.url.clone()) })
+28
Переглянути файл
@@ -20,6 +20,8 @@ pub enum ToolKind {
/// Where release archives come from.
#[derive(Clone, Copy, Debug)]
pub enum ReleaseSource {
/// One pinned archive, verified against its SHA-256 before extraction.
Fixed { version: &'static str, url: &'static str, sha256: &'static str },
/// Latest GitHub release of `owner/repo`; assets plus links in the release notes.
GitHub { repo: &'static str },
/// `api.releases.hashicorp.com` product.
@@ -80,6 +82,7 @@ impl Method {
Method::Release { source: ReleaseSource::EclipseJdtls, .. } => "Eclipse download",
Method::Release { source: ReleaseSource::OpenVsx { .. }, .. } => "Open VSX",
Method::Release { source: ReleaseSource::MavenCentral { .. }, .. } => "Maven Central",
Method::Release { source: ReleaseSource::Fixed { .. }, .. } => "Verified download",
Method::Release { .. } => "GitHub release",
}
}
@@ -131,6 +134,29 @@ const fn ver(cmd: &'static str) -> Option<(&'static str, &'static [&'static str]
pub const TYPESCRIPT: &str = "typescript@6";
pub static TOOLS: &[ToolSpec] = &[
ToolSpec {
name: "unity-debug",
display: "Unity Debugger",
kind: Debugger,
commands: &["unity-debug"],
method: Method::Release {
source: ReleaseSource::Fixed {
version: "3.0.1",
url: "https://github.com/Unity-Technologies/vscode-unity-debug/releases/download/Version-3.0.1/unity-debug-3.0.1.vsix",
sha256: "4fa00660e0b52b0413726f80962e7d3d6efd41ac6cfd4df39520cae4a8ba5bd0",
},
assets: &[any_arch(Mac, "*.vsix"), any_arch(Linux, "*.vsix"), any_arch(Windows, "*.vsix")],
locate: &["UnityDebug.exe"],
},
fallback: None,
version: V,
homepage: "https://github.com/Unity-Technologies/vscode-unity-debug",
needs: if cfg!(windows) {
&[]
} else {
&[("mono", "Mono is required to run the Unity debugger (https://www.mono-project.com)")]
},
},
ToolSpec {
name: "prettier",
display: "Prettier",
@@ -1164,6 +1190,8 @@ mod tests {
fn registry_names_match_language_configs() {
let langs = ide_language::LanguageRegistry::load(None).unwrap().all();
let mut known = std::collections::HashSet::new();
// The Unity debugger comes with Unity projects, apart from the C# debugger.
known.insert(("unity-debug".to_owned(), "unity-debug".to_owned()));
for l in &langs {
for s in &l.language_servers {
known.insert((s.name.clone(), s.command.clone()));
+68
Переглянути файл
@@ -49,6 +49,24 @@ fn find<'a>(list: &'a [ToolInfo], name: &str) -> &'a ToolInfo {
list.iter().find(|t| t.name == name).unwrap_or_else(|| panic!("{name} not listed"))
}
#[test]
fn unity_adapter_download_is_pinned_and_checksum_verified() {
let env = Env::new();
let tools = env.tools();
let spec = registry::find("unity-debug").unwrap();
let Method::Release { source, assets, locate } = spec.method else { panic!("expected release") };
// A fixed release resolves without a network request.
let curl = env.sys.join(if cfg!(windows) { "curl.exe" } else { "curl" });
fs::write(&curl, b"unused").unwrap();
archive::make_executable(&curl).unwrap();
let http = Http::new(env.sys.as_os_str()).unwrap();
let download = tools.resolve_release(&http, source, assets, &CancellationToken::new()).unwrap();
assert_eq!(download.version, "3.0.1");
assert!(download.url.starts_with("https://github.com/Unity-Technologies/vscode-unity-debug/releases/download/"));
assert_eq!(download.sha256.as_deref(), Some("4fa00660e0b52b0413726f80962e7d3d6efd41ac6cfd4df39520cae4a8ba5bd0"));
assert_eq!(locate, &["UnityDebug.exe"]);
}
#[test]
fn bundled_lombok_replaces_legacy_installs_on_every_platform_without_downloads() {
for os in [Os::Mac, Os::Linux, Os::Windows] {
@@ -877,9 +895,14 @@ esac
}
}
/// Installs of one tool name share a process-wide slot: tests installing debugpy take turns.
#[cfg(unix)]
static DEBUGPY_INSTALL: parking_lot::Mutex<()> = parking_lot::Mutex::new(());
#[cfg(unix)]
#[test]
fn selected_python_is_used_for_pip_and_uv_even_with_a_versioned_filename() {
let _guard = DEBUGPY_INSTALL.lock();
let env = Env::new();
env.script(&env.sys, "python3", "exit 99");
let sdk = env._tmp.path().join("python-sdk");
@@ -917,6 +940,51 @@ exit 1
assert!(args.contains(&format!("--python {}", sdk.join("python3.14").display())), "{args}");
}
/// A virtualenv made by uv has no pip: debugpy's private copy is made with pip through uv.
#[cfg(unix)]
#[test]
fn debugpy_installs_through_uv_when_the_selected_python_has_no_pip() {
let _guard = DEBUGPY_INSTALL.lock();
let env = Env::new();
let venv = env._tmp.path().join("project/.venv/bin");
env.script(&venv, "python", "echo \"$(basename \"$0\"): No module named pip\" >&2; exit 1");
let log = env._tmp.path().join("uv.log");
env.script(
&env.sys,
"uv",
&format!(
r#"
echo "$@" >> '{log}'
while [ $# -gt 0 ]; do
if [ "$1" = "--target" ]; then
/bin/mkdir -p "$2/debugpy" "$2/debugpy-1.8.0.dist-info"
/usr/bin/touch "$2/debugpy/__init__.py"
exit 0
fi
shift
done
exit 1
"#,
log = log.display()
),
);
let tools = env.tools().with_runtime(BTreeMap::from([("python".into(), venv.join("python"))]), BTreeMap::new());
let lines = Mutex::new(Vec::new());
let info = tools
.install("debugpy", &langs(), &CancellationToken::new(), &|e| {
if let InstallEvent::Line { text } = e {
lines.lock().push(text);
}
})
.unwrap();
assert_eq!(info.status, ToolStatus::Installed);
assert_eq!(info.version.as_deref(), Some("1.8.0"));
let args = fs::read_to_string(log).unwrap();
assert!(args.starts_with("tool run pip install "), "{args}");
assert!(args.contains("--platform any"), "{args}");
assert!(lines.lock().iter().any(|l| l.contains("has no pip")));
}
#[test]
fn a_cancelled_install_leaves_the_previous_one_in_place() {
let tmp = tempfile::tempdir().unwrap();
+2 -1
Переглянути файл
@@ -1159,7 +1159,8 @@ impl Repo {
write::stage_patch(self, patch, &|path| encoding(path).map(Into::into))
}
/// Discards unstaged changes: tracked paths are restored from the index (staged
/// changes are kept), untracked files and directories are deleted.
/// changes are kept), untracked files and directories are deleted. A submodule goes back
/// to the commit the index records, with its tracked files restored.
pub fn discard(&self, paths: &[PathBuf]) -> IdeResult<()> {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
write::discard(self, paths)
+9 -6
Переглянути файл
@@ -25,16 +25,19 @@ pub(crate) fn save(r: &Repo, message: &str) -> IdeResult<()> {
if run(r.root(), &["status", "--porcelain", "--untracked-files=no"], None)?.stdout_str().trim().is_empty() {
return Ok(());
}
let before = run(r.root(), &["rev-parse", "-q", "--verify", "refs/stash"], None).map(|o| o.stdout_str()).ok();
let before = stash_top(r);
run(r.root(), &["stash", "push", "-q", "-m", message], None)?;
let id = run(r.root(), &["rev-parse", "refs/stash"], None)?.stdout_str();
if before.as_deref().map(str::trim) == Some(id.trim()) {
return Err(IdeError::invalid("could not save the local changes"));
}
std::fs::write(marker, id.trim())?;
// A stash that succeeds without a new entry found nothing it saves: the status above also
// lists submodules at another commit or with changes inside, which a stash leaves in place.
let Some(id) = stash_top(r).filter(|id| Some(id) != before.as_ref()) else { return Ok(()) };
std::fs::write(marker, id)?;
Ok(())
}
fn stash_top(r: &Repo) -> Option<String> {
run(r.root(), &["rev-parse", "-q", "--verify", "refs/stash"], None).ok().map(|o| o.stdout_str().trim().to_owned())
}
/// Brings the saved changes back once no operation is in progress. Fails when they come
/// back with conflicts (they then also stay in the stash).
pub(crate) fn restore(r: &Repo) -> IdeResult<()> {
+17 -6
Переглянути файл
@@ -391,18 +391,24 @@ pub(crate) fn discard(r: &Repo, paths: &[PathBuf]) -> IdeResult<()> {
let rel = r.rel_paths(paths)?;
// `git restore --worktree` refuses unmerged paths: roll those back to HEAD first.
discard_unmerged(r, &rel)?;
let (mut tracked, mut untracked) = (Vec::new(), Vec::new());
let (mut tracked, mut untracked, mut submodules) = (Vec::new(), Vec::new(), Vec::new());
{
let repo = r.gix()?;
let index = repo.index_or_empty().map_err(gx)?;
for p in rel {
let exact = index.entry_index_by_path(BStr::new(p.as_bytes())).is_ok();
let exact = index.entry_index_by_path(BStr::new(p.as_bytes())).ok().map(|i| &index.entries()[i]);
let dir_prefix = if p == "." { String::new() } else { format!("{}/", p.trim_end_matches('/')) };
let has_tracked_children = index.prefixed_entries(BStr::new(dir_prefix.as_bytes())).is_some();
if exact {
tracked.push(p);
let children = index.prefixed_entries(BStr::new(dir_prefix.as_bytes()));
if let Some(entry) = exact {
if entry.mode.is_submodule() {
submodules.push(p);
} else {
tracked.push(p);
}
} else if r.abs_path(&p).is_dir() {
if has_tracked_children {
if let Some(children) = children {
submodules
.extend(children.iter().filter(|e| e.mode.is_submodule()).map(|e| e.path(&index).to_string()));
tracked.push(p.clone());
}
untracked.push(p);
@@ -412,6 +418,11 @@ pub(crate) fn discard(r: &Repo, paths: &[PathBuf]) -> IdeResult<()> {
}
}
run_paths(r, &["restore", "--worktree"], &tracked)?;
// A plain restore leaves a submodule alone. This one checks out the commit the index
// records there and restores its tracked files, keeping its untracked ones.
if crate::execution_allowed() {
run_paths(r, &["restore", "--recurse-submodules", "--worktree"], &submodules)?;
}
if !untracked.is_empty() {
// `git clean` keeps ignored files and refuses paths outside the worktree.
run_paths(r, &["clean", "-f", "-d", "-q"], &untracked)?;
+69 -1
Переглянути файл
@@ -69,7 +69,8 @@ impl Fixture {
fn push_from_other(&self, bare: &Path, rel: &str, content: &str) {
let other = self.tmp.path().join(format!("other-{}", rel.replace('/', "_")));
if !other.exists() {
git_in(self.tmp.path(), &["clone", "-q", bare.to_str().unwrap(), other.to_str().unwrap()]);
let (bare, other_dir) = (bare.to_str().unwrap(), other.to_str().unwrap());
git_in(self.tmp.path(), &["clone", "-q", "-c", "core.autocrlf=false", bare, other_dir]);
configure(&other);
}
git_in(&other, &["pull", "-q", "--rebase"]);
@@ -636,6 +637,73 @@ fn update_with_rebase_keeps_a_file_added_then_deleted_added_to_the_index() {
assert!(fx.git(&["status", "--porcelain", "--", "ad.txt"]).starts_with('A'), "still added");
}
/// Submodules `dirty` and `moved` (each with commits "one" and "two", at "two") committed in
/// the clone of [`Fixture::with_origin`] and pushed; then `dirty` gets an uncommitted edit of a
/// tracked file plus an untracked file, and `moved` is checked out at "one". Returns the commit
/// the superproject records for `moved`.
fn with_changed_submodules(fx: &Fixture) -> String {
for name in ["dirty", "moved"] {
let lib = fx.tmp.path().join(format!("lib-{name}"));
std::fs::create_dir(&lib).unwrap();
git_in(&lib, &["init", "-q"]);
configure(&lib);
std::fs::write(lib.join("f.txt"), "one\n").unwrap();
git_in(&lib, &["add", "-A"]);
git_in(&lib, &["commit", "-q", "-m", "one"]);
std::fs::write(lib.join("f.txt"), "two\n").unwrap();
git_in(&lib, &["commit", "-q", "-am", "two"]);
let url = lib.to_str().unwrap();
fx.git(&["-c", "protocol.file.allow=always", "-c", "core.autocrlf=false", "submodule", "add", "-q", url, name]);
configure(&fx.path(name));
}
fx.commit_all("submodules");
fx.git(&["push", "-q", "origin", "main"]);
let recorded = git_in(&fx.path("moved"), &["rev-parse", "HEAD"]);
fx.write("dirty/f.txt", "edited\n");
fx.write("dirty/untracked.txt", "u\n");
git_in(&fx.path("moved"), &["checkout", "-q", "HEAD~1"]);
recorded
}
/// git lists submodules at another commit or with changes inside among the superproject's
/// changes, but its stash leaves them in place, so Update Project has nothing to put aside (#3632).
#[test]
fn update_with_changed_submodules_and_no_other_local_changes() {
for (rebase, earlier_stash) in [(false, false), (false, true), (true, false), (true, true)] {
let (fx, bare) = Fixture::with_origin();
let recorded = with_changed_submodules(&fx);
if earlier_stash {
fx.write("a.txt", "stashed\n");
fx.git(&["stash", "push", "-q", "-m", "earlier"]);
}
fx.push_from_other(&bare, "remote.txt", "r\n");
let repo = fx.repo();
let (cancel, out) = quiet();
repo.pull(rebase, &cancel, &out).unwrap_or_else(|e| panic!("rebase={rebase} stash={earlier_stash}: {e}"));
assert!(fx.exists("remote.txt"));
assert_eq!(fx.read("dirty/f.txt"), "edited\n");
assert_ne!(git_in(&fx.path("moved"), &["rev-parse", "HEAD"]), recorded);
let stashes = fx.git(&["stash", "list"]);
assert_eq!(stashes.lines().count(), usize::from(earlier_stash), "{stashes}");
assert!(!fx.dir.join(".git/openidea-saved-changes").exists());
}
}
#[test]
fn rollback_changed_submodules_restores_the_recorded_commit_and_tracked_files() {
for whole_root in [false, true] {
let (fx, _bare) = Fixture::with_origin();
let recorded = with_changed_submodules(&fx);
let repo = fx.repo();
let paths = if whole_root { vec![fx.dir.clone()] } else { vec![fx.path("dirty"), fx.path("moved")] };
repo.discard(&paths).unwrap();
assert_eq!(fx.read("dirty/f.txt"), "two\n", "whole_root={whole_root}");
assert_eq!(git_in(&fx.path("moved"), &["rev-parse", "HEAD"]), recorded);
assert_eq!(fx.read("dirty/untracked.txt"), "u\n", "untracked files of a submodule are kept");
assert_eq!(fx.git(&["status", "--porcelain", "--ignore-submodules=untracked"]), "");
}
}
#[test]
fn reset_to_the_remote_branch_drops_local_commits_and_keeps_local_changes() {
let (fx, bare) = Fixture::with_origin();
+95 -3
Переглянути файл
@@ -140,9 +140,6 @@ pub fn detect(root: &Path) -> Vec<SourceFolder> {
}
let found: Vec<String> = out[before..].iter().map(|r| r.path.clone()).collect();
for name in dirs {
if name.starts_with('.') || SKIP_DIRS.contains(&name.as_str()) {
continue;
}
let child = join(&rel, &name);
// Roots are not searched for nested modules (`src/main/java` can be huge).
if found.iter().any(|f| *f == child || f.is_empty() && name == "src") {
@@ -155,6 +152,11 @@ pub fn detect(root: &Path) -> Vec<SourceFolder> {
}
continue;
}
// Skipping discovery is not an exclusion: marked hidden/conventional
// environments still need an explicit root for index and watcher filtering.
if name.starts_with('.') || SKIP_DIRS.contains(&name.as_str()) {
continue;
}
queue.push_back((child, depth + 1));
}
}
@@ -572,6 +574,96 @@ mod tests {
assert!(affects_roots(Path::new("code10/pyvenv.cfg")));
}
#[test]
fn marked_environments_are_detected_before_name_based_walk_skips() {
let dir = tree(&[
".venv/pyvenv.cfg",
".venv/Lib/site-packages/pkg/setup.py",
".conda/conda-meta/history",
"venv/pyvenv.cfg",
"nested/.custom/pyvenv.cfg",
"nested/.custom/lib/pkg/pyproject.toml",
"build/business.go",
"bin/business.go",
"env/business.go",
"dist/business.go",
".ordinary/setup.py",
]);
assert_eq!(
summary(&detect(dir.path())),
vec![
"[email protected]/conda-meta",
"[email protected]/pyvenv.cfg",
"nested/.custom=Excluded@nested/.custom/pyvenv.cfg",
"venv=Excluded@venv/pyvenv.cfg",
]
);
}
#[test]
fn marked_environment_detection_preserves_source_roots_and_user_overrides() {
let dir = tree(&["Cargo.toml", "src/pyvenv.cfg", ".venv/pyvenv.cfg", ".conda/conda-meta/history"]);
let detected = detect(dir.path());
assert!(detected.iter().any(|r| r.path == ".venv" && r.kind == RootKind::Excluded));
assert!(detected.iter().any(|r| r.path == "src" && r.kind == RootKind::Source));
let settings = ide_core::settings::ProjectStructureSettings {
source_roots: vec![".venv".into()],
unmarked: vec![".conda".into()],
..Default::default()
};
let effective = super::super::ProjectRoots::compute(detected, &settings);
assert!(effective.excluded_globs().is_empty());
assert_eq!(effective.root_for(".venv/app.py").unwrap().kind, RootKind::Source);
}
#[test]
fn environment_markers_require_the_expected_file_type_and_respect_walk_boundaries() {
let dir = tree(&[
"pyvenv.cfg",
"app.py",
".not_venv/pyvenv.cfg/",
".not_conda/conda-meta",
".hidden/nested/pyvenv.cfg",
"a/b/c/d/e/f/g/pyvenv.cfg",
"at/b/c/d/e/f/pyvenv.cfg",
]);
// An environment opened as the project remains browsable. Hidden parents and
// the existing depth budget are not traversed to discover more environments.
assert_eq!(summary(&detect(dir.path())), vec!["at/b/c/d/e/f=Excluded@at/b/c/d/e/f/pyvenv.cfg"]);
}
#[test]
fn detected_environment_roots_prune_vfs_walk_without_hiding_business_directories() {
let dir = tree(&[
".venv/pyvenv.cfg",
".venv/Lib/site-packages/pkg/setup.py",
"internal/build/build.go",
"env/business.go",
"bin/business.go",
"dist/business.go",
"service/go.mod",
]);
for i in 0..128 {
fs::write(dir.path().join(format!(".venv/Lib/site-packages/pkg/dep{i}.py")), "").unwrap();
}
let walk = |excludes: &[String]| {
let files = std::sync::Mutex::new(Vec::new());
ide_vfs::walk_files(dir.path(), excludes, |path| {
files.lock().unwrap().push(path.strip_prefix(dir.path()).unwrap().to_owned());
});
let mut files = files.into_inner().unwrap();
files.sort();
files
};
let before = walk(&[]);
let roots = super::super::ProjectRoots::compute(detect(dir.path()), &Default::default());
let after = walk(&roots.excluded_globs());
assert_eq!(before.len(), 135);
assert_eq!(after.len(), 5);
assert_eq!(after, before.into_iter().filter(|p| !p.starts_with(".venv")).collect::<Vec<_>>());
assert_eq!(roots.root_for("service/go.mod").unwrap().kind, RootKind::Source);
}
#[test]
fn first_ecosystem_wins_for_a_shared_folder() {
// A Gradle build with a frontend: `build` stays Gradle's, `src` is not a Node root.
+81 -9
Переглянути файл
@@ -30,12 +30,14 @@ pub enum SettingsScope {
/// Settings a project's own file can't hold: the IDE's MCP server, imported color schemes, and
/// what agents may do without asking (commands run without asking, the modes new tasks start in,
/// whether new tasks ask for approvals).
const USER_ONLY: [&[&str]; 5] = [
const USER_ONLY: [&[&str]; 6] = [
&["mcpServer"],
&["editor", "customSchemes"],
&["agentSecurity", "allowedCommands"],
&["agents", "defaults"],
&["agents", "newTaskApprovals"],
// OS notification centre: machine-local; projects must not enable/disable.
&["notifications", "systemNotifications"],
];
/// The [`USER_ONLY`] setting that writing `value` at `key` would set, as a dotted key.
@@ -439,13 +441,26 @@ impl SettingsStore {
#[serde(rename_all = "camelCase")]
pub struct JetBrainsSettings {
pub entries: Vec<String>,
/// Entry name → text, for `colors/*.icls` and the `options/*.xml` files OpenIDEA reads.
/// Entry name → text, for the files OpenIDEA reads: `colors/*.icls`, `keymaps/*.xml`,
/// `codestyles/*.xml` and some of `options/`.
pub files: BTreeMap<String, String>,
}
const JETBRAINS_MARKER: &str = "IntelliJ IDEA Global Settings";
const JETBRAINS_OPTIONS: [&str; 4] =
["options/editor-font.xml", "options/colors.scheme.xml", "options/editor.xml", "options/ide.general.xml"];
const JETBRAINS_OPTIONS: [&str; 9] = [
"options/editor-font.xml",
"options/terminal-font.xml",
"options/colors.scheme.xml",
"options/code.style.schemes.xml",
"options/editor.xml",
"options/ide.general.xml",
// The active keymap is stored per operating system.
"options/mac/keymap.xml",
"options/windows/keymap.xml",
"options/linux/keymap.xml",
];
/// Folders whose files are all read: (folder, extension).
const JETBRAINS_READ_DIRS: [(&str, &str); 3] = [("colors/", ".icls"), ("keymaps/", ".xml"), ("codestyles/", ".xml")];
const JETBRAINS_MAX_TEXT: u64 = 4 << 20;
/// The settings of a JetBrains IDE: an exported `settings.zip`, or the IDE's own settings folder
@@ -456,11 +471,23 @@ pub fn read_jetbrains_settings(path: &Path) -> IdeResult<JetBrainsSettings> {
fn is_mapped_jetbrains_file(name: &str) -> bool {
JETBRAINS_OPTIONS.contains(&name)
|| name.strip_prefix("colors/").is_some_and(|n| !n.contains('/') && n.ends_with(".icls"))
|| JETBRAINS_READ_DIRS
.iter()
.any(|(dir, ext)| name.strip_prefix(dir).is_some_and(|n| !n.contains('/') && n.ends_with(ext)))
}
/// Folders of the settings folder whose files are listed (their names say what the user customised).
const JETBRAINS_LISTED_DIRS: [&str; 6] = ["options", "colors", "keymaps", "codestyles", "templates", "inspection"];
const JETBRAINS_LISTED_DIRS: [&str; 9] = [
"options",
"options/mac",
"options/windows",
"options/linux",
"colors",
"keymaps",
"codestyles",
"templates",
"inspection",
];
fn read_jetbrains_folder(dir: &Path) -> IdeResult<JetBrainsSettings> {
use std::io::Read;
@@ -934,11 +961,25 @@ mod tests {
("options/editor-font.xml", "<application/>"),
("options/vcs.xml", "<application/>"),
("keymaps/macOS.xml", "<keymap/>"),
("keymaps/nested/ignored.xml", "<keymap/>"),
("codestyles/Default.xml", "<code_scheme/>"),
("options/mac/keymap.xml", "<application/>"),
("options/terminal-font.xml", "<application/>"),
],
);
let read = read_jetbrains_settings(&ok).unwrap();
assert_eq!(read.entries.len(), 5);
assert_eq!(read.files.keys().collect::<Vec<_>>(), ["colors/_@user_Darcula.icls", "options/editor-font.xml"]);
assert_eq!(read.entries.len(), 9);
assert_eq!(
read.files.keys().collect::<Vec<_>>(),
[
"codestyles/Default.xml",
"colors/_@user_Darcula.icls",
"keymaps/macOS.xml",
"options/editor-font.xml",
"options/mac/keymap.xml",
"options/terminal-font.xml"
]
);
assert!(read_jetbrains_settings(&write("other.zip", &[("options/editor.xml", "")])).is_err());
std::fs::write(tmp.path().join("plain.zip"), "not a zip").unwrap();
assert!(read_jetbrains_settings(&tmp.path().join("plain.zip")).is_err());
@@ -957,18 +998,31 @@ mod tests {
put("colors/nested/ignored.icls", "<scheme/>");
put("options/editor-font.xml", "<application/>");
put("options/vcs.xml", "<application/>");
put("options/mac/keymap.xml", "<application/>");
put("keymaps/macOS.xml", "<keymap/>");
put("codestyles/Default.xml", "<code_scheme/>");
put("plugins/Tools/lib/tools.jar", "jar");
let read = read_jetbrains_settings(&config).unwrap();
assert_eq!(read.files.keys().collect::<Vec<_>>(), ["colors/_@user_Darcula.icls", "options/editor-font.xml"]);
assert_eq!(
read.files.keys().collect::<Vec<_>>(),
[
"codestyles/Default.xml",
"colors/_@user_Darcula.icls",
"keymaps/macOS.xml",
"options/editor-font.xml",
"options/mac/keymap.xml"
]
);
assert_eq!(
read.entries,
[
"options/editor-font.xml",
"options/vcs.xml",
"options/mac/keymap.xml",
"colors/_@user_Darcula.icls",
"keymaps/macOS.xml",
"codestyles/Default.xml",
"installed.txt"
]
);
@@ -1219,4 +1273,22 @@ mod tests {
std::fs::write(project.join(".openidea/settings.toml"), "[agents]\nnewTaskApprovals = \"bypass\"\n").unwrap();
assert_eq!(settings.reload().agents.new_task_approvals, NewTaskApprovals::Ask);
}
#[test]
fn system_notifications_are_a_user_setting() {
let tmp = tempfile::tempdir().unwrap();
let config = tmp.path().join("config");
let project = tmp.path().join("project");
std::fs::create_dir_all(project.join(".openidea")).unwrap();
std::fs::write(project.join(".openidea/settings.toml"), "[notifications]\nsystemNotifications = false\n")
.unwrap();
let settings = SettingsStore::load(&config, Some(&project));
assert!(settings.effective().notifications.system_notifications);
assert!(settings.set(SettingsScope::Project, "notifications.systemNotifications", json!(false)).is_err());
let s = settings.set(SettingsScope::Global, "notifications.systemNotifications", json!(false)).unwrap();
assert!(!s.notifications.system_notifications);
std::fs::write(project.join(".openidea/settings.toml"), "[notifications]\nsystemNotifications = true\n")
.unwrap();
assert!(!settings.reload().notifications.system_notifications);
}
}
+7 -6
Переглянути файл
@@ -152,12 +152,13 @@ Sub-tables such as `[editor.general]`, `[editor.appearance]`, `[editor.completio
### `[notifications]`
| Key | Default | Description |
| --------------------------- | ----------- | ------------------------------------------------------------ |
| `balloons` | `true` | **Display balloon notifications**. |
| `sound` | `false` | **Play sound**. |
| `groups.<group-id>.display` | `"balloon"` | Popup type per group: `balloon`, `sticky` or `none`. |
| `groups.<group-id>.log` | `true` | Also list the notification in the Notifications tool window. |
| Key | Default | Description |
| --------------------------- | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `balloons` | `true` | **Display balloon notifications**. |
| `sound` | `false` | **Play sound**. |
| `systemNotifications` | `true` | **Enable system notifications**. When a balloon is shown and no OpenIDEA window is focused, the same title and text also go to the OS notification centre. On by default; client/local only. Click focuses the window that raised the toast; balloon actions stay in the IDE. **Windows:** a click is reported only while the toast is on screen, not after it moves to Action Center. Desktop `permission_state` always reports Granted without an OS prompt — that is not proof Do Not Disturb or system notification settings allow delivery. |
| `groups.<group-id>.display` | `"balloon"` | Popup type per group: `balloon`, `sticky` or `none`. |
| `groups.<group-id>.log` | `true` | Also list the notification in the Notifications tool window. |
### `[terminal]`
+7 -6
Переглянути файл
@@ -152,12 +152,13 @@ exclude = ["**/.git", "**/node_modules", "**/target", "**/dist"]
### `[notifications]`
| 键 | 默认值 | 说明 |
| --------------------------- | ----------- | --------------------------------------------------- |
| `balloons` | `true` | **显示气球通知**。 |
| `sound` | `false` | **播放声音**。 |
| `groups.<group-id>.display` | `"balloon"` | 每个分组的弹出方式:`balloon`、`sticky` 或 `none`。 |
| `groups.<group-id>.log` | `true` | 同时在通知工具窗口中列出。 |
| 键 | 默认值 | 说明 |
| --------------------------- | ----------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `balloons` | `true` | **显示气球通知**。 |
| `sound` | `false` | **播放声音**。 |
| `systemNotifications` | `true` | **启用系统通知**。气球通知显示且没有任何 OpenIDEA 窗口处于焦点时,相同的标题和正文也会发到操作系统通知中心。默认开启;仅客户端/本机设置。点击会聚焦发出该通知的窗口;气球操作仍只在 IDE 内。**Windows:**仅在 toast 仍显示在屏幕上时可收到点击,进入操作中心后不再触发。桌面端 `permission_state` 始终返回 Granted 且不会弹出系统授权——这并不表示勿扰模式或系统通知设置允许显示。 |
| `groups.<group-id>.display` | `"balloon"` | 每个分组的弹出方式:`balloon`、`sticky` 或 `none`。 |
| `groups.<group-id>.log` | `true` | 同时在通知工具窗口中列出。 |
### `[terminal]`
+83
Переглянути файл
@@ -819,3 +819,86 @@ test("keeps ordered, bulleted and task list markers unclipped inside measured ro
expect(cb.offsetFromRowLeft).toBeGreaterThanOrEqual(0);
}
});
test("indents process-run thoughts and tool calls clearly and aligns output-less tool icons", async ({ page }) => {
await openReply(page, "All checks passed.");
await page.evaluate(async (task) => {
const storePath = "/src/features/agents/store.ts";
const store = await import(storePath);
store.useAgents.setState({
tasks: new Map([[task.id, { ...task, status: "running" as const }]]),
entries: new Map([
[
task.id,
[
{ type: "thought", text: "**Checking CI Status**\n\nInspecting workflow runs." },
{
type: "tool",
id: "t1",
title: "gh pr checks 3631 --repo l0ng-ai/openidea",
kind: "execute",
status: "completed",
locations: [],
output: "All checks pending",
diffs: [],
},
{ type: "thought", text: "**Tracking Continuous Integration**\n\nWaiting for E2E." },
{
type: "tool",
id: "t2",
title: "read_bash",
kind: "other",
status: "completed",
locations: [],
output: "E2E pass",
diffs: [],
},
{
type: "tool",
id: "t3",
title: "read_bash",
kind: "other",
status: "running",
locations: [],
output: "",
diffs: [],
},
],
],
]),
});
store.openTaskInEditorLocation(task.id);
}, TASK);
const stream = page.locator("[class*='_stream_']:visible");
const summary = stream.locator("[class*='_processSummary_']").first();
await summary.click();
await expect(stream.getByText("Checking CI Status")).toBeVisible();
const layout = await stream.evaluate((root) => {
const summaryChevron = root.querySelector<SVGElement>("[class*='_processChevron_']")!.getBoundingClientRect();
const processBody = root.querySelector<HTMLElement>("[class*='_processBody_']")!.getBoundingClientRect();
const thoughtChevron = root.querySelector<SVGElement>("[class*='_thoughtChevron_']")!.getBoundingClientRect();
const toolRows = [...root.querySelectorAll<HTMLElement>("[class*='_tool_']")];
const expandableToolChevron = toolRows[0]!
.querySelector<SVGElement>("[class*='_toolChevron_']")!
.getBoundingClientRect();
const completedReadIcon = [...toolRows[1]!.querySelectorAll("svg")].at(-1)!.getBoundingClientRect();
const runningReadIcon = toolRows[2]!.querySelector("svg")!.getBoundingClientRect();
return {
summaryChevronCenter: summaryChevron.left + summaryChevron.width / 2,
guideLeft: processBody.left,
summaryToThoughtIndent: thoughtChevron.left - summaryChevron.left,
thoughtToToolIndent: expandableToolChevron.left - thoughtChevron.left,
iconLeftDiff: Math.abs(completedReadIcon.left - runningReadIcon.left),
};
});
// Guide line drops from the center of the process summary chevron.
expect(Math.abs(layout.guideLeft - layout.summaryChevronCenter)).toBeLessThanOrEqual(1.5);
// Thoughts indent clearly inside the process run, and tool calls indent under their thought step.
expect(layout.summaryToThoughtIndent).toBeGreaterThanOrEqual(20);
expect(layout.thoughtToToolIndent).toBeGreaterThanOrEqual(14);
// Output-less running tool rows align their kind icon with expandable tool rows.
expect(layout.iconLeftDiff).toBeLessThanOrEqual(1);
});
+43
Переглянути файл
@@ -0,0 +1,43 @@
import { EditorView } from "@codemirror/view";
import { commands, type InlayHint, type Range } from "../src/platform/ipc";
import { setInvokeRoute } from "../src/platform/tauriCore";
import { lspDoc } from "../src/editor/lsp/lsp";
import { inlayExtension } from "../src/editor/lsp/inlay";
import { lspTheme } from "../src/editor/lsp/theme";
const requests: { range: Range; resolve: (hints: InlayHint[]) => void }[] = [];
setInvokeRoute(() => null);
commands.lspInlayHints = async (_doc, range) =>
new Promise((resolve) => requests.push({ range, resolve: (data) => resolve({ status: "ok", data }) }));
const view = new EditorView({
parent: document.body,
doc: Array.from({ length: 2000 }, (_, i) => `let item${i} = value;`).join("\n"),
extensions: [
EditorView.theme({ "&": { height: "400px" }, ".cm-scroller": { overflow: "auto" } }),
lspTheme,
lspDoc.of({ doc: 1, path: "demo.rs", language: "rust", uiMode: "Rust", readOnly: false }),
inlayExtension(),
],
});
Object.assign(window, {
inlayTest: {
count: () => requests.length,
resolve(index: number) {
const request = requests[index]!;
request.resolve([
{
position: { line: request.range.start.line + 1, col: 4 },
label: `hint-${index}`,
kind: "type",
paddingLeft: false,
paddingRight: false,
tooltip: null,
parts: [],
},
]);
},
destroy: () => view.destroy(),
},
});
+9
Переглянути файл
@@ -0,0 +1,9 @@
<!doctype html>
<html>
<head>
<meta charset="UTF-8" />
</head>
<body>
<script type="module" src="./inlayRequests.fixture.ts"></script>
</body>
</html>
+18
Переглянути файл
@@ -0,0 +1,18 @@
import { expect, test } from "@playwright/test";
type Probe = { count(): number; resolve(index: number): void };
test("scrolling does not let an old viewport response replace current inlay hints", async ({ page }) => {
await page.goto("/e2e/inlayRequests.html");
const count = () => page.evaluate(() => (window as unknown as { inlayTest: Probe }).inlayTest.count());
await expect.poll(count).toBe(1);
await page.locator(".cm-scroller").evaluate((el) => {
el.scrollTop = 12000;
});
await expect.poll(count).toBe(2);
await page.evaluate(() => (window as unknown as { inlayTest: Probe }).inlayTest.resolve(1));
await expect(page.locator(".cm-lsp-inlay")).toHaveText("hint-1");
await page.evaluate(() => (window as unknown as { inlayTest: Probe }).inlayTest.resolve(0));
await page.waitForTimeout(500);
await expect(page.locator(".cm-lsp-inlay")).toHaveText("hint-1");
});
+6
Переглянути файл
@@ -0,0 +1,6 @@
id = "gherkin"
name = "Gherkin"
extensions = ["feature"]
line-comment = "#"
indent = { tab-size = 2, insert-spaces = true }
ui-mode = "Gherkin"
+4
Переглянути файл
@@ -36,6 +36,10 @@ body,
opacity: 0;
pointer-events: none;
}
/* A question asked while the window opens (Trust Project?) shows over the splash (platform/splash.ts). */
.splash.splash-under-dialogs {
z-index: calc(var(--z-dialog, 900) - 1);
}
:root[data-theme^="dark"] .splash {
color: var(--fg-muted, var(--boot-fg, #8c8f95));
}
+1
Переглянути файл
@@ -16,6 +16,7 @@ dunce.workspace = true
[dependencies]
tauri = { version = "2", features = [] }
tauri-plugin-opener = "2"
tauri-plugin-notification = "2.8.1"
tauri-plugin-dialog = { version = "2", default-features = false, features = ["xdg-portal"] }
tauri-plugin-mcp-bridge = "0.13"
tauri-plugin-window-state = "2"
+1
Переглянути файл
@@ -16,6 +16,7 @@
"core:webview:allow-set-webview-background-color",
"opener:default",
"opener:allow-reveal-item-in-dir",
"notification:default",
"dialog:default",
"core:window:allow-destroy",
"core:window:allow-close",
+9
Переглянути файл
@@ -348,6 +348,15 @@ pub async fn debug_free_port(window: Window, state: State<'_, AppState>) -> IdeR
ide_host::ops::debug::debug_free_port(&state.host, window.label()).await
}
#[tauri::command]
#[specta::specta]
pub async fn debug_unity_processes(
window: tauri::Window,
state: State<'_, AppState>,
) -> IdeResult<Vec<attach::AttachableProcess>> {
ide_host::ops::debug::debug_unity_processes(&state.host, window.label()).await
}
/// Remote JVM Debug in listen mode: waits (cancellable through `request`) for the remote
/// JVM to connect to `host:port`; returns the loopback port java-debug attaches to.
#[tauri::command]
+4
Переглянути файл
@@ -35,6 +35,7 @@ pub mod lsp;
pub mod mcp;
pub mod nav;
pub mod notebook;
pub mod notification;
pub mod perf;
pub mod plugin;
pub mod profiler;
@@ -199,6 +200,7 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
clipboard::clipboard_has_image,
clipboard::clipboard_image,
clipboard::clipboard_set_file_list,
notification::show_system_notification,
fonts::system_font_families,
doc::doc_open,
doc::doc_open_virtual,
@@ -487,6 +489,7 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
sdk::sdk_python_interpreter,
sdk::sdk_python_effective,
sdk::sdk_php_effective,
sdk::sdk_jdk_at,
sdk::sdk_container_python,
sdk::sdk_container_python_refresh,
sdk::sdk_php_xdebug,
@@ -551,6 +554,7 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
debug::debug_data_breakpoint_info,
debug::debug_attachable_processes,
debug::debug_free_port,
debug::debug_unity_processes,
debug::debug_listen_for_jvm,
debug::debug_redefine_classes,
debug::debug_jvm_memory_classes,
+12
Переглянути файл
@@ -0,0 +1,12 @@
//! IPC for OS notification centre toasts.
use ide_core::IdeResult;
use tauri::{AppHandle, Window};
/// When a balloon is shown and OpenIDEA is unfocused, mirror it to the OS.
#[tauri::command]
#[specta::specta]
pub fn show_system_notification(app: AppHandle, window: Window, title: String, body: String) -> IdeResult<()> {
crate::system_notifications::show(&app, window.label(), title, body);
Ok(())
}
+7
Переглянути файл
@@ -17,6 +17,13 @@ pub async fn sdk_detect(window: Window, state: State<'_, AppState>, kind: SdkKin
ide_host::ops::sdk::sdk_detect(&state.host, window.label(), kind).await
}
/// The JDK whose home is `path`, as the SDK list shows it; `None` when it is no JDK home.
#[tauri::command]
#[specta::specta]
pub async fn sdk_jdk_at(path: String) -> IdeResult<Option<Sdk>> {
ide_host::ops::sdk::sdk_jdk_at(path).await
}
/// The Python interpreters of the recently opened projects, each with its project.
#[tauri::command]
#[specta::specta]
+7 -1
Переглянути файл
@@ -330,7 +330,13 @@ pub fn menu_model(app: AppHandle, state: State<'_, AppState>, menu_state: State<
/// disabled in place (no rebuild).
#[tauri::command]
#[specta::specta]
pub fn menu_set_disabled(app: AppHandle, menu_state: State<'_, MenuState>, ids: Vec<String>) {
pub fn menu_set_disabled(window: WebviewWindow, app: AppHandle, menu_state: State<'_, MenuState>, ids: Vec<String>) {
// The window whose menu runs: a project window also while its Settings window is focused.
if menu::native_menu_bar()
&& windows::target_window(&app).is_some_and(|target| !owns_menu_config(window.label(), target.label()))
{
return;
}
let disabled: std::collections::HashSet<String> = ids.into_iter().collect();
if *menu_state.disabled.lock() == disabled {
return;
+19 -15
Переглянути файл
@@ -26,6 +26,7 @@ mod relaunch;
mod remote_container;
mod remote_dev;
mod remote_wsl;
mod system_notifications;
mod state;
mod theme_frame;
@@ -121,7 +122,10 @@ pub fn run() {
// Install before window-state restores maximized geometry during window creation.
#[cfg(windows)]
let app = app.plugin(window_work_area::init());
let app = app.plugin(tauri_plugin_opener::init()).plugin(tauri_plugin_dialog::init());
let app = app
.plugin(tauri_plugin_opener::init())
.plugin(tauri_plugin_notification::init())
.plugin(tauri_plugin_dialog::init());
#[cfg(target_os = "linux")]
let app = app.plugin(linux_window_state::plugin());
#[cfg(not(target_os = "linux"))]
@@ -220,6 +224,7 @@ pub fn run() {
windows::report_cli_error(app.handle(), error);
}
app.manage(application_focus::ApplicationFocus::default());
system_notifications::init(app.handle());
#[cfg(target_os = "macos")]
macos::intercept_system_quit(app.handle());
#[cfg(target_os = "macos")]
@@ -368,25 +373,24 @@ pub(crate) fn dispatch_menu_action(app: &tauri::AppHandle, id: &str) {
let Some(route) = menu::route(&menu::spec(menu::Os::current()), id) else { return };
match windows::target_window(app) {
Some(w) => {
// App-level items of an auxiliary window go to its project window. Settings is modal for it:
// nothing else gets through. Others handle their own items; Close Tab closes the window.
let label = match windows::auxiliary(w.label()) {
Some((_, parent))
if matches!(
route.action.as_str(),
"app.quit" | "file.settings" | "file.projectStructure" | "file.newProjectsSettings"
) =>
{
parent
// The window to bring back to the front once what the action shows is closed (Settings).
let mut return_to = None;
let label = match windows::menu_destination(w.label(), &route.action) {
windows::MenuDestination::Own => w.label(),
windows::MenuDestination::Parent { label, raise } => {
if raise && let Some(parent) = app.get_webview_window(label) {
windows::focus(&parent);
return_to = Some(w.label());
}
label
}
Some((kind, _)) if kind.modal() => return,
Some(_) if route.action == "editor.closeTab" => {
windows::MenuDestination::Close => {
let _ = w.close();
return;
}
_ => w.label(),
};
if let Err(e) = app.emit_to(label, menu::MENU_EVENT, &route) {
let event = menu::MenuEvent { route: &route, return_to };
if let Err(e) = app.emit_to(label, menu::MENU_EVENT, &event) {
tracing::warn!("failed to deliver menu event {id}: {e}");
}
}
+11
Переглянути файл
@@ -904,6 +904,17 @@ pub struct MenuRoute {
pub arg: Option<String>,
}
/// Payload of [`MENU_EVENT`]: the route, and the window that was in front when the item was
/// chosen if the action runs in another one (a Settings window's project window).
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MenuEvent<'a> {
#[serde(flatten)]
pub route: &'a MenuRoute,
#[serde(skip_serializing_if = "Option::is_none")]
pub return_to: Option<&'a str>,
}
/// Maps a clicked item id to the action to run. `None` for ids that are not
/// IDE items (native roles, placeholders).
pub fn route(spec: &[Entry], id: &str) -> Option<MenuRoute> {
+1
Переглянути файл
@@ -179,6 +179,7 @@ impl AppState {
/// Called on the event-loop thread (window destruction, the `close_project`
/// command), so it must not wait for the project's workers to shut down.
pub fn close_project(&self, window: &str) {
crate::system_notifications::clear_window(window);
self.remote_dev.disconnect(window);
self.host.close_project_detached(window);
}
+150
Переглянути файл
@@ -0,0 +1,150 @@
//! OS notification centre toasts for in-IDE balloons while OpenIDEA is unfocused.
//!
//! Driven by `show_system_notification` from the notification store. Honour
//! global `[notifications].systemNotifications`; suppressed while any window is
//! active. Click focuses the window that raised the toast — balloon actions stay
//! in the IDE.
use parking_lot::Mutex;
use std::collections::HashMap;
use std::sync::LazyLock;
use std::sync::atomic::{AtomicBool, AtomicI32, Ordering};
use tauri::{AppHandle, Manager};
use tauri_plugin_notification::{NotificationExt, PermissionState};
const MAX_TARGETS: usize = 64;
struct State {
ready: AtomicBool,
next_id: AtomicI32,
/// Native notification id → owning window label.
targets: Mutex<HashMap<i32, String>>,
}
impl State {
fn new() -> Self {
Self { ready: AtomicBool::new(false), next_id: AtomicI32::new(1), targets: Mutex::new(HashMap::new()) }
}
fn put_target(&self, id: i32, window: String) {
let mut targets = self.targets.lock();
targets.insert(id, window);
while targets.len() > MAX_TARGETS {
let oldest = targets.keys().copied().min();
if let Some(oldest) = oldest {
targets.remove(&oldest);
} else {
break;
}
}
}
fn take_target(&self, id: i32) -> Option<String> {
self.targets.lock().remove(&id)
}
fn clear_window(&self, window: &str) {
self.targets.lock().retain(|_, w| w != window);
}
}
static STATE: LazyLock<State> = LazyLock::new(State::new);
/// Registers the notification plugin's activation handler once.
pub fn init(app: &AppHandle) {
if STATE.ready.swap(true, Ordering::AcqRel) {
return;
}
let handle = app.clone();
if let Err(e) = app.notification().on_action(move |performed| {
if performed.action_id() != "tap" {
return;
}
let Some(n) = performed.notification() else { return };
activate(&handle, n.id());
}) {
tracing::warn!("system notifications: cannot register action handler: {e}");
STATE.ready.store(false, Ordering::Release);
}
}
/// Project closed or window replaced: drop click targets for that owner.
pub fn clear_window(window: &str) {
STATE.clear_window(window);
}
/// Show an OS toast when the setting is on and no OpenIDEA window is focused.
pub fn show(app: &AppHandle, window: &str, title: String, body: String) {
let owner = crate::state::AppState::owner_window(window).to_owned();
let app = app.clone();
let _ = app.clone().run_on_main_thread(move || deliver(&app, &owner, &title, &body));
}
fn deliver(app: &AppHandle, window: &str, title: &str, body: &str) {
let Some(state) = app.try_state::<crate::state::AppState>() else { return };
let settings = state.host.global_settings.effective();
if !settings.notifications.system_notifications {
return;
}
if crate::application_focus::application_active(app) {
return;
}
init(app);
if !STATE.ready.load(Ordering::Acquire) {
return;
}
// Desktop always reports Granted without an OS prompt (not proof of visible delivery).
let granted = app
.notification()
.permission_state()
.ok()
.or_else(|| app.notification().request_permission().ok())
.is_some_and(|s| s == PermissionState::Granted);
if !granted {
return;
}
let id = STATE.next_id.fetch_add(1, Ordering::Relaxed);
STATE.put_target(id, window.to_owned());
let mut builder = app.notification().builder().id(id).title(title).body(body);
if settings.notifications.sound {
builder = builder.sound("default");
}
if let Err(e) = builder.show() {
tracing::debug!("system notification not shown: {e}");
STATE.take_target(id);
}
}
fn activate(app: &AppHandle, id: i32) {
let Some(window_label) = STATE.take_target(id) else { return };
let app = app.clone();
let _ = app.clone().run_on_main_thread(move || {
let Some(window) = app.get_webview_window(&window_label) else { return };
let _ = window.unminimize();
let _ = window.show();
let _ = window.set_focus();
});
}
#[cfg(test)]
mod tests {
use super::*;
use ide_core::settings::NotificationSettings;
#[test]
fn settings_default_on() {
assert!(NotificationSettings::default().system_notifications);
}
#[test]
fn clear_window_drops_targets() {
let state = State::new();
state.put_target(1, "w1".into());
state.put_target(2, "w2".into());
state.clear_window("w1");
assert!(state.take_target(1).is_none());
assert_eq!(state.take_target(2).as_deref(), Some("w2"));
}
}
+51 -2
Переглянути файл
@@ -360,8 +360,8 @@ impl AuxKind {
self != AuxKind::Settings
}
/// Modal for its parent: menu items other than app-level ones are dropped.
pub fn modal(self) -> bool {
/// Has no actions of its own: menu items run in its project window.
fn runs_menu_in_parent(self) -> bool {
self == AuxKind::Settings
}
@@ -386,6 +386,34 @@ pub fn auxiliary(label: &str) -> Option<(AuxKind, &str)> {
})
}
/// Where a menu item chosen while window `label` is focused runs.
#[derive(Debug, PartialEq, Eq)]
pub enum MenuDestination<'a> {
/// The window's own frontend.
Own,
/// The project window `label`; `raise` brings it to the front so what the action shows is seen.
Parent { label: &'a str, raise: bool },
/// The window itself is the tab: Close Tab closes it.
Close,
}
/// Actions an auxiliary window always leaves to its project window.
const PARENT_ACTIONS: [&str; 4] = ["app.quit", "file.settings", "file.projectStructure", "file.newProjectsSettings"];
/// Where menu item `action` runs while window `label` is focused. As in IDEA, the menu stays usable
/// with Settings open: it runs in the project window, whose enablement (no focused editor) the menu shows.
pub fn menu_destination<'a>(label: &'a str, action: &str) -> MenuDestination<'a> {
match auxiliary(label) {
None => MenuDestination::Own,
Some((_, parent)) if PARENT_ACTIONS.contains(&action) => {
MenuDestination::Parent { label: parent, raise: false }
}
Some((kind, parent)) if kind.runs_menu_in_parent() => MenuDestination::Parent { label: parent, raise: true },
Some(_) if action == "editor.closeTab" => MenuDestination::Close,
Some(_) => MenuDestination::Own,
}
}
/// The project window an auxiliary window belongs to (`settings-main` → `main`).
pub fn auxiliary_parent(label: &str) -> Option<&str> {
auxiliary(label).map(|(_, parent)| parent)
@@ -2349,6 +2377,27 @@ mod tests {
assert_eq!(sorted_labels(labels.into_iter().filter(|l| auxiliary_parent(l).is_none())), ["main", "project-2"]);
}
#[test]
fn menu_items_chosen_in_settings_run_in_its_project_window() {
use MenuDestination::*;
for (label, action, expected) in [
("main", "app.about", Own),
("main", "editor.closeTab", Own),
// #3625: Settings has no actions of its own; the rest of the menu runs in the project window.
("settings-main", "app.checkForUpdates", Parent { label: "main", raise: true }),
("settings-project-2", "file.newFile", Parent { label: "project-2", raise: true }),
("settings-main", "editor.closeTab", Parent { label: "main", raise: true }),
("settings-main", "file.settings", Parent { label: "main", raise: false }),
("settings-main", "app.quit", Parent { label: "main", raise: false }),
("comparison-main-0", "app.quit", Parent { label: "main", raise: false }),
("comparison-main-0", "editor.closeTab", Close),
("diff-main-1", "vcs.diff.next", Own),
("deployment-main", "app.about", Own),
] {
assert_eq!(menu_destination(label, action), expected, "{label} {action}");
}
}
#[test]
fn settings_bounds_fit_current_work_area() {
for (parent, size, work, expected) in [
+3
Переглянути файл
@@ -165,6 +165,7 @@ debug_step_in_target trusted project_host bin
debug_step_in_targets trusted project_host bindings async
debug_stop always project_host bindings async
debug_threads trusted project_host bindings async
debug_unity_processes trusted project_host bindings async
debug_variables trusted project_host bindings async
dependency_versions trusted project_host bindings async
deploy_compare trusted project_host bindings async
@@ -512,6 +513,7 @@ scaffold_requirements always project_host bin
sdk_container_python trusted project_host bindings sync
sdk_container_python_refresh trusted project_host bindings async
sdk_detect trusted project_host bindings async
sdk_jdk_at trusted project_host bindings async
sdk_locate_tools trusted project_host bindings async
sdk_php_composer_install trusted project_host bindings async
sdk_php_effective trusted project_host bindings sync
@@ -535,6 +537,7 @@ settings_list_jetbrains_ides always desktop bin
settings_read_jetbrains always desktop bindings async
settings_removed_theme always project_host bindings sync
settings_set always project_host bindings sync
show_system_notification trusted desktop bindings sync
spell_check always project_host bindings async
spell_suggest always project_host bindings async
spring_route_sources trusted desktop bindings sync
+69 -3
Переглянути файл
@@ -331,6 +331,8 @@ export const commands = {
* false when the clipboard stayed busy; the caller keeps working either way.
*/
clipboardSetFileList: (paths: string[]) => typedError<boolean, IdeError>(__TAURI_INVOKE("clipboard_set_file_list", { paths })),
/** When a balloon is shown and OpenIDEA is unfocused, mirror it to the OS. */
showSystemNotification: (title: string, body: string) => typedError<null, IdeError>(__TAURI_INVOKE("show_system_notification", { title, body })),
/**
* Every installed family, sorted, each flagged monospaced or not. Read on
* first use (off the command threads), cached, and re-queried on `refresh`.
@@ -1094,6 +1096,26 @@ export const commands = {
sdkPythonEffective: (near: string | null) => typedError<string | null, IdeError>(__TAURI_INVOKE("sdk_python_effective", { near })),
/** The PHP interpreter chosen in Settings › Languages & Frameworks › PHP; `None`: the `php` on `PATH`. */
sdkPhpEffective: () => typedError<string | null, IdeError>(__TAURI_INVOKE("sdk_php_effective")),
/** The JDK whose home is `path`, as the SDK list shows it; `None` when it is no JDK home. */
sdkJdkAt: (path: string) => typedError<{
/**
* Executable (`python`, `node`, `pnpm`) or directory (Rust toolchain bin
* dir, GOROOT, TypeScript `lib` dir) that the setting stores.
*/
path: IpcPath,
/** Display name, e.g. `Python 3.12 (.venv)` or `stable-aarch64-apple-darwin`. */
name: string,
version: string | null,
/**
* Where it was found: `venv` | `system` | `pyenv` | `conda` | `uv` | `nvm` |
* `rustup` | `bundled` | `workspace` | `path` …
*/
source: string,
/** Environment / toolchain root (virtualenv dir, rustup toolchain dir, GOROOT). */
home: IpcPath | null,
/** Rust standard library sources, Go default GOPATH. */
extra: IpcPath | null,
} | null, IdeError>(__TAURI_INVOKE("sdk_jdk_at", { path })),
/** The project interpreter when it is a Docker or Compose run target's, with its snapshot. */
sdkContainerPython: () => typedError<{
/** The run target's id. */
@@ -1335,6 +1357,7 @@ export const commands = {
debugAttachableProcesses: () => typedError<AttachableProcess[], IdeError>(__TAURI_INVOKE("debug_attachable_processes")),
/** A loopback port that is free right now, for a debug agent the launch line starts. */
debugFreePort: () => typedError<number, IdeError>(__TAURI_INVOKE("debug_free_port")),
debugUnityProcesses: () => typedError<AttachableProcess[], IdeError>(__TAURI_INVOKE("debug_unity_processes")),
/**
* Remote JVM Debug in listen mode: waits (cancellable through `request`) for the remote
* JVM to connect to `host:port`; returns the loopback port java-debug attaches to.
@@ -1892,6 +1915,9 @@ export type AgentAcceptSkipped = {
reason: string,
};
/** Why a task needs the user's attention (native / in-app notify). */
export type AgentAttentionReason = "finished" | "input" | "failed";
/** A task the agent runs in the background while the conversation goes on. */
export type AgentBackgroundTask = {
id: string,
@@ -2098,7 +2124,9 @@ export type AgentEvent =
/** A model lookup started or completed, including unsuccessful lookups. */
{ type: "modelCatalog"; catalog: AgentModelCatalog } |
/** The installed or configured agent providers changed. */
{ type: "providers" };
{ type: "providers" } |
/** The task needs attention once (finished turn, explicit input, or failure). */
{ type: "attention"; task: string; eventId: string; reason: AgentAttentionReason };
/** A form the agent asks the user to fill in (ACP `elicitation/create`, form mode). */
export type AgentForm = {
@@ -2730,7 +2758,7 @@ export type AskpassKind =
/** Yes / no (an unknown host key); answered with `yes` or `no`. */
"confirm";
export type AttachKind = "java" | "node" | "python" | "dotnet" | "go" | "native";
export type AttachKind = "unity" | "java" | "node" | "python" | "dotnet" | "go" | "native";
export type AttachableProcess = {
pid: number,
@@ -3854,6 +3882,20 @@ export type DataSource_Serialize = {
pluginSourceId?: string | null,
};
/** Database settings: Query Execution and SQL Resolution Scopes. */
export type DatabaseSettings = {
/**
* A console's result sets show under the statements that produced them, in the editor,
* instead of in the Services view's result tabs.
*/
inEditorResults?: boolean,
/**
* Languages & Frameworks › SQL Resolution Scopes: the data source SQL in a file or folder
* resolves against (completion, inspections, navigation), most specific path first.
*/
resolutionScopes?: SqlResolutionScope[],
};
/** System Settings › Date Formats (Git log, Local History, blame). */
export type DateFormatSettings = {
/** Use `pattern` / `use24_hour` instead of the system locale's format. */
@@ -6698,6 +6740,11 @@ export type JavaSettings = {
jdtlsVmArgs?: string,
/** Share one JDT LS across builds in an ordinary project window; other windows remain separate. */
jdtlsShared?: boolean,
/**
* JDK homes added by hand (Platform Settings › SDKs › Add JDK from Disk…), listed with the
* detected ones.
*/
addedJdks?: string[],
/** Build Tools › Maven. */
maven?: MavenSettings,
/** Build Tools › Gradle. */
@@ -6726,7 +6773,10 @@ export type JdkVendor = {
*/
export type JetBrainsSettings = {
entries: string[],
/** Entry name → text, for `colors/*.icls` and the `options/*.xml` files OpenIDEA reads. */
/**
* Entry name → text, for the files OpenIDEA reads: `colors/*.icls`, `keymaps/*.xml`,
* `codestyles/*.xml` and some of `options/`.
*/
files: { [key in string]: string },
};
@@ -7957,6 +8007,8 @@ export type NotificationLevel = "info" | "warning" | "error";
export type NotificationSettings = {
balloons?: boolean,
sound?: boolean,
/** Mirror balloon notifications to the OS when no OpenIDEA window is focused. */
systemNotifications?: boolean,
/** Group id → display; groups not listed use their default. */
groups?: { [key in string]: NotificationGroupSettings },
};
@@ -9928,6 +9980,8 @@ export type Settings_Deserialize = {
scopes?: NamedScope[],
/** Appearance & Behavior › File Colors. */
fileColors?: FileColorSettings,
/** Database › Query Execution, Languages & Frameworks › SQL Resolution Scopes. */
database?: DatabaseSettings,
/** Plugin settings (`[contributes.settings]`): plugin id → its values by key. */
plugins?: { [key in string]: { [key in string]: unknown } },
};
@@ -9998,6 +10052,8 @@ export type Settings_Serialize = {
scopes: NamedScope[],
/** Appearance & Behavior › File Colors. */
fileColors: FileColorSettings,
/** Database › Query Execution, Languages & Frameworks › SQL Resolution Scopes. */
database: DatabaseSettings,
/** Plugin settings (`[contributes.settings]`): plugin id → its values by key. */
plugins: { [key in string]: { [key in string]: unknown } },
};
@@ -10146,6 +10202,16 @@ export type SpellingSettings = {
customDictionaries?: string[],
};
/** One row of SQL Resolution Scopes. */
export type SqlResolutionScope = {
/** Project-relative file or folder, `/`-separated; empty for the whole project. */
path?: string,
/** Data source id. */
dataSource?: string,
/** Schema unqualified names resolve in; empty for the data source's default. */
schema?: string,
};
export type SqlStatement = {
/**
* UTF-16 offsets of the statement text (whitespace trimmed, `;` excluded except
+2 -1
Переглянути файл
@@ -134,7 +134,8 @@ class LensWidget extends WidgetType {
const guides = this.inline
? null
: guideVars(Math.floor(this.indent / this.indentUnit), this.indentUnit, this.rainbow);
if (!this.inline) dom.style.paddingLeft = `${Math.round(this.indent * view.defaultCharacterWidth) + LINE_INSET}px`;
if (!this.inline)
dom.style.paddingLeft = `calc(${LINE_INSET}px + ${this.indent} * var(--openidea-space, ${view.defaultCharacterWidth}px))`;
if (guides) {
dom.style.setProperty("--openidea-guide-images", guides.images);
dom.style.setProperty("--openidea-guide-positions", guides.positions);
+44
Переглянути файл
@@ -0,0 +1,44 @@
import { foldable } from "@codemirror/language";
import { EditorState } from "@codemirror/state";
import { describe, expect, it } from "vitest";
import { gherkinSupport } from "./gherkin";
const DOC = `@smoke
Feature: Checkout
As a shopper
Background:
Given a cart
Scenario Outline: pay with <method>
When I pay with "<method>":
| amount |
| 10 |
Then I see:
"""
Thanks
"""
Examples:
| method |
| card |
`;
describe("Gherkin", () => {
const state = EditorState.create({ doc: DOC, extensions: gherkinSupport() });
const foldAt = (lineText: string) => {
const line = state.doc.line(DOC.split("\n").findIndex((l) => l.trim() === lineText) + 1);
const r = foldable(state, line.from, line.to);
return r ? state.doc.lineAt(r.to).text.trim() : null;
};
it("folds sections, step arguments and doc strings by indentation", () => {
expect(foldAt("Feature: Checkout")).toBe("| card |");
expect(foldAt("Background:")).toBe("Given a cart");
expect(foldAt("Scenario Outline: pay with <method>")).toBe("| card |");
expect(foldAt('When I pay with "<method>":')).toBe("| 10 |");
expect(foldAt('"""')).toBe('"""');
expect(foldAt("Given a cart")).toBeNull();
expect(foldAt("@smoke")).toBeNull();
});
});
+51
Переглянути файл
@@ -0,0 +1,51 @@
/**
* Gherkin (`.feature`): the legacy-mode highlighting (keywords in every Gherkin
* language, tags, tables, doc strings, `<placeholders>`) plus folding of each
* section, step argument and doc string by indentation, as Cucumber's outline does.
*/
import { LanguageSupport, StreamLanguage, foldService } from "@codemirror/language";
import { gherkin } from "@codemirror/legacy-modes/mode/gherkin";
import type { EditorState } from "@codemirror/state";
export const gherkinLanguage = StreamLanguage.define(gherkin);
const indentOf = (text: string) => /^\s*/.exec(text)![0].replace(/\t/g, " ").length;
/**
* A header line — `Feature:`, `Scenario:`, a step ending in `:` before its table, an
* opening `"""` — folds the more indented lines below it, up to the last of them.
*/
export function gherkinFold(
state: EditorState,
lineStart: number,
lineEnd: number,
): { from: number; to: number } | null {
const doc = state.doc;
const header = doc.lineAt(lineStart);
const text = header.text.trim();
if (!text || text.startsWith("#") || text.startsWith("|") || text.startsWith("@")) return null;
const docString = /^("""|```)/.exec(text);
if (docString) {
// The matching closing fence, at any indentation.
for (let n = header.number + 1; n <= doc.lines; n++) {
const line = doc.line(n);
if (line.text.trim().startsWith(docString[1]!))
return n > header.number + 1 ? { from: lineEnd, to: line.to } : null;
}
return null;
}
if (!text.endsWith(":") && !/^[^\s:]+(\s[^\s:]+)*:\s/.test(text)) return null;
const own = indentOf(header.text);
let last = header.number;
for (let n = header.number + 1; n <= doc.lines; n++) {
const line = doc.line(n);
if (!line.text.trim()) continue;
if (indentOf(line.text) <= own && !line.text.trim().startsWith("#")) break;
last = n;
}
return last > header.number ? { from: lineEnd, to: doc.line(last).to } : null;
}
export function gherkinSupport(): LanguageSupport {
return new LanguageSupport(gherkinLanguage, [foldService.of(gherkinFold)]);
}
+38 -10
Переглянути файл
@@ -1,4 +1,4 @@
import { afterEach, describe, expect, it } from "vitest";
import { afterEach, describe, expect, it, vi } from "vitest";
import { Compartment, EditorState, type Extension } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { indentUnit } from "@codemirror/language";
@@ -46,23 +46,25 @@ describe("indent guides", () => {
expect(guideVars(1, 4)).toBeNull();
expect(guideVars(3, 4)).toEqual({
images: "var(--openidea-guide), var(--openidea-guide)",
positions: "calc(0.5px + 4ch) 0, calc(0.5px + 8ch) 0",
positions: "calc(0.5px + 4 * var(--openidea-space, 1ch)) 0, calc(0.5px + 8 * var(--openidea-space, 1ch)) 0",
});
});
it("positions each guide the same way on lines of different depth", () => {
const v = mount(SOURCE);
expect(line(v, 1).classList.contains("cm-openidea-guides")).toBe(false);
expect(line(v, 2).style.getPropertyValue("--openidea-guide-positions")).toBe("calc(0.5px + 4ch) 0");
expect(line(v, 2).style.getPropertyValue("--openidea-guide-positions")).toBe(
"calc(0.5px + 4 * var(--openidea-space, 1ch)) 0",
);
expect(line(v, 3).style.getPropertyValue("--openidea-guide-positions")).toBe(
"calc(0.5px + 4ch) 0, calc(0.5px + 8ch) 0",
"calc(0.5px + 4 * var(--openidea-space, 1ch)) 0, calc(0.5px + 8 * var(--openidea-space, 1ch)) 0",
);
});
it("keeps guides through blank lines inside a block", () => {
const v = mount(SOURCE);
expect(line(v, 4).style.getPropertyValue("--openidea-guide-positions")).toBe(
"calc(0.5px + 4ch) 0, calc(0.5px + 8ch) 0",
"calc(0.5px + 4 * var(--openidea-space, 1ch)) 0, calc(0.5px + 8 * var(--openidea-space, 1ch)) 0",
);
});
@@ -77,7 +79,9 @@ describe("indent guides", () => {
]);
const [implLens, fnLens] = [...v.contentDOM.querySelectorAll<HTMLElement>(".cm-openidea-lens")];
expect(v.contentDOM.classList.contains("cm-openidea-guidesOn")).toBe(true);
expect(fnLens!.style.getPropertyValue("--openidea-guide-positions")).toBe("calc(0.5px + 4ch) 0");
expect(fnLens!.style.getPropertyValue("--openidea-guide-positions")).toBe(
"calc(0.5px + 4 * var(--openidea-space, 1ch)) 0",
);
expect(implLens!.style.getPropertyValue("--openidea-guide-positions")).toBe("");
});
});
@@ -136,7 +140,7 @@ describe("rainbow indent guides", () => {
expect(guideVars(1, 4, true)).toBeNull();
expect(guideVars(3, 4, true)).toEqual({
images: "var(--openidea-guide-1), var(--openidea-guide-2)",
positions: "calc(0.5px + 4ch) 0, calc(0.5px + 8ch) 0",
positions: "calc(0.5px + 4 * var(--openidea-space, 1ch)) 0, calc(0.5px + 8 * var(--openidea-space, 1ch)) 0",
});
const deep = guideVars(8, 2, true)!;
expect(deep.images.split(", ")).toEqual([1, 2, 3, 4, 5, 1, 2].map((n) => `var(--openidea-guide-${n})`));
@@ -156,7 +160,9 @@ describe("rainbow indent guides", () => {
expect(images(line(v, 2))).toBe("var(--openidea-guide-1)");
expect(images(line(v, 3))).toBe("var(--openidea-guide-1), var(--openidea-guide-2)");
expect(images(line(v, 4))).toBe("var(--openidea-guide-1), var(--openidea-guide-2)");
expect(positions(line(v, 4))).toBe("calc(0.5px + 4ch) 0, calc(0.5px + 8ch) 0");
expect(positions(line(v, 4))).toBe(
"calc(0.5px + 4 * var(--openidea-space, 1ch)) 0, calc(0.5px + 8 * var(--openidea-space, 1ch)) 0",
);
expect(images(line(v, 6))).toBe("var(--openidea-guide-1)");
});
@@ -170,7 +176,27 @@ describe("rainbow indent guides", () => {
spaces.destroy();
const tabs = mount(body("\t"), [EditorState.tabSize.of(4)], rainbowIndentGuides, "\t");
expect(images(deepest(tabs))).toBe(expected);
expect(positions(deepest(tabs)).split(", ")[1]).toBe("calc(0.5px + 8ch) 0");
expect(positions(deepest(tabs)).split(/, (?=calc)/)[1]).toBe("calc(0.5px + 8 * var(--openidea-space, 1ch)) 0");
});
it("measures a column as the font's space width, so a proportional font keeps guides in the indentation", () => {
const rect = vi.spyOn(HTMLElement.prototype, "getBoundingClientRect").mockImplementation(function (
this: HTMLElement,
) {
const sample = this.textContent ?? "";
const width = /^ +$/.test(sample) ? sample.length * 3.5 : 0;
return { width, height: 0, top: 0, left: 0, right: width, bottom: 0, x: 0, y: 0, toJSON: () => ({}) };
});
try {
const v = mount(SOURCE);
(v as unknown as { measure(): void }).measure();
expect(v.scrollDOM.style.getPropertyValue("--openidea-space")).toBe("3.5px");
v.destroy();
expect(v.scrollDOM.style.getPropertyValue("--openidea-space")).toBe("");
view = undefined;
} finally {
rect.mockRestore();
}
});
it("does not count a partial indent unit as a level", () => {
@@ -211,7 +237,9 @@ describe("rainbow indent guides", () => {
});
const lens = () => view!.contentDOM.querySelector<HTMLElement>(".cm-openidea-lens")!;
expect(images(lens())).toBe("var(--openidea-guide-1), var(--openidea-guide-2)");
expect(positions(lens())).toBe("calc(0.5px + 4ch) 0, calc(0.5px + 8ch) 0");
expect(positions(lens())).toBe(
"calc(0.5px + 4 * var(--openidea-space, 1ch)) 0, calc(0.5px + 8 * var(--openidea-space, 1ch)) 0",
);
view.dispatch({ effects: guides.reconfigure(indentGuides) });
expect(images(lens())).toBe("var(--openidea-guide), var(--openidea-guide)");
});
+33 -3
Переглянути файл
@@ -7,7 +7,9 @@
* the smaller level of their neighbours and code lens rows the level of the
* line they annotate (`guideVars`), so guides stay continuous. With rainbow
* guides each depth gets its own image, coloured from `--syn-rainbow-*`. The
* guide the caret is on takes the selected colour (`caretGuide`).
* guide the caret is on takes the selected colour (`caretGuide`). A column is
* the editor font's space width (`--openidea-space`, measured), not `ch`: in a
* proportional font a space is narrower than "0", and guides would drift into the code.
*/
import { countColumn, Facet, RangeSetBuilder, type EditorState, type Extension } from "@codemirror/state";
import { Decoration, EditorView, ViewPlugin, type DecorationSet, type ViewUpdate } from "@codemirror/view";
@@ -17,6 +19,11 @@ import { LINE_INSET } from "./lineInset";
/** How far (px) a guide sits left of its column, so a caret in that column is right of it (IDEA's indent guide shift). */
const GUIDE_SHIFT = 2;
/** One column of indentation: a space in the editor font, as measured by the guides plugin. */
const SPACE = "var(--openidea-space, 1ch)";
const SPACE_SAMPLE = 64;
/** Number of `--openidea-guide-<n>` rainbow colours; deeper guides repeat them. */
export const GUIDE_COLORS = 5;
@@ -50,7 +57,7 @@ export function guideVars(
? `var(--openidea-guide-${((level - 1) % GUIDE_COLORS) + 1})`
: "var(--openidea-guide)",
);
positions.push(`calc(${LINE_INSET - GUIDE_SHIFT}px + ${level * step}ch) 0`);
positions.push(`calc(${LINE_INSET - GUIDE_SHIFT}px + ${level * step} * ${SPACE}) 0`);
}
return { images: images.join(", "), positions: positions.join(", ") };
}
@@ -187,10 +194,33 @@ export const indentGuides: Extension = [
ViewPlugin.fromClass(
class {
decorations: DecorationSet;
constructor(view: EditorView) {
private probe: HTMLElement;
constructor(readonly view: EditorView) {
// Inherits the editor font from the scroller, outside the content CodeMirror observes;
// the measured width goes on the scroller, where lines and code lens rows pick it up.
this.probe = document.createElement("span");
this.probe.setAttribute("aria-hidden", "true");
this.probe.style.cssText = "position: absolute; top: 0; left: 0; visibility: hidden; white-space: pre";
this.probe.textContent = " ".repeat(SPACE_SAMPLE);
view.scrollDOM.appendChild(this.probe);
this.decorations = build(view);
this.measure();
}
measure() {
this.view.requestMeasure({
key: this,
read: (view) => this.probe.getBoundingClientRect().width / (view.scaleX || 1) / SPACE_SAMPLE,
write: (width, view) => {
if (width > 0) view.scrollDOM.style.setProperty("--openidea-space", `${+width.toFixed(3)}px`);
},
});
}
destroy() {
this.probe.remove();
this.view.scrollDOM.style.removeProperty("--openidea-space");
}
update(u: ViewUpdate) {
if (u.geometryChanged) this.measure();
if (
u.docChanged ||
u.selectionSet ||
+5
Переглянути файл
@@ -92,6 +92,11 @@ const OWN_MODES = [
extensions: ["rst"],
load: () => import("./restructuredtext").then((m) => new LanguageSupport(m.restructuredtextLanguage)),
}),
LanguageDescription.of({
name: "Gherkin",
extensions: ["feature"],
load: () => import("./gherkin").then((m) => m.gherkinSupport()),
}),
LanguageDescription.of({
name: "Log",
extensions: ["log"],
+34 -1
Переглянути файл
@@ -1,5 +1,6 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { EditorState } from "@codemirror/state";
import { EditorState, StateEffect } from "@codemirror/state";
import { showTooltip, type Tooltip } from "@codemirror/view";
import { indentUnit, language as languageFacet } from "@codemirror/language";
import { HEAVY_LIMIT, onEditorEvent, registerSaveParticipant, remoteChange, shownAgain } from "@/editor/api";
import { createMemoryBackend, type MemoryBackend } from "../backend";
@@ -16,6 +17,15 @@ const host: SlotHost = {
onContextMenu: () => {},
};
const testTooltip: Tooltip = {
pos: 0,
create: () => {
const dom = document.createElement("div");
dom.className = "test-tab-tooltip";
return { dom };
},
};
async function settle() {
for (let i = 0; i < 10; i++) await new Promise((r) => setTimeout(r, 0));
}
@@ -362,6 +372,29 @@ describe("DocumentManager + slots", () => {
manager.stop();
});
it("takes a hidden tab's tooltips off the page with its view, and back when it shows again (#3647)", async () => {
const { manager } = setup({ "/p/a.txt": "abc" });
const model = await manager.acquire("/p/a.txt");
const slot = new EditorSlot(model, "t1", host);
const other = new EditorSlot(model, "t2", host);
const tooltip = () => document.querySelector(".cm-tooltip.test-tab-tooltip");
const view = slot.mount(document.body);
// Any tooltip of the tab (a hint, hover, completion…): they live in `document.body`, outside the view.
view.dispatch({ effects: StateEffect.appendConfig.of(showTooltip.of(testTooltip)) });
expect(tooltip()).not.toBeNull();
slot.unmount();
other.mount(document.body);
expect(tooltip()).toBeNull();
other.unmount();
expect(slot.mount(document.body)).toBe(view);
expect(tooltip()).not.toBeNull();
// Disposing the tab leaves nothing of it in the page.
slot.dispose();
other.dispose();
expect(tooltip()).toBeNull();
manager.stop();
});
it("destroys the least recently hidden views beyond the kept ones, and kept views on dispose", async () => {
const { manager } = setup({ "/p/a.txt": "abc" });
const model = await manager.acquire("/p/a.txt");
+11 -1
Переглянути файл
@@ -20,7 +20,7 @@ import {
type TransactionSpec,
} from "@codemirror/state";
import { historyField } from "@codemirror/commands";
import { EditorView, ViewPlugin, keymap, type ViewUpdate } from "@codemirror/view";
import { EditorView, ViewPlugin, keymap, tooltips, type ViewUpdate } from "@codemirror/view";
import {
_addEditor,
_removeEditor,
@@ -69,6 +69,11 @@ export class EditorSlot {
view: EditorView | null = null;
/** The view kept, detached from the document, while the tab is hidden. */
private kept: EditorView | null = null;
/**
* The tab's tooltips (hints, hover, completion…). They live outside the view, in `document.body`,
* so they leave the page with the view when the tab is hidden instead of floating over the next tab.
*/
private readonly tooltipLayer = typeof document === "undefined" ? null : document.createElement("div");
/** The view's scroll offset, tracked so hiding it needn't read layout. */
private scrollPos = { top: 0, left: 0 };
handle: TextEditorHandle | null = null;
@@ -166,6 +171,8 @@ export class EditorSlot {
}
}),
Prec.highest(keymap.of([{ key: "Escape", run: () => this.host.onEscape?.(this) ?? false }])),
// Ahead of the shared `document.body` parent (the tooltip space still comes from it).
this.tooltipLayer ? Prec.highest(tooltips({ parent: this.tooltipLayer })) : [],
EditorView.domEventObservers({
scroll: (_e, view) => {
if (view === this.view) this.scrollPos = { top: view.scrollDOM.scrollTop, left: view.scrollDOM.scrollLeft };
@@ -200,6 +207,7 @@ export class EditorSlot {
mount(parent: HTMLElement): EditorView {
if (this.view) return this.view;
if (this.tooltipLayer && !this.tooltipLayer.isConnected) document.body.appendChild(this.tooltipLayer);
const kept = this.kept;
let view: EditorView;
if (kept) {
@@ -243,6 +251,7 @@ export class EditorSlot {
this.kept = view;
if (!keep) return this.release();
view.dom.remove();
this.tooltipLayer?.remove();
keptSlots.push(this);
if (keptSlots.length > KEPT_VIEWS) keptSlots.shift()!.release();
}
@@ -258,6 +267,7 @@ export class EditorSlot {
this.scroll = scrollSnapshotAt(view, this.scrollPos);
this.stored = view.state;
view.destroy();
this.tooltipLayer?.remove();
}
dispose() {
+4 -4
Переглянути файл
@@ -74,9 +74,8 @@ export function showHint(
clearTimeout(timers.get(view));
timers.set(
view,
setTimeout(() => {
if (view.dom.isConnected && view.state.field(hintField, false)) view.dispatch({ effects: setHint.of(null) });
}, opts.timeout ?? 4000),
// Also while the view is hidden: it would show the hint again when its tab is shown.
setTimeout(() => hideHint(view), opts.timeout ?? 4000),
);
}
@@ -104,9 +103,10 @@ export function showPendingHint(view: EditorView, content: string): () => void {
}, PENDING_HINT_DELAY_MS);
return () => {
clearTimeout(timer);
// Also when the request ended by opening another tab, which hid this view.
if (shown && view.state.field(hintField, false) === shown) {
clearTimeout(timers.get(view));
if (view.dom.isConnected) hideHint(view);
hideHint(view);
}
};
}
+5 -3
Переглянути файл
@@ -89,11 +89,13 @@ export function cellLspExtensions(ctx: EditorDocContext): Extension[] {
}
/**
* A diff pane showing a file's open document: hover / quick docs and ⌘/Ctrl-click navigation,
* so references can be followed while reviewing. Editing features stay with text editors.
* A diff pane showing a file's open document: hover / quick docs, ⌘/Ctrl-click
* navigation and semantic highlighting, so colours match the editor while
* reviewing. Editing features stay with text editors; panes without a document
* (revisions) get nothing from the semantic extension (`docOf` is null).
*/
export function diffLspExtensions(ctx: EditorDocContext): Extension[] {
return [lspDoc.of(ctx), lspTheme, hintExtension(), hoverExtension(), navigationExtension()];
return [lspDoc.of(ctx), lspTheme, hintExtension(), hoverExtension(), navigationExtension(), semanticExtension()];
}
export function activate(): () => void {
+16 -5
Переглянути файл
@@ -159,7 +159,8 @@ function shownKind(kind: InlayHint["kind"]): boolean {
const inlayPlugin = ViewPlugin.fromClass(
class {
private refresh = debounce(() => void this.run(), 400);
private generation = 0;
private schedule = debounce(() => void this.run(), 400);
private unsubscribe: () => void;
private offReady: () => void;
private offSettled: () => void;
@@ -185,6 +186,10 @@ const inlayPlugin = ViewPlugin.fromClass(
update(u: ViewUpdate) {
if (u.docChanged || u.viewportChanged || (this.skipped && shownAgain(u))) this.refresh();
}
private refresh() {
this.generation++;
this.schedule();
}
async run() {
const view = this.view;
this.skipped = !view.dom.isConnected;
@@ -204,12 +209,17 @@ const inlayPlugin = ViewPlugin.fromClass(
return;
}
const state = view.state;
const generation = this.generation;
const wanted = () => generation === this.generation && view.state.doc === state.doc;
const { from, to } = view.viewport;
const first = state.doc.lineAt(from).from;
const last = state.doc.lineAt(to).to;
try {
const hints = await lspRequest(() => commands.lspInlayHints(doc.doc, offsetsToRange(state.doc, first, last)));
if (view.state.doc !== state.doc) return this.refresh();
const hints = await lspRequest(
() => commands.lspInlayHints(doc.doc, offsetsToRange(state.doc, first, last)),
wanted,
);
if (!wanted()) return;
const fresh = hints.filter((h) => shownKind(h.kind));
// A busy server (indexing, loading a build) can answer with nothing: keep the
// hints shown until it settles, instead of blinking them away and reflowing
@@ -220,11 +230,12 @@ const inlayPlugin = ViewPlugin.fromClass(
effects: setInlays.of(inlayDecorations(view, fresh)),
});
} catch (e) {
if (isUnavailable(e)) inlayBackoff.mark(doc.doc);
if (wanted() && isUnavailable(e)) inlayBackoff.mark(doc.doc);
}
}
destroy() {
this.refresh.cancel();
this.generation++;
this.schedule.cancel();
this.unsubscribe();
this.offReady();
this.offSettled();
+184
Переглянути файл
@@ -0,0 +1,184 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { _addEditor, _removeEditor, documentSynced, viewShown } from "@/editor/api";
import type { InlayHint } from "@/bindings";
const ipc = vi.hoisted(() => ({ lspInlayHints: vi.fn() }));
vi.mock("@/platform/ipc", async (orig) => {
const real = await orig<typeof import("@/platform/ipc")>();
return { ...real, isTauri: () => true, commands: { ...real.commands, ...ipc } };
});
const { inlayExtension } = await import("./inlay");
const { lspDoc } = await import("./lsp");
const { useProject } = await import("@/platform/project");
const { emitLocalIdeEvent } = await import("@/platform/ipc");
const views: EditorView[] = [];
const ok = (label: string) => ({
status: "ok" as const,
data: [
{
position: { line: 0, col: 5 },
label,
kind: "type",
parts: [],
paddingLeft: false,
paddingRight: false,
tooltip: null,
},
] as InlayHint[],
});
function deferred<T>() {
let resolve!: (value: T) => void;
const promise = new Promise<T>((r) => (resolve = r));
return { promise, resolve };
}
const ctx = { doc: 71, path: "/p/a.rs", language: "rust", uiMode: "Rust", readOnly: false };
function editor(sync?: () => Promise<void>) {
const view = new EditorView({
state: EditorState.create({
doc: "let x = 1;",
extensions: [lspDoc.of(ctx), ...(sync ? [documentSynced.of(sync)] : []), inlayExtension()],
}),
parent: document.body,
});
views.push(view);
return view;
}
const labels = (view: EditorView) => [...view.dom.querySelectorAll(".cm-lsp-inlay")].map((e) => e.textContent);
beforeEach(() => {
vi.useFakeTimers();
ipc.lspInlayHints.mockReset().mockResolvedValue(ok("current"));
useProject.setState({ settings: { editor: { inlayHints: true } } as never });
});
afterEach(() => {
views.splice(0).forEach((v) => v.destroy());
useProject.setState({ settings: null });
vi.useRealTimers();
});
describe("inlay request lifetime", () => {
it("does not restore hints after they were disabled", async () => {
const old = deferred<ReturnType<typeof ok>>();
ipc.lspInlayHints.mockReturnValueOnce(old.promise);
const view = editor();
await vi.advanceTimersByTimeAsync(400);
useProject.setState({ settings: { editor: { inlayHints: false } } as never });
await vi.advanceTimersByTimeAsync(400);
old.resolve(ok("stale"));
await vi.advanceTimersByTimeAsync(1);
expect(labels(view)).toEqual([]);
});
it("does not overwrite a newer server refresh with an older response", async () => {
const old = deferred<ReturnType<typeof ok>>();
ipc.lspInlayHints.mockReturnValueOnce(old.promise);
const view = editor();
await vi.advanceTimersByTimeAsync(400);
emitLocalIdeEvent({ type: "lspRefresh", kind: "inlayHints", server: 1 });
await vi.advanceTimersByTimeAsync(400);
expect(labels(view)).toEqual(["current"]);
old.resolve(ok("stale"));
await vi.advanceTimersByTimeAsync(1);
expect(labels(view)).toEqual(["current"]);
});
});
describe("obsolete inlay work", () => {
it("invalidates immediately, before the next debounced request starts", async () => {
const old = deferred<ReturnType<typeof ok>>();
ipc.lspInlayHints.mockReturnValueOnce(old.promise);
const view = editor();
await vi.advanceTimersByTimeAsync(400);
emitLocalIdeEvent({ type: "lspRefresh", kind: "inlayHints", server: 1 });
old.resolve(ok("stale"));
await vi.advanceTimersByTimeAsync(1);
expect(labels(view)).toEqual([]);
await vi.advanceTimersByTimeAsync(399);
expect(labels(view)).toEqual(["current"]);
});
it("does not dispatch a response into a destroyed editor", async () => {
const old = deferred<ReturnType<typeof ok>>();
ipc.lspInlayHints.mockReturnValueOnce(old.promise);
const view = editor();
await vi.advanceTimersByTimeAsync(400);
view.destroy();
views.splice(views.indexOf(view), 1);
const dispatch = vi.spyOn(view, "dispatch");
old.resolve(ok("stale"));
await vi.advanceTimersByTimeAsync(400);
expect(dispatch).not.toHaveBeenCalled();
});
it("does not send obsolete requests after waiting for document synchronization", async () => {
const synced = deferred<void>();
const view = editor(() => synced.promise);
const handle = { view, ctx };
_addEditor(handle);
try {
await vi.advanceTimersByTimeAsync(400);
expect(ipc.lspInlayHints).not.toHaveBeenCalled();
view.destroy();
views.splice(views.indexOf(view), 1);
synced.resolve();
await vi.advanceTimersByTimeAsync(400);
expect(ipc.lspInlayHints).not.toHaveBeenCalled();
} finally {
_removeEditor(handle);
}
});
});
describe("retained editors", () => {
it("keeps an in-flight response when the editor is detached then shown again", async () => {
const pending = deferred<ReturnType<typeof ok>>();
ipc.lspInlayHints.mockReturnValueOnce(pending.promise);
const view = editor();
await vi.advanceTimersByTimeAsync(400);
view.dom.remove();
pending.resolve(ok("retained"));
await vi.advanceTimersByTimeAsync(1);
document.body.append(view.dom);
view.dispatch({ effects: viewShown.of(null) });
await vi.advanceTimersByTimeAsync(400);
expect(labels(view)).toEqual(["retained"]);
});
it("keeps work waiting for document synchronization when detached then shown again", async () => {
const synced = deferred<void>();
const view = editor(() => synced.promise);
const handle = { view, ctx };
_addEditor(handle);
try {
await vi.advanceTimersByTimeAsync(400);
expect(ipc.lspInlayHints).not.toHaveBeenCalled();
view.dom.remove();
synced.resolve();
await vi.advanceTimersByTimeAsync(1);
document.body.append(view.dom);
view.dispatch({ effects: viewShown.of(null) });
await vi.advanceTimersByTimeAsync(400);
expect(labels(view)).toEqual(["current"]);
} finally {
_removeEditor(handle);
}
});
});
describe("settled refresh request lifetime", () => {
it.each([true, false])("rejects old busy answers after a settled refresh (empty=%s)", async (empty) => {
const view = editor();
await vi.advanceTimersByTimeAsync(400);
expect(labels(view)).toEqual(["current"]);
const old = deferred<ReturnType<typeof ok>>();
ipc.lspInlayHints.mockReturnValueOnce(old.promise);
emitLocalIdeEvent({ type: "languageServer", server: 91, name: "rust-analyzer", status: "busy", message: null });
emitLocalIdeEvent({ type: "lspRefresh", kind: "inlayHints", server: 91 });
await vi.advanceTimersByTimeAsync(1600);
const settled = empty ? { status: "ok" as const, data: [] } : ok("settled");
ipc.lspInlayHints.mockResolvedValue(settled);
emitLocalIdeEvent({ type: "languageServer", server: 91, name: "rust-analyzer", status: "ready", message: null });
// Settling invalidates immediately, not only after the debounce delay.
old.resolve(ok("stale busy"));
await vi.advanceTimersByTimeAsync(1);
expect(labels(view)).toEqual(["current"]);
await vi.advanceTimersByTimeAsync(399);
expect(labels(view)).toEqual(empty ? [] : ["settled"]);
});
});
+21
Переглянути файл
@@ -70,6 +70,27 @@ describe("slow navigation feedback", () => {
expect(document.querySelector(".cm-lsp-hint")).toBeNull();
});
it("clears the progress hint when the target opens in another tab and hides this view (#3647)", async () => {
let resolve!: (result: Awaited<ReturnType<typeof commands.lspGotoImplementation>>) => void;
lspGotoImplementation.mockImplementationOnce(() => new Promise((r) => (resolve = r)));
// Opening the target's tab detaches this tab's view, as `EditorSlot.unmount` does.
openFile.mockImplementationOnce(async () => view.dom.remove());
const pending = gotoTargets(view, "implementation");
await vi.advanceTimersByTimeAsync(250);
expect(document.querySelector(".cm-lsp-hint")?.textContent).toBe("Finding navigation target…");
resolve({
status: "ok",
data: [{ path: "/p/Impl.java", range: { start: { line: 1, col: 0 }, end: { line: 1, col: 4 } }, uri: null }],
});
await pending;
expect(openFile).toHaveBeenCalled();
expect(view.dom.isConnected).toBe(false);
expect(document.querySelector(".cm-lsp-hint")).toBeNull();
// Shown again, the tab has no stale progress hint.
document.body.appendChild(view.dom);
expect(document.querySelector(".cm-lsp-hint")).toBeNull();
});
it("shows progress while the chooser's rows load after a quick answer, until the chooser opens", async () => {
let finish!: (files: Map<string, string[]>) => void;
vi.spyOn(files, "readManyFileLines").mockImplementationOnce(() => new Promise((r) => (finish = r)));
+41 -2
Переглянути файл
@@ -66,7 +66,7 @@ import {
} from "./composerModel";
import { referenceExtensions, setReferences } from "./composerEditor";
import { referenceHover } from "./ReferenceChip";
import { composerDraft, updateComposer, useAgents } from "./store";
import { composerDraft, provideIdeContext, setIdeContext, updateComposer, useAgents } from "./store";
import { ImagePreview, imageSrc } from "./ImagePreview";
import { useAgentSettings } from "./agentSettings";
import styles from "./Composer.module.css";
@@ -933,6 +933,27 @@ export function Composer(props: ComposerProps) {
return { path: activePath, rel };
}, [activePath, projectRoot, root, text]);
const ideContext = useAgents((s) => s.ideContext);
useEffect(
() =>
provideIdeContext(id, () => {
const active = useEditorRegistry.getState().active;
const path = active?.ctx.path;
if (!active || !path || isVirtualUri(path)) return null;
const rel = relativeTo([projectRoot, root], path);
if (!rel || rel === ".") return null;
const { doc, selection } = active.view.state;
const { from, to } = selection.main;
if (from === to) return { path, rel };
const first = doc.lineAt(from).number;
const end = doc.lineAt(to);
// A selection ending at the start of a line does not take that line.
const last = end.from === to && end.number > first ? end.number - 1 : end.number;
return { path, rel, lines: { from: first, to: last } };
}),
[id, projectRoot, root],
);
const showContext = images.length > 0 || attached.length > 0 || !!suggested;
return (
@@ -1056,7 +1077,14 @@ export function Composer(props: ComposerProps) {
)}
{showContext && (
<div className={styles.context} onMouseDown={(e) => e.stopPropagation()}>
{suggested && (
{suggested && ideContext && (
<span className={styles.attachment} title={tx`${suggested.rel} is added to your request`}>
<Icon name={fileIconName(basename(suggested.rel), suggested.rel)} size={14} />
<span className={styles.attachmentName}>{basename(suggested.rel)}</span>
<span className={styles.suggestionHint}>{tx("Current File")}</span>
</span>
)}
{suggested && !ideContext && (
<button
type="button"
className={styles.suggestion}
@@ -1127,6 +1155,17 @@ export function Composer(props: ComposerProps) {
replace(from, to, before && !/\s/.test(before) ? " @" : "@");
}}
/>
<IconButton
icon="file-code"
title={
ideContext
? "IDE Context Enabled: the current file and selection are added to your request"
: "IDE Context Disabled: the current file and selection are not added to your request"
}
pressed={ideContext}
className={styles.composerButton}
onClick={() => setIdeContext(!ideContext)}
/>
<IconButton
icon="image"
title="Attach Image…"
+31 -8
Переглянути файл
@@ -404,6 +404,13 @@
.agentName {
display: none;
}
.processBody,
.turnBody {
padding-left: var(--space-2);
}
.processBody > .thoughtEntry ~ .toolEntry {
padding-left: var(--space-3);
}
}
.messageActions {
display: inline-flex;
@@ -771,6 +778,10 @@
margin-bottom: 0;
}
.thoughtEntry,
.toolEntry {
min-width: 0;
}
.thought summary,
.toolDetails > summary {
cursor: pointer;
@@ -783,15 +794,18 @@
.thought summary {
display: flex;
align-items: center;
gap: var(--space-1);
gap: var(--space-1-5);
min-width: 0;
min-height: var(--h-row);
padding: 0 calc(var(--space-2) / 2);
border-radius: var(--radius-row);
color: var(--fg-muted);
font-size: var(--agent-fs-small, var(--fs-small));
-webkit-user-select: none;
user-select: none;
}
.thought summary:hover {
background: var(--bg-hover);
color: var(--fg);
}
.thoughtChevron {
@@ -807,7 +821,9 @@
transform: rotate(90deg);
}
.thoughtBody {
margin-top: var(--space-2);
margin: var(--space-1-5) 0 var(--space-1) 10px;
padding-left: var(--space-3);
border-left: 1px solid var(--border);
color: var(--fg-secondary);
}
.thoughtText {
@@ -821,7 +837,7 @@
.tool {
display: flex;
align-items: center;
gap: var(--space-2);
gap: var(--space-1-5);
min-width: 0;
box-sizing: border-box;
min-height: var(--h-row);
@@ -848,6 +864,10 @@
.toolChevron {
flex: none;
}
.toolChevronSpacer {
width: 12px;
flex: none;
}
.toolDetails[open] > summary .toolChevron {
transform: rotate(90deg);
}
@@ -927,12 +947,15 @@
gap: var(--space-0-5);
max-height: calc(var(--h-row) * 16);
overflow-y: auto;
margin-top: 2px;
padding-left: 10px;
margin: 2px 0 0 10px;
padding-left: var(--space-3);
border-left: 1px solid var(--border);
}
.processBody > .thoughtEntry ~ .toolEntry {
padding-left: var(--space-4);
}
.output {
margin: 4px 0 0;
margin: 4px 0 4px 22px;
max-height: 240px;
overflow: auto;
padding: 8px 10px;
@@ -1828,8 +1851,8 @@
display: flex;
flex-direction: column;
gap: var(--space-2);
margin-top: 2px;
padding-left: 10px;
margin: 2px 0 0 10px;
padding-left: var(--space-3);
border-left: 1px solid var(--border);
}
+7 -4
Переглянути файл
@@ -1426,7 +1426,7 @@ function ThoughtEntry({
if (working && open) onDiagramDrawn();
}, [shown, working, open, onDiagramDrawn]);
return (
<div className={styles.process}>
<div className={clsx(styles.process, styles.thoughtEntry)}>
<Fold
className={clsx(styles.thought, thinking === "auto" && working && styles.thoughtLive)}
open={open}
@@ -2072,12 +2072,15 @@ const ToolEntry = memo(function ToolEntry({
);
if (!entry.output)
return (
<div className={styles.process}>
<div className={styles.tool}>{head}</div>
<div className={clsx(styles.process, styles.toolEntry)}>
<div className={styles.tool}>
<span className={styles.toolChevronSpacer} aria-hidden="true" />
{head}
</div>
</div>
);
return (
<div className={styles.process}>
<div className={clsx(styles.process, styles.toolEntry)}>
<Fold
className={styles.toolDetails}
open={liveTool(entry) || expandToolOutput}
-11
Переглянути файл
@@ -35,7 +35,6 @@ import {
import {
age,
appendEntry,
attentionChange,
branchLabel,
entriesKey,
findSubagent,
@@ -447,16 +446,6 @@ describe("agents model", () => {
expect(appendEntry([u, a], 2, 0, "x")).toBeNull();
});
it("notifies on finish, failure and questions only", () => {
expect(attentionChange("running", "ready")).toBe("finished");
expect(attentionChange("running", "failed")).toBe("failed");
expect(attentionChange("running", "limited")).toBe("failed");
expect(attentionChange("running", "needsInput")).toBe("input");
expect(attentionChange("needsInput", "running")).toBeNull();
expect(attentionChange("ready", "archived")).toBeNull();
expect(attentionChange(undefined, "ready")).toBeNull();
});
it("finds subagent cards and keys their conversations apart", () => {
const card: SubagentEntry = {
type: "subagent",
+45 -1
Переглянути файл
@@ -14,6 +14,7 @@ const pathCompletions = vi.fn();
const fsProbe = vi.fn();
const fsEntryKind = vi.fn();
const findSymbols = vi.fn();
const agentPrompt = vi.fn((..._args: unknown[]) => Promise.resolve({ status: "ok", data: null }));
vi.mock("@/platform/ipc", async (importOriginal) => {
const real = await importOriginal<typeof import("@/platform/ipc")>();
@@ -28,6 +29,7 @@ vi.mock("@/platform/ipc", async (importOriginal) => {
fsProbe: (path: string) => fsProbe(path),
fsEntryKind: (path: string) => fsEntryKind(path),
findSymbols: (query: string, filter: string, limit: number) => findSymbols(query, filter, limit),
agentPrompt: (...args: unknown[]) => agentPrompt(...args),
},
};
});
@@ -35,7 +37,7 @@ vi.mock("@/platform/ipc", async (importOriginal) => {
import { Composer } from "./Composer";
import { registerAgentContextSource } from "@/workbench/contributions";
import { useEditorRegistry, type TextEditorHandle } from "@/editor/api";
import { composerDraft, updateComposer } from "./store";
import { composerDraft, sendMessage, setIdeContext, updateComposer, useAgents } from "./store";
import { emptyDraft, toPrompt } from "./composerModel";
const ID = "folders-test";
@@ -318,6 +320,7 @@ describe("Composer editing", () => {
describe("Composer current file", () => {
it("offers the focused editor's file until the draft references it", () => {
const view = {} as TextEditorHandle["view"];
act(() => setIdeContext(false));
act(() =>
useEditorRegistry.setState({ active: { view, ctx: { path: "/p/src/main.ts" } as TextEditorHandle["ctx"] } }),
);
@@ -336,6 +339,47 @@ describe("Composer current file", () => {
});
});
describe("Composer IDE context", () => {
it("sends the focused editor's file, or its selected lines, while IDE context is on", async () => {
const view = new EditorView({ doc: "a\nb\nc\nd\n" });
act(() => setIdeContext(true));
act(() =>
useEditorRegistry.setState({ active: { view, ctx: { path: "/p/src/main.ts" } as TextEditorHandle["ctx"] } }),
);
try {
renderComposer();
const toggle = screen.getByRole("button", { name: /IDE Context Enabled/ });
expect(toggle).toHaveAttribute("aria-pressed", "true");
expect(screen.queryByRole("button", { name: /main\.ts/ })).toBeNull();
expect(screen.getByTitle("src/main.ts is added to your request")).toHaveTextContent("Current File");
const send = async (text: string) => {
updateComposer(ID, { text });
await sendMessage(ID, false);
return agentPrompt.mock.lastCall?.[1];
};
expect(await send("explain")).toEqual({ text: "explain", files: ["/p/src/main.ts"], images: [] });
// Lines 2–3: the selection ends at the start of line 4.
view.dispatch({ selection: { anchor: 2, head: 6 } });
expect(await send("explain")).toEqual({
text: "explain\n\n@src/main.ts:2-3",
files: ["/p/src/main.ts"],
images: [],
});
// A draft that already references the file is sent as written.
expect(await send("see @src/main.ts:1")).toEqual({ text: "see @src/main.ts:1", files: [], images: [] });
fireEvent.click(toggle);
expect(useAgents.getState().ideContext).toBe(false);
expect(screen.getByRole("button", { name: /IDE Context Disabled/ })).toHaveAttribute("aria-pressed", "false");
expect(await send("explain")).toEqual({ text: "explain", files: [], images: [] });
} finally {
act(() => useEditorRegistry.setState({ active: null }));
view.destroy();
}
});
});
describe("Composer pasted code and terminal output", () => {
const paste = (box: HTMLElement, text: string) =>
act(() => {
+30
Переглянути файл
@@ -317,6 +317,36 @@ export function mentionOf(rel: string, lines?: { from: number; to: number }): st
export const isMentioned = (text: string, rel: string) =>
new RegExp(`@${escapeRe(rel)}(?![\\w./-])|@${escapeRe(rel)}:`).test(text);
/** The file in the focused editor and the lines selected in it, for IDE context. */
export interface IdeContext {
path: string;
rel: string;
/** 1-based lines of a non-empty selection. */
lines?: { from: number; to: number };
}
/**
* `draft` with the editor's current file added (as an attachment), or its selection as a
* line-range mention after the text; unchanged when the draft already references the file.
*/
export function withIdeContext(draft: ComposerDraft, context: IdeContext | null): ComposerDraft {
if (
!context ||
isMentioned(draft.text, context.rel) ||
draft.files.some((f) => f.path === context.path && f.attached)
)
return draft;
if (!context.lines)
return { ...draft, files: [...draft.files, { path: context.path, rel: context.rel, attached: true }] };
const mention = mentionOf(context.rel, context.lines);
const text = draft.text.trim();
return {
...draft,
text: text ? `${text}\n\n${mention}` : mention,
files: [...draft.files, { path: context.path, rel: context.rel }],
};
}
/** The prompt to send: attached files, files still mentioned in the text (each once), and the images. */
export function toPrompt(draft: ComposerDraft): AgentPrompt {
const seen = new Set<string>();
-13
Переглянути файл
@@ -242,16 +242,3 @@ export function age(ms: number, now = Date.now()): string {
if (h < 24) return `${h}h`;
return `${Math.round(h / 24)}d`;
}
/** The status change worth a notification, if any. */
export function attentionChange(
prev: AgentStatus | undefined,
next: AgentStatus,
): "finished" | "failed" | "input" | null {
if (prev === next || prev === undefined) return null;
if (next === "needsInput") return "input";
if (!isBusy(prev)) return null;
if (next === "ready") return "finished";
if (next === "failed" || next === "limited") return "failed";
return null;
}
+50 -18
Переглянути файл
@@ -14,6 +14,7 @@ import type {
AgentImage,
AgentLimit,
AgentModelCatalog,
AgentPrompt,
AgentProvider,
AgentTask,
ExternalSession,
@@ -35,8 +36,10 @@ import {
isMentioned,
isPerModelOption,
toPrompt,
withIdeContext,
type ComposerDraft,
type FileRef,
type IdeContext,
} from "./composerModel";
import { withQuote } from "./conversation";
import {
@@ -53,7 +56,6 @@ import {
SESSION_KIND,
TOOL_WINDOW,
appendEntry,
attentionChange,
entriesKey,
isBusy,
sessionKey,
@@ -128,6 +130,8 @@ interface AgentsState {
/** Side conversations by task id: kept out of the task list, discarded when their view closes. */
ephemeral: ReadonlySet<string>;
pinnedModels: string[];
/** Whether messages carry the editor's current file and selection. */
ideContext: boolean;
}
const DRAFT_KEY = "openidea.agents.draft.v2";
@@ -135,6 +139,7 @@ const HISTORY_KEY = "openidea.agents.history.v1";
const HISTORY_SIZE = 50;
const SESSION_LOCATION_KEY = "openidea.agents.sessionLocation.v1";
const PINNED_MODELS_KEY = "openidea.agents.pinnedModels.v1";
const IDE_CONTEXT_KEY = "openidea.agents.ideContext.v1";
function load<T>(key: string, fallback: T): T {
try {
@@ -199,6 +204,7 @@ export const useAgents = create<AgentsState>(() => ({
homeOpen: false,
ephemeral: new Set<string>(),
pinnedModels: load<string[]>(PINNED_MODELS_KEY, []),
ideContext: load<boolean>(IDE_CONTEXT_KEY, true),
scrollPositions: new Map(),
}));
@@ -553,14 +559,17 @@ function onEvent(e: AgentEvent) {
useAgents.setState({ tasks: new Map(s.tasks).set(e.task.id, e.task) });
if (prev && (prev.title !== e.task.title || prev.status !== e.task.status)) notifyTabTitlesChanged();
if (e.task.status === "archived") setUnread(e.task.id, false);
else if (attentionChange(prev?.status, e.task.status)) markUnread(e.task.id);
notifyChange(prev, e.task);
if (prev?.status !== e.task.status && !isBusy(e.task.status)) {
void refreshChanges(e.task.id);
void refreshProviders();
}
break;
}
case "attention": {
markUnread(e.task);
notifyAttention(e.task, e.reason);
break;
}
case "removed": {
const tasks = new Map(s.tasks);
tasks.delete(e.id);
@@ -633,27 +642,28 @@ function onEvent(e: AgentEvent) {
}
}
function notifyChange(prev: AgentTask | undefined, task: AgentTask) {
const change = attentionChange(prev?.status, task.status);
if (!change) return;
if (viewing(task.id)) return;
/** In-app balloon for an Attention event; OS delivery goes through the general balloon path. */
function notifyAttention(taskId: string, reason: "finished" | "input" | "failed") {
if (viewing(taskId)) return;
const task = useAgents.getState().tasks.get(taskId);
const title = task?.title ?? "Agent";
const body =
change === "input"
reason === "input"
? "Waiting for your answer"
: change === "failed"
? (task.error ?? "The agent stopped")
: reason === "failed"
? (task?.error ?? "The agent stopped")
: "Finished";
notifications().notify({
level: change === "failed" ? "error" : "info",
title: task.title,
level: reason === "failed" ? "error" : "info",
title,
body,
key: `agent:${task.id}`,
key: `agent:${taskId}`,
group: "tools",
sticky: change !== "finished",
sticky: reason !== "finished",
actions: [
{
label: change === "finished" ? "Review" : "Open",
run: () => openTask(task.id),
label: reason === "finished" ? "Review" : "Open",
run: () => openTask(taskId),
},
],
});
@@ -969,7 +979,7 @@ export async function startTask(
const task = await call(
commands.agentCreate({
projectRoot,
prompt: toPrompt(composer),
prompt: promptOf(HOME, composer),
provider: draft.provider,
config,
isolation,
@@ -1083,6 +1093,28 @@ export async function importExternalSessions(
void showError(title, failures.join("\n"));
}
export function setIdeContext(on: boolean) {
useAgents.setState({ ideContext: on });
save(IDE_CONTEXT_KEY, on);
}
/** The IDE context of each mounted composer, by draft key. */
const ideContexts = new Map<string, () => IdeContext | null>();
/** Registers what composer `key` sends as IDE context; returns the unregister. */
export function provideIdeContext(key: string, context: () => IdeContext | null): () => void {
ideContexts.set(key, context);
return () => {
if (ideContexts.get(key) === context) ideContexts.delete(key);
};
}
/** The prompt of composer `key`, with the IDE context when it is on. */
function promptOf(key: string, composer: ComposerDraft): AgentPrompt {
const context = useAgents.getState().ideContext ? (ideContexts.get(key)?.() ?? null) : null;
return toPrompt(withIdeContext(composer, context));
}
function remember(text: string) {
if (!text) return;
const history = [text, ...useAgents.getState().history.filter((h) => h !== text)].slice(0, HISTORY_SIZE);
@@ -1095,7 +1127,7 @@ export async function sendMessage(task: string, now: boolean): Promise<void> {
const composer = composerDraft(task);
if (!canSend(composer)) return;
const started = generation;
await call(commands.agentPrompt(task, toPrompt(composer), now));
await call(commands.agentPrompt(task, promptOf(task, composer), now));
clearSubmittedComposer(task, composer, started);
}
+15 -2
Переглянути файл
@@ -163,16 +163,28 @@ describe("agent unread activity", () => {
expect([...useAgents.getState().unread]).toEqual(["one"]);
});
it.each(["ready", "needsInput", "failed", "limited"] as const)("marks background %s transitions unread", (status) => {
it.each([
["finished", "ready"],
["input", "needsInput"],
["failed", "failed"],
["failed", "limited"],
] as const)("marks background attention %s unread", (reason, status) => {
emit({ type: "task", task: task("one", status) });
emit({ type: "attention", task: "one", eventId: `one:${reason}:1`, reason });
expect(useAgents.getState().unread.has("one")).toBe(true);
expect(backend.notify).toHaveBeenCalledTimes(1);
show();
emit({ type: "task", task: task("one", status) });
emit({ type: "attention", task: "one", eventId: `one:${reason}:2`, reason });
expect(useAgents.getState().unread.size).toBe(0);
expect(backend.notify).toHaveBeenCalledTimes(1);
});
it("does not notify from status alone once Attention exists", () => {
emit({ type: "task", task: task("one", "ready") });
expect(backend.notify).not.toHaveBeenCalled();
expect(useAgents.getState().unread.has("one")).toBe(false);
});
it("keeps the latest usage limits per provider without marking anything unread", () => {
const fiveHour = (usedPercent: number) => [{ window: "five_hour", usedPercent, resetsMs: null }];
emit({ type: "limits", provider: "claude", limits: fiveHour(10) });
@@ -258,6 +270,7 @@ describe("agent unread activity", () => {
describe("agent unread indicators", () => {
it("shows a dot on the task and a clickable status count even when all tasks are idle", () => {
emit({ type: "task", task: task("one", "ready") });
emit({ type: "attention", task: "one", eventId: "one:finished:1", reason: "finished" });
render(
<>
<AgentsView />
+207 -18
Переглянути файл
@@ -11,7 +11,13 @@ const component = (name: string, options: Record<string, string>) =>
.map(([k, v]) => `<option name="${k}" value="${v}" />`)
.join("")}</component></application>`;
const editor = { fontSize: 13, customSchemes: {}, colorOverrides: {} };
const settings = {
editor: { fontFamily: "JetBrains Mono", fontSize: 13, customSchemes: {}, colorOverrides: {} },
customKeymaps: {},
};
/** JetBrains Maple Mono's metrics (ascent 1.02em, descent 0.3em), for any family. */
const fontHeight = (_family: string, size: number) => Math.ceil(size * 1.02) + Math.ceil(size * 0.3);
/** A WebStorm export, trimmed to what the import reads. */
const webstorm = {
@@ -51,8 +57,8 @@ const webstorm = {
};
describe("planJetBrainsImport", () => {
it("maps a WebStorm export to the settings it has, and lists what is left out", () => {
const plan = planJetBrainsImport(webstorm, editor);
it("maps a WebStorm export to the settings it has, and lists what is left out", async () => {
const plan = await planJetBrainsImport(webstorm, settings, fontHeight);
const writes = Object.fromEntries(plan.writes);
const schemes = writes["editor.customSchemes"] as Record<string, { name: string; parent: string }>;
const [id, scheme] = Object.entries(schemes)[0]!;
@@ -62,12 +68,15 @@ describe("planJetBrainsImport", () => {
"editor.colorScheme": id,
"editor.fontFamily": "JetBrains Maple Mono",
"editor.fontSize": 17,
// (18 + 6) × the default spacing 1.2, rounded up, as WebStorm draws it.
"editor.lineHeight": 29,
"editor.ligatures": true,
"files.trimTrailingWhitespace": true,
"editor.general.stripTrailingScope": "all",
"files.ensureFinalNewline": true,
"editor.stickyScroll": false,
"editor.softWrap": false,
"console.softWrap": true,
"general.confirmExit": false,
});
expect(plan.rows).toContainEqual({
@@ -79,12 +88,12 @@ describe("planJetBrainsImport", () => {
label: "Remove trailing spaces on:",
value: "All lines",
});
expect(plan.skipped).toEqual(["Keymap", "Code Style", "Inspections", "Plugins"]);
expect(plan.skipped).toEqual(["Code Style options other than Tabs and Indents", "Inspections", "Plugins"]);
expect(plan.invalid).toEqual([]);
});
it("writes only the keys present, and derives the line height from IDEA's spacing", () => {
const plan = planJetBrainsImport(
it("writes only the keys present, and derives the line height from IDEA's spacing", async () => {
const plan = await planJetBrainsImport(
{
entries: [],
files: {
@@ -97,33 +106,213 @@ describe("planJetBrainsImport", () => {
}),
},
},
editor,
settings,
fontHeight,
);
expect(plan.writes).toEqual([
["editor.lineHeight", 20],
// (14 + 4) × 1.5
["editor.lineHeight", 27],
["files.trimTrailingWhitespace", false],
["editor.softWrap", true],
["console.softWrap", true],
]);
expect(plan.skipped).toEqual([]);
});
it("re-importing replaces the earlier copy of a scheme and drops its edits", () => {
const first = Object.fromEntries(planJetBrainsImport(webstorm, editor).writes);
const customs = first["editor.customSchemes"] as typeof editor.customSchemes;
it("re-importing replaces the earlier copy of a scheme and drops its edits", async () => {
const first = Object.fromEntries((await planJetBrainsImport(webstorm, settings, fontHeight)).writes);
const customs = first["editor.customSchemes"] as typeof settings.editor.customSchemes;
const [id] = Object.keys(customs);
const again = planJetBrainsImport(webstorm, {
...editor,
customSchemes: customs,
colorOverrides: { [id!]: { keyword: { bold: true } }, other: {} },
});
const again = await planJetBrainsImport(
webstorm,
{
...settings,
editor: {
...settings.editor,
customSchemes: customs,
colorOverrides: { [id!]: { keyword: { bold: true } }, other: {} },
},
},
fontHeight,
);
const writes = Object.fromEntries(again.writes);
expect(Object.keys(writes["editor.customSchemes"] as object)).toEqual([id]);
expect(writes["editor.colorOverrides"]).toEqual({ other: {} });
expect(writes["editor.colorScheme"]).toBe(id);
});
it("skips colour schemes that cannot be read", () => {
const plan = planJetBrainsImport({ entries: [], files: { "colors/broken.icls": "<nope" } }, editor);
it("falls back to the font size when the font cannot be measured", async () => {
const plan = await planJetBrainsImport(
{ entries: [], files: { "options/editor-font.xml": component("DefaultFont", { FONT_SIZE: "20" }) } },
settings,
() => undefined,
);
expect(plan.writes).toEqual([
["editor.fontSize", 20],
["editor.lineHeight", 29],
]);
});
it("imports the keymaps and makes the active one current", async () => {
const keymap =
'<keymap version="1" name="macOS copy" parent="Mac OS X 10.5+">' +
'<action id="NextTab"><keyboard-shortcut first-keystroke="ctrl right" /></action>' +
'<action id="GotoSuperMethod" /><action id="RunAnything" /></keymap>';
const active =
'<application><component name="KeymapManager"><active_keymap name="macOS copy" /></component></application>';
const bundle = {
entries: ["keymaps/macOS copy.xml", "keymaps/broken.xml"],
files: {
"keymaps/macOS copy.xml": keymap,
"keymaps/broken.xml": "<nope",
// The active keymap is stored per operating system; the host picks its own.
"options/mac/keymap.xml": active,
"options/windows/keymap.xml": active,
"options/linux/keymap.xml": active,
},
};
const plan = await planJetBrainsImport(bundle, settings);
const expected = {
name: "macOS copy",
parent: "intellij-macos",
overrides: { "editor.nextTab": ["Ctrl+Right"], "navigate.superMethod": [] },
};
expect(plan.writes).toEqual([
["customKeymaps", { "custom.macos-copy": expected }],
["keymap", "custom.macos-copy"],
]);
expect(plan.rows).toEqual([
{ label: "Keymap", value: "macOS copy" },
{ label: "Current keymap", value: "macOS copy" },
]);
expect(plan.unknownActions).toEqual(["RunAnything"]);
expect(plan.invalid).toEqual(["broken.xml"]);
// Importing again replaces the earlier copy and keeps the user's other keymaps.
const mine = { name: "Mine", parent: "vscode-macos", overrides: {} };
const again = await planJetBrainsImport(bundle, {
...settings,
customKeymaps: { "custom.macos-copy": { ...expected, overrides: {} }, "custom.mine": mine },
});
expect(again.writes[0]).toEqual(["customKeymaps", { "custom.macos-copy": expected, "custom.mine": mine }]);
});
it("imports the terminal font", async () => {
const plan = await planJetBrainsImport(
{
entries: [],
files: {
"options/terminal-font.xml": component("TerminalFontOptions", {
VERSION: "1",
FONT_SIZE: "17",
FONT_SIZE_2D: "17.0",
FONT_FAMILY: "MesloLGS NF",
LINE_SPACING: "1.1",
}),
},
},
settings,
);
expect(plan.writes).toEqual([
["terminal.useEditorFont", false],
["terminal.fontFamily", "MesloLGS NF"],
["terminal.fontSize", 17],
["terminal.lineHeight", 1.1],
]);
});
it("imports tabs and indents of the current code style scheme onto the languages' own styles", async () => {
const scheme = (name: string, body: string) => `<code_scheme name="${name}" version="173">${body}</code_scheme>`;
const plan = await planJetBrainsImport(
{
entries: ["codestyles/Default.xml", "codestyles/Team.xml"],
files: {
"options/code.style.schemes.xml": component("CodeStyleSchemeSettings", { CURRENT_SCHEME_NAME: "Team" }),
"codestyles/Default.xml": scheme(
"Default",
'<codeStyleSettings language="Python"><indentOptions><option name="INDENT_SIZE" value="8" /></indentOptions></codeStyleSettings>',
),
"codestyles/Team.xml": scheme(
"Team",
'<option name="RIGHT_MARGIN" value="100" />' +
'<option name="OTHER_INDENT_OPTIONS"><value><option name="TAB_SIZE" value="8" />' +
'<option name="USE_TAB_CHARACTER" value="true" /></value></option>' +
'<JSCodeStyleSettings version="0"><option name="USE_SEMICOLON_AFTER_STATEMENT" value="false" /></JSCodeStyleSettings>' +
'<codeStyleSettings language="TypeScript"><option name="SPACE_WITHIN_BRACKETS" value="true" />' +
'<indentOptions><option name="INDENT_SIZE" value="2" /><option name="CONTINUATION_INDENT_SIZE" value="2" />' +
'<option name="TAB_SIZE" value="2" /></indentOptions></codeStyleSettings>' +
'<codeStyleSettings language="HTML"><option name="LINE_COMMENT_AT_FIRST_COLUMN" value="false" />' +
'<indentOptions><option name="USE_TAB_CHARACTER" value="true" /></indentOptions></codeStyleSettings>' +
'<codeStyleSettings language="Brainfuck"><indentOptions><option name="INDENT_SIZE" value="3" /></indentOptions></codeStyleSettings>',
),
},
},
{
...settings,
editor: {
...settings.editor,
codeStyle: { languages: { typescript: { hardWrapAt: 90 }, go: { tabSize: 8 } } },
},
},
);
expect(plan.writes).toEqual([
["editor.codeStyle.hardWrapAt", 100],
["editor.tabSize", 8],
["editor.insertSpaces", false],
[
"editor.codeStyle.languages",
{
typescript: { hardWrapAt: 90, indent: 2, tabSize: 2 },
typescriptreact: { indent: 2, tabSize: 2 },
html: { useTab: true, lineCommentAtFirstColumn: false },
go: { tabSize: 8 },
},
],
]);
expect(plan.rows).toContainEqual({ label: "Code Style › TypeScript", value: "Indent 2, Tab size 2" });
expect(plan.rows).toContainEqual({ label: "Use tab character", value: "On" });
expect(plan.skipped).toEqual(["Code Style options other than Tabs and Indents"]);
});
it("imports the editor options that have a setting here", async () => {
const xml =
"<application>" +
component("EditorSettings", {
IS_SMOOTH_CARET_BLINKING: "true",
IS_BLOCK_CURSOR: "true",
ARE_LINE_NUMBERS_SHOWN: "false",
LINE_NUMERATION: "HYBRID",
SHOW_BREADCRUMBS_ABOVE: "true",
CARET_BLINKING_PERIOD: "700",
IS_ANIMATED_SCROLLING: "false",
}).replace(/<\/?application>/g, "") +
component("CodeInsightSettings", {
AUTOINSERT_PAIR_QUOTE: "false",
REFORMAT_ON_PASTE: "2",
SMART_BACKSPACE: "1",
PARAMETER_INFO_DELAY: "500",
COMPLETION_CASE_SENSITIVE: "2",
}).replace(/<\/?application>/g, "") +
"</application>";
const plan = await planJetBrainsImport({ entries: [], files: { "options/editor.xml": xml } }, settings);
expect(Object.fromEntries(plan.writes)).toEqual({
"editor.appearance.lineNumberMode": "hybrid",
"editor.breadcrumbs.placement": "top",
"editor.appearance.smoothCaretBlinking": true,
"editor.appearance.blockCaret": true,
"editor.appearance.lineNumbers": false,
"editor.appearance.caretBlinkPeriod": 700,
"editor.smartKeys.pairQuotes": false,
"editor.completion.parameterInfoDelay": 500,
"editor.smartKeys.reformatOnPaste": "indentBlock",
"editor.smartKeys.backspaceUnindent": "nearest",
});
expect(plan.rows).toContainEqual({ label: "Unindent", value: "To nearest indent position" });
expect(plan.rows).toContainEqual({ label: "Show line numbers", value: "Hybrid" });
});
it("skips colour schemes that cannot be read", async () => {
const plan = await planJetBrainsImport({ entries: [], files: { "colors/broken.icls": "<nope" } }, settings);
expect(plan.invalid).toEqual(["broken.icls"]);
expect(plan.writes).toEqual([]);
});
+5 -2
Переглянути файл
@@ -4,7 +4,7 @@ import { act, fireEvent, render, screen } from "@testing-library/react";
const read = vi.fn();
const set = vi.fn();
const notify = vi.fn();
const editor = { fontSize: 13, customSchemes: {}, colorOverrides: {} };
const editor = { fontFamily: "JetBrains Mono", fontSize: 13, customSchemes: {}, colorOverrides: {} };
vi.mock("@/platform/ipc", async (original) => {
const actual = await original<typeof import("@/platform/ipc")>();
@@ -44,6 +44,8 @@ beforeEach(() => {
},
});
set.mockResolvedValue({ status: "ok", data: { editor } });
// jsdom has no canvas: the import falls back to the font size for the line height.
vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockReturnValue(null);
});
it.each(["Cancel", "Import"])("confirms folder settings before applying them: %s", async (button) => {
@@ -56,7 +58,7 @@ it.each(["Cancel", "Import"])("confirms folder settings before applying them: %s
expect(screen.getByText("Monaco")).toBeInTheDocument();
expect(screen.getByText("17")).toBeInTheDocument();
expect(screen.getAllByText("Custom")).toHaveLength(2);
expect(screen.getByText(/Not imported:/)).toHaveTextContent("Keymap, Plugins");
expect(screen.getByText(/Not imported:/)).toHaveTextContent("Plugins");
expect(set).not.toHaveBeenCalled();
await act(async () => {
fireEvent.click(screen.getByRole("button", { name: button }));
@@ -78,6 +80,7 @@ it.each(["Cancel", "Import"])("confirms folder settings before applying them: %s
"editor.colorScheme": id,
"editor.fontFamily": "Monaco",
"editor.fontSize": 17,
"editor.lineHeight": 25,
});
expect(notify).toHaveBeenCalledWith(expect.objectContaining({ title: "Settings imported" }));
}
+79
Переглянути файл
@@ -15,6 +15,7 @@ import {
installMenuBridge,
menuAccelerator,
menuActionIds,
returnFocusAfterMenu,
routeMenuEvent,
} from "../menuBridge";
@@ -54,6 +55,84 @@ describe("menu state from the frontend", () => {
}
});
it("pushes enablement once when the window loses focus, for its Settings window (#3625)", async () => {
vi.useFakeTimers();
vi.spyOn(ipc, "isTauri").mockReturnValue(true);
const hasFocus = vi.spyOn(document, "hasFocus").mockReturnValue(true);
vi.spyOn(ipc.commands, "appBuildInfo").mockRejectedValue(new Error("No build info in tests"));
vi.spyOn(ipc.commands, "menuConfigure").mockResolvedValue();
vi.spyOn(ipc.commands, "menuModel").mockResolvedValue([
{ kind: "action", id: "test.menuBlur", label: "Test", hint: null, arg: null, checked: null },
]);
const pushDisabled = vi.spyOn(ipc.commands, "menuSetDisabled").mockResolvedValue();
const offAction = registerAction({ id: "test.menuBlur", title: "Test", when: "testMenuBlurEditor", run: () => {} });
setContext("testMenuBlurEditor", true);
const dispose = installMenuBridge();
try {
await vi.advanceTimersByTimeAsync(120);
expect(pushDisabled).toHaveBeenCalledExactlyOnceWith([]);
pushDisabled.mockClear();
// Focus moves to the Settings window: the editor loses focus, then the window blurs.
hasFocus.mockReturnValue(false);
setContext("testMenuBlurEditor", false);
window.dispatchEvent(new Event("blur"));
await vi.advanceTimersByTimeAsync(120);
expect(pushDisabled).toHaveBeenCalledExactlyOnceWith(["test.menuBlur"]);
pushDisabled.mockClear();
// Later changes in a background window are not pushed.
setContext("testMenuBlurEditor", true);
await vi.advanceTimersByTimeAsync(120);
expect(pushDisabled).not.toHaveBeenCalled();
} finally {
dispose();
offAction();
clearContext("testMenuBlurEditor");
vi.useRealTimers();
vi.restoreAllMocks();
}
});
it("brings Settings back once the dialog opened from its menu closes (#3625)", async () => {
vi.useFakeTimers();
vi.spyOn(document, "hasFocus").mockReturnValue(true);
const focusSettings = vi.fn(async () => {});
try {
// About opens a dialog: Settings waits under it.
const about = returnFocusAfterMenu(
Promise.resolve(true)
.then(() => setContext("popupOpen", true))
.then(() => true),
focusSettings,
);
await vi.advanceTimersByTimeAsync(1000);
expect(focusSettings).not.toHaveBeenCalled();
setContext("popupOpen", false);
await about;
expect(focusSettings).toHaveBeenCalledOnce();
// An action that opens nothing: Settings comes back right away.
focusSettings.mockClear();
const saveAll = returnFocusAfterMenu(Promise.resolve(true), focusSettings);
await vi.advanceTimersByTimeAsync(300);
await saveAll;
expect(focusSettings).toHaveBeenCalledOnce();
// Focus moved on (a new window or a native dialog): Settings stays where it is.
focusSettings.mockClear();
vi.mocked(document.hasFocus).mockReturnValue(false);
const open = returnFocusAfterMenu(Promise.resolve(true), focusSettings);
await vi.advanceTimersByTimeAsync(300);
await open;
expect(focusSettings).not.toHaveBeenCalled();
} finally {
clearContext("popupOpen");
vi.useRealTimers();
vi.restoreAllMocks();
}
});
it("lists registered tool windows by title and saved layouts", () => {
localStorage.clear();
_reloadLayouts();
+2
Переглянути файл
@@ -8,6 +8,8 @@ vi.mock("@tauri-apps/api/core", () => ({
Channel: class {
onmessage: (p: unknown) => void = () => {};
},
// Balloons are mirrored to a system notification (`showSystemNotification`).
invoke: async () => null,
}));
type Channel = { onmessage: (p: UpdateProgress) => void };
+50
Переглянути файл
@@ -748,3 +748,53 @@ describe("explicit project-window requests", () => {
}
});
});
describe("trust is asked before a new project window opens", () => {
const openProjectPath = (arg: unknown) =>
windowActions()
.find((a) => a.id === "file.openProjectPath")!
.run({ arg } as never);
const newWindowEntries: [string, () => unknown][] = [
["Open… from a project window", () => openProjectInWindow("/p/b", false)],
["Open in New Window", () => openProjectInWindow("/p/b", true)],
["Open project in: New Window", () => openProjectWithPolicy("/p/b")],
["a plugin's new-window request", () => openProjectPath({ path: "/p/b", newWindow: true })],
];
it.each(newWindowEntries)("%s asks in this window first", async (_, open) => {
useProject.setState({ ...projectState("/p/a"), settings: { general: { openProjectIn: "new" } } } as never);
windowOpenProject.mockResolvedValue(ok({ kind: "opened", label: "project-1" }));
await open();
expect(confirmProjectTrust).toHaveBeenCalledWith("/p/b", "local");
expect(vi.mocked(confirmProjectTrust).mock.invocationCallOrder[0]).toBeLessThan(
windowOpenProject.mock.invocationCallOrder[0]!,
);
expect(windowOpenProject).toHaveBeenCalledWith("/p/b", true, []);
});
it.each(newWindowEntries)("%s opens no window when the user chooses Don't Open", async (_, open) => {
useProject.setState({ ...projectState("/p/a"), settings: { general: { openProjectIn: "new" } } } as never);
vi.mocked(confirmProjectTrust).mockRejectedValueOnce(new IpcError({ kind: "cancelled", message: "Cancelled" }));
await open();
expect(windowOpenProject).not.toHaveBeenCalled();
expect(notify).not.toHaveBeenCalled();
expect(useProject.getState().project?.root).toBe("/p/a");
});
it("leaves a WSL folder to the remote window, which asks about the distribution's project", async () => {
useProject.setState(projectState("/p/a") as never);
wslResolve.mockResolvedValue({ target: { kind: "wsl", distro: "Debian" }, path: "/srv/app" });
windowOpenProject.mockResolvedValue(ok({ kind: "opened", label: "project-1" }));
await openProjectInWindow("\\\\wsl.localhost\\Debian\\srv\\app", true);
expect(confirmProjectTrust).not.toHaveBeenCalled();
expect(windowOpenProject).toHaveBeenCalled();
});
it("asks only once, from openProject, when the project opens in this window", async () => {
windowOpenProject.mockResolvedValue(ok({ kind: "current" }));
await openProjectInWindow("/p/b", false);
expect(windowOpenProject).toHaveBeenCalledWith("/p/b", false, []);
expect(confirmProjectTrust).not.toHaveBeenCalled();
expect(openProject).toHaveBeenCalledWith("/p/b");
});
});
+123
Переглянути файл
@@ -0,0 +1,123 @@
/**
* JetBrains option names (as the IDE writes them to `options/editor.xml` and
* `codestyles/*.xml`) and the OpenIDEA settings of the same meaning. Each entry
* carries the label the option has in Settings, for the import confirmation.
*/
type Mapped = readonly [key: string, label: string];
/** `<component name="EditorSettings">`: on/off options. */
export const EDITOR_FLAGS: Record<string, Mapped> = {
IS_WHEEL_FONTCHANGE_ENABLED: ["editor.general.wheelZoom", "Change font size with Ctrl/Command+Mouse Wheel"],
IS_DND_ENABLED: ["editor.general.dragAndDrop", "Enable drag-and-drop functionality in editor"],
USE_CUSTOM_SOFT_WRAP_INDENT: ["editor.general.softWrapIndent", "Use original line's indent for wrapped parts"],
ADDITIONAL_PAGE_AT_BOTTOM: ["editor.general.scrollPastEnd", "Show virtual space at file bottom"],
KEEP_TRAILING_SPACE_ON_CARET_LINE: ["editor.general.keepTrailingOnCaretLine", "Keep trailing spaces on caret line"],
REMOVE_TRAILING_BLANK_LINES: [
"editor.general.removeTrailingBlankLines",
"Remove trailing blank lines at the end of saved files",
],
IS_CARET_BLINKING: ["editor.appearance.caretBlinking", "Caret blinking (ms):"],
IS_SMOOTH_CARET_BLINKING: ["editor.appearance.smoothCaretBlinking", "Use smooth caret blinking"],
IS_BLOCK_CURSOR: ["editor.appearance.blockCaret", "Use block caret"],
IS_SMOOTH_CARET_MOVEMENT: ["editor.appearance.smoothCaretMovement", "Use smooth caret movement"],
IS_RIGHT_MARGIN_SHOWN: [
"editor.appearance.hardWrapGuides",
"Show hard wrap and visual guides (configured in Code Style options)",
],
ARE_LINE_NUMBERS_SHOWN: ["editor.appearance.lineNumbers", "Show line numbers"],
IS_LEADING_WHITESPACES_SHOWN: ["editor.appearance.whitespaceLeading", "Leading"],
IS_INNER_WHITESPACES_SHOWN: ["editor.appearance.whitespaceInner", "Inner"],
IS_TRAILING_WHITESPACES_SHOWN: ["editor.appearance.whitespaceTrailing", "Trailing"],
IS_INDENT_GUIDES_SHOWN: ["editor.appearance.indentGuides", "Show indent guides"],
SHOW_INTENTION_BULB: ["editor.appearance.intentionBulb", "Show intention bulb"],
ENABLE_RENDERED_DOC: ["editor.appearance.renderDocComments", "Render documentation comments"],
SHOW_BREADCRUMBS: ["editor.breadcrumbs.show", "Show breadcrumbs:"],
IS_FOLDING_OUTLINE_SHOWN: ["editor.folding.showOutline", "Show code folding outline"],
SMART_HOME: ["editor.smartKeys.smartHome", "Home moves caret to first non-whitespace character"],
IS_CAMEL_WORDS: ["editor.smartKeys.camelHumps", 'Use "CamelHumps" words'],
IS_HIGHLIGHT_SELECTION_OCCURRENCES: ["editor.codeEditing.highlightSelection", "Occurrences of selected text"],
SHOW_QUICK_DOC_ON_MOUSE_OVER_ELEMENT: ["editor.codeEditing.quickDocOnHover", "Show quick documentation on hover"],
INSERT_PARENTHESES_AUTOMATICALLY: [
"editor.completion.insertParentheses",
"Insert parentheses automatically when applicable",
],
};
/** `<component name="EditorSettings">`: numbers. */
export const EDITOR_NUMBERS: Record<string, Mapped> = {
CARET_BLINKING_PERIOD: ["editor.appearance.caretBlinkPeriod", "Caret blinking (ms):"],
STICKY_LINES_LIMIT: ["editor.codeEditing.stickyLinesMax", "Maximum number of lines"],
TOOLTIPS_DELAY_MS: ["editor.codeEditing.quickDocDelay", "Tooltip delay"],
};
/** `<component name="CodeInsightSettings">`: on/off options. */
export const CODE_INSIGHT_FLAGS: Record<string, Mapped> = {
AUTOINSERT_PAIR_BRACKET: ["editor.smartKeys.pairBrackets", "Insert paired brackets (), [], {}"],
AUTOINSERT_PAIR_QUOTE: ["editor.smartKeys.pairQuotes", "Insert pair quote"],
SURROUND_SELECTION_ON_QUOTE_TYPED: [
"editor.smartKeys.surroundSelection",
"Surround selection on typing quote or brace",
],
TAB_EXITS_BRACKETS_AND_QUOTES: ["editor.smartKeys.tabOutOfPair", "Jump outside closing bracket/quote with Tab"],
SMART_INDENT_ON_ENTER: ["editor.smartKeys.smartIndent", "Smart indent"],
JAVADOC_STUB_ON_ENTER: ["editor.smartKeys.insertDocStub", "Insert documentation comment stub"],
HIGHLIGHT_IDENTIFIER_UNDER_CARET: ["editor.codeEditing.highlightUsages", "Usages of element at caret"],
HIGHLIGHT_BRACES: ["editor.codeEditing.highlightBraces", "Matched brace"],
AUTO_POPUP_COMPLETION_LOOKUP: ["editor.completion.autoPopup", "Show suggestions as you type"],
AUTOCOMPLETE_ON_CODE_COMPLETION: ["editor.completion.autoInsertSingle", "Automatically insert single suggestions"],
AUTO_POPUP_JAVADOC_INFO: ["editor.completion.showDocumentation", "Show the documentation popup in"],
AUTO_POPUP_PARAMETER_INFO: ["editor.completion.parameterInfo", "Show the parameter info popup in"],
};
/** `<component name="CodeInsightSettings">`: numbers. */
export const CODE_INSIGHT_NUMBERS: Record<string, Mapped> = {
JAVADOC_INFO_DELAY: ["editor.completion.documentationDelay", "Show the documentation popup in"],
PARAMETER_INFO_DELAY: ["editor.completion.parameterInfoDelay", "Show the parameter info popup in"],
};
/** `REFORMAT_ON_PASTE` (IDEA's `CodeInsightSettings` constants) → `editor.smartKeys.reformatOnPaste`, its label. */
export const REFORMAT_ON_PASTE: Record<string, Mapped> = {
"1": ["none", "None"],
"2": ["indentBlock", "Indent Block"],
"3": ["indentEachLine", "Indent Each Line"],
};
/** `SMART_BACKSPACE` (IDEA's `SmartBackspaceMode` ordinals) → `editor.smartKeys.backspaceUnindent`, its label. */
export const SMART_BACKSPACE: Record<string, Mapped> = {
"0": ["none", "Disabled"],
"1": ["nearest", "To nearest indent position"],
"2": ["autoindent", "To proper indent position"],
};
/** `<codeStyleSettings language=…>` → the language ids that share that code style here. */
export const CODE_STYLE_LANGUAGES: Record<string, readonly string[]> = {
JAVA: ["java"],
kotlin: ["kotlin"],
Groovy: ["groovy"],
Scala: ["scala"],
JavaScript: ["javascript", "javascriptreact"],
TypeScript: ["typescript", "typescriptreact"],
Vue: ["vue"],
HTML: ["html"],
XML: ["xml"],
CSS: ["css"],
SCSS: ["scss"],
SASS: ["sass"],
LESS: ["less"],
JSON: ["json", "jsonc"],
yaml: ["yaml"],
TOML: ["toml"],
Markdown: ["markdown"],
Python: ["python"],
go: ["go"],
Rust: ["rust"],
PHP: ["php"],
ruby: ["ruby"],
Dart: ["dart"],
Swift: ["swift"],
"C#": ["csharp"],
Lua: ["lua"],
SQL: ["sql"],
"Shell Script": ["shellscript"],
};
+228 -18
Переглянути файл
@@ -1,20 +1,32 @@
/**
* Import Settings… with a JetBrains `settings.zip`: maps the archive's colour
* schemes and the editor / general options OpenIDEA has to settings writes, after
* a confirmation listing them. Only keys present in the archive are written
* (JetBrains leaves defaults out). Keymaps, code styles and the rest are listed
* as not imported.
* schemes, keymaps, fonts, tabs and indents, and the editor / general options
* OpenIDEA has to settings writes, after a confirmation listing them. Only keys
* present in the archive are written (JetBrains leaves defaults out). The rest
* is listed as not imported.
*/
import { Fragment } from "react";
import type { JetBrainsSettings } from "@/bindings";
import type { CustomKeymap, JetBrainsSettings, LanguageCodeStyle } from "@/bindings";
import { customSchemes } from "@/platform/colorScheme";
import { createFontProbeCanvas, fontsLoaded, monoFontFamily } from "@/platform/fonts";
import { tx } from "@/platform/i18n";
import { importScheme, parseIcls } from "@/platform/icls";
import { addIdeaKeymap, parseIdeaKeymap } from "@/platform/ideaKeymap";
import { call, commands } from "@/platform/ipc";
import { guessOs } from "@/platform/platformInfo";
import { useProject } from "@/platform/project";
import { notifications } from "@/workbench/contributions";
import { ask } from "@/workbench/messages";
import styles from "./app.module.css";
import {
CODE_INSIGHT_FLAGS,
CODE_INSIGHT_NUMBERS,
CODE_STYLE_LANGUAGES,
EDITOR_FLAGS,
EDITOR_NUMBERS,
REFORMAT_ON_PASTE,
SMART_BACKSPACE,
} from "./jetbrainsOptions";
export interface JetBrainsImportPlan {
/** Settings writes, in order: `settingsSet("global", key, JSON.stringify(value))`. */
@@ -23,14 +35,22 @@ export interface JetBrainsImportPlan {
rows: { label: string; value: string }[];
/** Categories present in the archive that are not imported (translated). */
skipped: string[];
/** `.icls` files that could not be read. */
/** Colour scheme and keymap files that could not be read. */
invalid: string[];
/** IDEA action ids the imported keymaps bind that have no counterpart here. */
unknownActions: string[];
}
interface EditorState {
fontSize: number | null;
customSchemes: unknown;
colorOverrides: Record<string, unknown>;
/** The settings the import builds on (`settingsGetGlobal`). */
interface CurrentSettings {
editor: {
fontFamily: string;
fontSize: number | null;
customSchemes: unknown;
colorOverrides: Record<string, unknown>;
codeStyle?: { languages?: Record<string, LanguageCodeStyle> };
};
customKeymaps?: Record<string, CustomKeymap>;
}
const USER_PREFIX = "_@user_";
@@ -63,8 +83,67 @@ const num = (v: string | undefined) => {
const onOff = (v: boolean) => (v ? tx("On") : tx("Off"));
export function planJetBrainsImport(bundle: JetBrainsSettings, editor: EditorState): JetBrainsImportPlan {
const plan: JetBrainsImportPlan = { writes: [], rows: [], skipped: [], invalid: [] };
/** IDEA's `LINE_SPACING` when the export leaves it out. */
const DEFAULT_LINE_SPACING = 1.2;
/** The font's own line height in px, as IDEA's editor takes it from Java's FontMetrics. */
export type FontHeight = (family: string, size: number) => Promise<number | undefined> | number | undefined;
/** WebKit reports whole-pixel metrics; measured this large, they keep the font's fractions. */
const PROBE_SIZE = 1000;
async function measuredFontHeight(family: string, size: number): Promise<number | undefined> {
// The editor's own stack: WKWebView draws an installed font only through its loaded alias.
const stack = monoFontFamily(family);
await fontsLoaded(stack, size);
const canvas = createFontProbeCanvas();
try {
const ctx = canvas.getContext("2d");
if (!ctx) return undefined;
ctx.font = `${PROBE_SIZE}px ${stack}`;
const m = ctx.measureText("M");
// Java rounds the ascent and the descent up separately (anything past .05 of a pixel).
const px = (v: number) => Math.floor((v / PROBE_SIZE) * size + 0.95);
const h = px(m.fontBoundingBoxAscent) + px(m.fontBoundingBoxDescent);
return Number.isFinite(h) && h > 0 ? h : undefined;
} finally {
canvas.remove();
}
}
/** `<option name value>` children of `parent`. */
function optionValues(parent: Element | null | undefined): Map<string, string> {
const out = new Map<string, string>();
for (const o of Array.from(parent?.children ?? [])) {
const name = o.getAttribute("name");
const value = o.getAttribute("value");
if (o.tagName === "option" && name && value !== null) out.set(name, value);
}
return out;
}
const childOf = (parent: Element, tag: string, name?: string) =>
Array.from(parent.children).find((c) => c.tagName === tag && (name === undefined || c.getAttribute("name") === name));
/** The code style scheme called `name` among `codestyles/*.xml`. */
function codeScheme(files: Record<string, string>, name: string): Element | undefined {
for (const [file, text] of Object.entries(files)) {
if (!file.startsWith("codestyles/")) continue;
const doc = new DOMParser().parseFromString(text, "application/xml");
const root = doc.documentElement;
if (!doc.querySelector("parsererror") && root.tagName === "code_scheme" && root.getAttribute("name") === name)
return root;
}
return undefined;
}
export async function planJetBrainsImport(
bundle: JetBrainsSettings,
current: CurrentSettings,
fontHeight: FontHeight = measuredFontHeight,
): Promise<JetBrainsImportPlan> {
const { editor } = current;
const plan: JetBrainsImportPlan = { writes: [], rows: [], skipped: [], invalid: [], unknownActions: [] };
const add = (key: string, value: string | number | boolean | undefined, label: string, shown?: string) => {
if (value === undefined) return;
plan.writes.push([key, value]);
@@ -100,15 +179,63 @@ export function planJetBrainsImport(bundle: JetBrainsSettings, editor: EditorSta
if (id) add("editor.colorScheme", id, tx("Current color scheme"), customs[id]?.name);
}
let keymaps = current.customKeymaps ?? {};
const importedKeymaps = new Map<string, string>(); // name in the keymap file → keymap id
for (const [file, text] of Object.entries(bundle.files)) {
if (!file.startsWith("keymaps/")) continue;
let parsed;
try {
parsed = parseIdeaKeymap(text);
} catch {
plan.invalid.push(file.slice("keymaps/".length));
continue;
}
// Overwrites an earlier import of the same keymap, as colour schemes do.
const next = addIdeaKeymap(keymaps, parsed);
keymaps = next.customs;
importedKeymaps.set(parsed.name, next.id);
plan.unknownActions.push(...parsed.unknownActions.filter((id) => !plan.unknownActions.includes(id)));
plan.rows.push({ label: tx("Keymap"), value: keymaps[next.id]?.name ?? parsed.name });
}
if (importedKeymaps.size) {
plan.writes.push(["customKeymaps", keymaps]);
// The active keymap is stored per operating system; a bundled one keeps OpenIDEA's choice.
const os = { macos: "mac", windows: "windows", linux: "linux", web: "" }[guessOs()];
const active = options(bundle.files[`options/${os}/keymap.xml`], "KeymapManager", "active_keymap").get("");
const id = importedKeymaps.get(active ?? "");
if (id) add("keymap", id, tx("Current keymap"), keymaps[id]?.name);
}
const font = options(bundle.files["options/editor-font.xml"], "DefaultFont");
add("editor.fontFamily", font.get("FONT_FAMILY")?.trim() || undefined, tx("Font"));
const family = font.get("FONT_FAMILY")?.trim() || undefined;
add("editor.fontFamily", family, tx("Font"));
const size = num(font.get("FONT_SIZE"));
add("editor.fontSize", size, tx("Size"));
const spacing = num(font.get("LINE_SPACING"));
// IDEA spaces lines by the font's own height, not its size, so a tall font keeps its
// spacing; and the default spacing still applies when only the font changed.
const base = size ?? editor.fontSize;
add("editor.lineHeight", spacing && base ? Math.round(base * spacing) : undefined, tx("Line height"));
if (base && (family || size || spacing)) {
const natural = (await fontHeight(family ?? editor.fontFamily, base)) ?? base * DEFAULT_LINE_SPACING;
add("editor.lineHeight", Math.ceil(natural * (spacing ?? DEFAULT_LINE_SPACING)), tx("Line height"));
}
add("editor.ligatures", bool(font.get("USE_LIGATURES")), tx("Enable ligatures"));
const terminal = options(bundle.files["options/terminal-font.xml"], "TerminalFontOptions");
const terminalFamily = terminal.get("FONT_FAMILY")?.trim() || undefined;
const terminalSize = num(terminal.get("FONT_SIZE"));
// A terminal font of its own: stop following the editor font (the font rows below say so).
if (terminalFamily || terminalSize) plan.writes.push(["terminal.useEditorFont", false]);
add("terminal.fontFamily", terminalFamily, tx("Terminal font"));
add("terminal.fontSize", terminalSize, tx("Terminal font size"));
add("terminal.lineHeight", num(terminal.get("LINE_SPACING")), tx("Terminal line height"));
add("terminal.columnWidth", num(terminal.get("COLUMN_SPACING")), tx("Terminal column width"));
add(
"terminal.fallbackFontFamily",
terminal.get("SECONDARY_FONT_FAMILY")?.trim() || undefined,
tx("Terminal fallback font"),
);
const ed = options(bundle.files["options/editor.xml"], "EditorSettings");
const strip = ed.get("STRIP_TRAILING_SPACES"); // None | Changed | Whole
if (strip === "Changed" || strip === "Whole") {
@@ -135,13 +262,95 @@ export function planJetBrainsImport(bundle: JetBrainsSettings, editor: EditorSta
wraps === undefined ? undefined : wraps.split(",").includes("MAIN_EDITOR"),
tx("Soft-wrap files"),
);
add(
"console.softWrap",
wraps === undefined ? undefined : wraps.split(",").includes("CONSOLE"),
tx("Use soft wraps in console"),
);
add("editor.general.softWrapFiles", ed.get("SOFT_WRAP_FILE_MASKS")?.trim() || undefined, tx("File patterns"));
const numeration = { ABSOLUTE: "Absolute", RELATIVE: "Relative", HYBRID: "Hybrid" }[ed.get("LINE_NUMERATION") ?? ""];
add("editor.appearance.lineNumberMode", numeration?.toLowerCase(), tx("Show line numbers"), tx(numeration ?? ""));
const above = bool(ed.get("SHOW_BREADCRUMBS_ABOVE"));
add(
"editor.breadcrumbs.placement",
above === undefined ? undefined : above ? "top" : "bottom",
tx("Show breadcrumbs:"),
tx(above ? "Top" : "Bottom"),
);
const insight = options(bundle.files["options/editor.xml"], "CodeInsightSettings");
for (const [source, flags, numbers] of [
[ed, EDITOR_FLAGS, EDITOR_NUMBERS],
[insight, CODE_INSIGHT_FLAGS, CODE_INSIGHT_NUMBERS],
] as const) {
for (const [name, [key, label]] of Object.entries(flags)) add(key, bool(source.get(name)), tx(label));
for (const [name, [key, label]] of Object.entries(numbers)) add(key, num(source.get(name)), tx(label));
}
const paste = REFORMAT_ON_PASTE[insight.get("REFORMAT_ON_PASTE") ?? ""];
add("editor.smartKeys.reformatOnPaste", paste?.[0], tx("Reformat on paste"), tx(paste?.[1] ?? ""));
const backspace = SMART_BACKSPACE[insight.get("SMART_BACKSPACE") ?? ""];
add("editor.smartKeys.backspaceUnindent", backspace?.[0], tx("Unindent"), tx(backspace?.[1] ?? ""));
// Tabs and Indents of the current code style scheme; its other formatting options have no setting here.
const schemeName =
options(bundle.files["options/code.style.schemes.xml"], "CodeStyleSchemeSettings").get("CURRENT_SCHEME_NAME") ??
"Default";
const scheme = codeScheme(bundle.files, schemeName);
if (scheme) {
const root = optionValues(scheme);
add("editor.codeStyle.hardWrapAt", num(root.get("RIGHT_MARGIN")), tx("Hard wrap at"));
add(
"editor.codeStyle.detectIndents",
bool(root.get("AUTODETECT_INDENTS")),
tx("Detect and use existing file indents for editing"),
);
// "Other File Types": the indent of languages without a code style of their own.
const other = optionValues(childOf(childOf(scheme, "option", "OTHER_INDENT_OPTIONS") ?? scheme, "value"));
add("editor.tabSize", num(other.get("TAB_SIZE")), tx("Tab size"));
const otherTabs = bool(other.get("USE_TAB_CHARACTER"));
add(
"editor.insertSpaces",
otherTabs === undefined ? undefined : !otherTabs,
tx("Use tab character"),
otherTabs === undefined ? undefined : onOff(otherTabs),
);
const languages = { ...editor.codeStyle?.languages };
let changed = false;
for (const block of Array.from(scheme.children)) {
const ids = CODE_STYLE_LANGUAGES[block.getAttribute("language") ?? ""];
if (block.tagName !== "codeStyleSettings" || !ids) continue;
const own = optionValues(block);
const indent = optionValues(childOf(block, "indentOptions"));
const style: Partial<LanguageCodeStyle> = {};
const shown: string[] = [];
const set = <K extends keyof LanguageCodeStyle>(
key: K,
value: LanguageCodeStyle[K] | undefined,
label: string,
) => {
if (value === undefined) return;
style[key] = value;
shown.push(`${tx(label)} ${typeof value === "boolean" ? onOff(value) : value}`);
};
set("indent", num(indent.get("INDENT_SIZE")), "Indent");
set("tabSize", num(indent.get("TAB_SIZE")), "Tab size");
set("useTab", bool(indent.get("USE_TAB_CHARACTER")), "Use tab character");
set("hardWrapAt", num(own.get("RIGHT_MARGIN")), "Hard wrap at");
set("lineCommentAtFirstColumn", bool(own.get("LINE_COMMENT_AT_FIRST_COLUMN")), "Line comment at first column");
set("lineCommentAddSpace", bool(own.get("LINE_COMMENT_ADD_SPACE")), "Add a space at line comment start");
if (!shown.length) continue;
for (const id of ids) languages[id] = { ...languages[id], ...style } as LanguageCodeStyle;
changed = true;
plan.rows.push({ label: `${tx("Code Style")} › ${block.getAttribute("language")}`, value: shown.join(", ") });
}
if (changed) plan.writes.push(["editor.codeStyle.languages", languages]);
}
const general = options(bundle.files["options/ide.general.xml"], "GeneralSettings");
add("general.confirmExit", bool(general.get("confirmExit")), tx("Confirm before exiting the IDE"));
const has = (prefix: string) => bundle.entries.some((e) => e.startsWith(prefix));
if (has("keymaps/")) plan.skipped.push(tx("Keymap"));
if (has("codestyles/")) plan.skipped.push(tx("Code Style"));
if (has("codestyles/")) plan.skipped.push(tx("Code Style options other than Tabs and Indents"));
if (has("templates/")) plan.skipped.push(tx("Live templates"));
if (has("inspection/")) plan.skipped.push(tx("Inspections"));
if (has("installed.txt")) plan.skipped.push(tx("Plugins"));
@@ -150,6 +359,7 @@ export function planJetBrainsImport(bundle: JetBrainsSettings, editor: EditorSta
function Summary({ plan }: { plan: JetBrainsImportPlan }) {
const left = [...plan.skipped, ...plan.invalid];
const unknown = plan.unknownActions;
return (
<div className={styles.importSummary}>
<div>{tx("These settings will be imported:")}</div>
@@ -166,6 +376,7 @@ function Summary({ plan }: { plan: JetBrainsImportPlan }) {
{tx("Not imported:")} {left.join(", ")}
</div>
)}
{unknown.length > 0 && <div>{tx`Not available in OpenIDEA (${unknown.length}): ${unknown.join(", ")}.`}</div>}
</div>
);
}
@@ -173,8 +384,7 @@ function Summary({ plan }: { plan: JetBrainsImportPlan }) {
/** Reads `path`, asks, then writes the mapped settings to the global layer. */
export async function importJetBrainsSettings(path: string) {
const bundle = await call(commands.settingsReadJetbrains(path));
const { editor } = await commands.settingsGetGlobal();
const plan = planJetBrainsImport(bundle, editor);
const plan = await planJetBrainsImport(bundle, await commands.settingsGetGlobal());
if (!plan.writes.length) {
notifications().notify({
level: "warning",
+53 -4
Переглянути файл
@@ -8,7 +8,7 @@
* equivalent while the JS keymap stays the only dispatcher (see src-tauri/src/menu.rs).
*/
import { executeActionFrom, getAction, isActionEnabled, useActions } from "@/platform/actions";
import { useContextKeys } from "@/platform/context";
import { getContext, useContextKeys } from "@/platform/context";
import { keysWithPrefix, t, tx, useI18n } from "@/platform/i18n";
import { commands, isTauri, type DynamicItem, type MenuConfig, type MenuNode } from "@/platform/ipc";
import {
@@ -32,6 +32,8 @@ export const MENU_EVENT = "openidea://menu";
export interface MenuRoute {
action: string;
arg?: string | null;
/** The window in front when the item was chosen, if it is not this one (this window's Settings). */
returnTo?: string;
}
export function isMenuRoute(v: unknown): v is MenuRoute {
@@ -47,6 +49,36 @@ export function routeMenuEvent(
return run(payload.action, payload.arg ?? undefined);
}
/** How long an action chosen from the menu may take to open its dialog or popup. */
const OPEN_DELAY_MS = 300;
const layersClosed = () =>
new Promise<void>((resolve) => {
if (!getContext().popupOpen) return resolve();
const off = useContextKeys.subscribe((ctx) => {
if (ctx.popupOpen) return;
off();
resolve();
});
});
/**
* After an item chosen in this window's Settings window ran here (the backend brought this window
* forward): once the dialog or popup it opened closes, or right away if it opened none, Settings comes
* back to the front, as IDEA's Settings dialog stays under the dialogs opened from the menu. Not when
* focus has moved on (a new window, a native dialog).
*/
export async function returnFocusAfterMenu(
ran: Promise<boolean>,
focusWindow: () => Promise<void>,
delay = OPEN_DELAY_MS,
): Promise<void> {
await ran;
await new Promise((r) => setTimeout(r, delay));
await layersClosed();
if (document.hasFocus()) await focusWindow();
}
/**
* Keymap key names a macOS key equivalent can show. Mirrors the names muda's accelerator
* parser accepts: Tauri drops an accelerator it cannot parse, and the item shows no shortcut.
@@ -167,22 +199,36 @@ export function installMenuBridge(): () => void {
void import("@tauri-apps/api/webviewWindow").then(async ({ getCurrentWebviewWindow }) => {
// Window-scoped: a global `listen` would also receive other windows' menu events.
const off = await getCurrentWebviewWindow().listen(MENU_EVENT, ({ payload }) => void routeMenuEvent(payload));
const off = await getCurrentWebviewWindow().listen(MENU_EVENT, ({ payload }) => {
const ran = routeMenuEvent(payload);
const returnTo = isMenuRoute(payload) ? payload.returnTo : undefined;
if (returnTo)
void returnFocusAfterMenu(ran, async () => {
const { Window } = await import("@tauri-apps/api/window");
await (await Window.getByLabel(returnTo))?.setFocus();
}).catch(() => {});
});
if (disposed) off();
else unlisten = off;
});
// Enablement of the native items follows this window's context (IDEA greys out
// what cannot run). Recomputed shortly after context changes, sent only when it changed.
// Also once on blur: the menu still runs here while this window's Settings window is focused,
// with nothing focused here (editor actions disabled). The backend ignores it for other windows.
let ids: Set<string> | null = null;
let lastDisabled = "";
let forceEnablement = false;
let afterBlur = false;
let enableTimer: ReturnType<typeof setTimeout> | undefined;
const pushEnablement = (force = false) => {
const pushEnablement = (force = false, blurred = false) => {
forceEnablement ||= force;
afterBlur ||= blurred;
clearTimeout(enableTimer);
enableTimer = setTimeout(() => {
if (!ids || disposed || !document.hasFocus()) return;
const unfocused = !document.hasFocus();
if (!ids || disposed || (unfocused && !afterBlur)) return;
afterBlur = false;
const dynamic = Object.values(dynamicMenuItems()).flatMap((items) => items.map((d) => d.action));
const disabled = disabledMenuActions(new Set([...ids, ...dynamic]));
const key = disabled.join(",");
@@ -209,6 +255,8 @@ export function installMenuBridge(): () => void {
// The backend edits only submenus whose visible items changed, so switching project
// tabs does not redraw the macOS menu bar.
window.addEventListener("focus", onFocus);
const onBlur = () => pushEnablement(true, true);
window.addEventListener("blur", onBlur);
const unsubs = [
useI18n.subscribe((s, prev) => {
if (s.messages !== prev.messages) push();
@@ -237,6 +285,7 @@ export function installMenuBridge(): () => void {
clearTimeout(timer);
clearTimeout(enableTimer);
window.removeEventListener("focus", onFocus);
window.removeEventListener("blur", onBlur);
unlisten?.();
unsubs.forEach((u) => u());
};
+13 -2
Переглянути файл
@@ -130,6 +130,17 @@ export async function openPaths(
if (dir) await openProjectWithPolicy(dir);
}
/**
* `window_open_project`. When that may create a window, the trust question is asked here
* first (IntelliJ IDEA asks before the project frame opens): the new window would otherwise
* show its Welcome screen under the question. A WSL folder opens as a remote project, whose
* window asks about the distribution's folder itself.
*/
async function openProjectWindow(path: string, newWindow: boolean, files: readonly string[] = []) {
if (newWindow && !(await commands.wslResolve(path).catch(() => null))) await confirmProjectTrust(path, "local");
return call(commands.windowOpenProject(path, newWindow, [...files]));
}
/**
* Opens `path`, focusing the window that already has it. `newWindow`: always a
* new window; otherwise this window unless it already has a project or LightEdit
@@ -140,7 +151,7 @@ export async function openProjectInWindow(path: string, newWindow: boolean, file
const s = useProject.getState();
const inNew = newWindow || s.project !== null || s.lightEdit;
try {
const outcome = await call(commands.windowOpenProject(path, inNew, [...files]));
const outcome = await openProjectWindow(path, inNew, files);
if (outcome.kind === "current" && (await openHere(path))) await openInEditor(files);
} catch (e) {
openFailed(path, e);
@@ -535,7 +546,7 @@ export function windowActions(): Action[] {
const arg = c.arg as { path?: unknown; newWindow?: unknown } | null;
if (!arg || typeof arg.path !== "string" || typeof arg.newWindow !== "boolean") return;
try {
const outcome = await call(commands.windowOpenProject(arg.path, arg.newWindow, []));
const outcome = await openProjectWindow(arg.path, arg.newWindow);
if (outcome.kind === "current") await openHere(arg.path);
} catch (error) {
openFailed(arg.path, error);
+32 -23
Переглянути файл
@@ -251,6 +251,8 @@
min-height: 0;
display: flex;
flex-direction: column;
/* Data source colours are stronger than file colours. */
--row-tint-strength: var(--tint-strength);
}
.treeHost > * {
flex: 1;
@@ -262,29 +264,6 @@
gap: var(--space-1-5);
min-width: 0;
}
/* The whole tree row, indent included, so a coloured source and its children form one band. */
.tintedRow:not([aria-selected="true"]):not(:hover) {
border-radius: 0;
background: color-mix(in srgb, var(--db-tint) var(--tint-strength), transparent);
}
.tintRed {
--db-tint: var(--db-color-red);
}
.tintOrange {
--db-tint: var(--db-color-orange);
}
.tintYellow {
--db-tint: var(--db-color-yellow);
}
.tintGreen {
--db-tint: var(--db-color-green);
}
.tintBlue {
--db-tint: var(--db-color-blue);
}
.tintViolet {
--db-tint: var(--db-color-violet);
}
.nodeLabel {
overflow: hidden;
text-overflow: ellipsis;
@@ -1407,3 +1386,33 @@
color: inherit;
cursor: default;
}
/* In-Editor Results: a result set under its statement in the console. */
:global(.cm-openidea-db-inline) {
padding: var(--space-1) 0 var(--space-2);
cursor: default;
}
.inlineResult {
position: relative;
display: flex;
flex-direction: column;
max-width: 100%;
border: 1px solid var(--border);
border-radius: var(--radius-control);
overflow: hidden;
background: var(--bg-editor);
font-family: var(--font-ui);
font-size: var(--fs-ui);
line-height: normal;
white-space: normal;
}
.inlineResult > :first-child {
flex: 1;
min-height: 0;
}
.inlineResize {
position: absolute;
inset: auto 0 0;
height: 5px;
cursor: row-resize;
}
+5 -5
Переглянути файл
@@ -8,7 +8,6 @@ import { tablesKey, useDatabase } from "./store";
import { tableInput } from "./tableInput";
import { useEditorRegistry } from "@/editor/api";
import { provideEditorService, provideToolWindowService, type EditorInput } from "@/workbench/contributions";
import styles from "./Database.module.css";
vi.mock("@tanstack/react-virtual", () => ({
useVirtualizer: ({ count }: { count: number }) => ({
@@ -195,9 +194,10 @@ describe("data source colour", () => {
});
render(<DatabaseView />);
const tree = within(screen.getByRole("tree", { name: "Data sources" }));
for (const name of ["PostgreSQL", "public", "routines", "refresh_data"]) {
expect(tree.getByText(name).closest('[role="treeitem"]')).toHaveClass(styles.tintedRow!, styles.tintRed!);
}
expect(tree.getByText("SQLite").closest('[role="treeitem"]')).not.toHaveClass(styles.tintedRow!);
const tint = (name: string) =>
tree.getByText(name).closest<HTMLElement>('[role="treeitem"]')!.style.getPropertyValue("--row-tint");
for (const name of ["PostgreSQL", "public", "routines", "refresh_data"])
expect(tint(name)).toBe("var(--db-color-red)");
expect(tint("SQLite")).toBe("");
});
});
+3 -12
Переглянути файл
@@ -6,7 +6,7 @@
* source to open its query console.
*/
import { useEffect, useMemo, useRef } from "react";
import type { DbColor, DbDatabases, DbTableDetails } from "@/platform/ipc";
import type { DbDatabases, DbTableDetails } from "@/platform/ipc";
import { executeAction } from "@/platform/actions";
import { shortcutLabel } from "@/platform/keymap";
import {
@@ -55,15 +55,6 @@ import styles from "./Database.module.css";
import { tx } from "@/platform/i18n";
import { databaseRequest } from "./requests";
const ROW_TINTS: Record<DbColor, string | undefined> = {
red: styles.tintRed,
orange: styles.tintOrange,
yellow: styles.tintYellow,
green: styles.tintGreen,
blue: styles.tintBlue,
violet: styles.tintViolet,
};
const GROUP_LABELS: Record<Group, string> = {
columns: "columns",
keys: "keys",
@@ -525,11 +516,11 @@ export function DatabaseView() {
getIcon={(n) => icon(n)}
getDetail={detail}
getColor={(n) => (n.kind === "message" && n.error ? "var(--danger)" : undefined)}
rowClassName={(n) => {
rowTint={(n) => {
// IDEA tints every row of a coloured data source across its full width and height.
const target = nodeTarget(n);
const color = target ? sourceOf(target)?.color : null;
return color ? `${styles.tintedRow} ${ROW_TINTS[color]}` : undefined;
return color ? `var(--db-color-${color})` : undefined;
}}
speedSearchField
renderNode={(n: Node, state) => {
+2
Переглянути файл
@@ -13,6 +13,7 @@ const ObjectDialogs = lazyComponent(() => import("./ObjectDialogs").then((m) =>
const ExportDialog = lazyComponent(() => import("./ExportDialog").then((m) => m.ExportDialog));
const HistoryDialog = lazyComponent(() => import("./DataDialogs").then((m) => m.HistoryDialog));
const ImportDialog = lazyComponent(() => import("./DataDialogs").then((m) => m.ImportDialog));
const SchemaCompareDialog = lazyComponent(() => import("./SchemaCompareDialog").then((m) => m.SchemaCompareDialog));
function PasswordDialog({ source, resolve }: { source: DataSource; resolve: (ok: boolean) => void }) {
const [password, setPassword] = useState("");
@@ -185,6 +186,7 @@ export function DatabaseDialogs() {
if (dialog.kind === "params") return <ParamsDialog names={dialog.names} resolve={dialog.resolve} />;
if (dialog.kind === "export")
return <ExportDialog data={dialog.data} source={dialog.source} initialFormat={dialog.format} />;
if (dialog.kind === "compareSchemas") return <SchemaCompareDialog initial={dialog.source} />;
if (dialog.kind === "history") return <HistoryDialog key={dialog.id} id={dialog.id} path={dialog.path} />;
if (dialog.kind === "import")
return (
+4 -2
Переглянути файл
@@ -254,7 +254,8 @@ function setSubmittingResult(result: DbQueryResult, on: boolean) {
notifyResults();
}
function Result({ tab }: { tab: ResultTab }) {
/** A result set's toolbar, grid and pager; `onClose` makes it an in-editor result (closed in place, not pinned). */
export function Result({ tab, onClose }: { tab: ResultTab; onClose?: () => void }) {
const [view, setView] = useState<"table" | "chart">("table");
const [panel, setPanel] = useState<DataPanel | null>(null);
const [searchOpen, setSearchOpen] = useState(false);
@@ -516,7 +517,7 @@ function Result({ tab }: { tab: ResultTab }) {
disabled={busy}
onClick={() => void rerunResult(tab.id)}
/>
<PinButton tab={tab} />
{!onClose && <PinButton tab={tab} />}
{view === "table" && (
<IconButton
icon="search"
@@ -568,6 +569,7 @@ function Result({ tab }: { tab: ResultTab }) {
onClick={(e) => showExport({ x: e.clientX, y: e.clientY })}
/>
{view === "table" && <PanelToggle panel={panel} onChange={setPanel} />}
{onClose && <IconButton icon="close" title="Close" onClick={onClose} />}
</Toolbar>
{view === "chart" ? (
<div className={styles.fill}>
+91
Переглянути файл
@@ -0,0 +1,91 @@
.body {
display: flex;
flex-direction: column;
gap: var(--space-2);
height: 560px;
padding: 14px;
}
.pickers {
display: flex;
align-items: center;
gap: var(--space-2);
flex-wrap: wrap;
}
.side {
display: flex;
align-items: center;
gap: var(--space-1);
}
.sideLabel {
color: var(--fg-secondary);
}
.arrow {
color: var(--fg-muted);
}
.toolbar {
display: flex;
align-items: center;
gap: var(--space-2);
}
.spacer {
flex: 1;
}
.count,
.direction {
color: var(--fg-muted);
}
.panes {
display: flex;
gap: var(--space-2);
flex: 1;
min-height: 0;
}
.tree {
display: flex;
flex-direction: column;
flex: 1.2;
min-width: 0;
border: 1px solid var(--border);
border-radius: var(--radius-control);
overflow: hidden;
}
.tree > * {
flex: 1;
min-height: 0;
}
.preview {
flex: 1;
min-width: 0;
}
.row {
display: inline-flex;
align-items: center;
gap: var(--space-1-5);
min-width: 0;
}
.name {
white-space: nowrap;
}
.detail {
overflow: hidden;
color: var(--fg-muted);
text-overflow: ellipsis;
white-space: nowrap;
}
.state {
width: 12px;
font-weight: 600;
text-align: center;
}
.added {
color: var(--vcs-added);
}
.removed {
color: var(--vcs-deleted);
}
.changed {
color: var(--vcs-modified);
}
.same {
color: var(--fg-muted);
}
Loaded 100 of 165 files, more files were not shown because too many files have changed in this diff. Show more