Compare commits

...
Author SHA1 Message Date
l0ng-ai fd5f95760f docs: record product and design-system context
PRODUCT.md records the users, positioning, constraints and evidence the UI must respect.
DESIGN.md documents the visual system from src/styles/tokens.css and the src/ui primitives:
colour roles, the type scale, density and compact mode, tonal layering with shadows only on
floating surfaces, and component rules. .impeccable/ holds the design tool's config and the
machine-readable form of DESIGN.md.

The UI guidelines now say Islands Light is the default theme and list the built-in themes,
instead of describing the style as dark.
2026-11-25 09:18:36 +08:00
Deng Liuanddengliu 8e9a0e48cf fix(vfs): ignore fsmonitor traffic in linked worktrees (#5717)
With Git's built-in fsmonitor enabled, even read-only git status / git diff create cookie files under .git/worktrees/<id>/fsmonitor--daemon/. The watcher treated everything below .git/worktrees as VCS metadata, so each VCS or agent change-list refresh produced cookies that scheduled another refresh, keeping the CPU busy with no edits. The daemon directory and its IPC socket inside a linked worktree's gitdir are now neither watched nor reported; real worktree metadata (HEAD, index, refs) still refreshes VCS. The main gitdir's fsmonitor--daemon was already ignored.

Co-authored-by: dengliu <[email protected]>
2026-11-25 09:14:10 +08:00
Vladislav Kuzmin e3f8bd45cf feat(database): manage external TCP tunnels for PostgreSQL (#5670)
PostgreSQL data sources can choose External TCP tunnel in SSH/SSL when a local program provides access to the database. The IDE starts the foreground helper with the configured arguments ({localPort}, {host}, {port}), shares it across the source's connections and stops it on the last disconnect; Test Connection uses a temporary helper. The driver gets a loopback endpoint, so the route stays driver-independent like SSH forwarding.

The executable and arguments run only after a machine-local approval in the desktop dialog, bound to the reviewed settings, the destination and the executable's path and content; a project file alone never starts a program. The helper gets a cleared environment (plus PATH/HOME-style and credential-free proxy variables), its own session or job object, and each forwarded socket is checked for helper ownership. Verify Full is explained as unavailable on this route.

Fixes #5653

Co-authored-by: principalwater <[email protected]>
2026-11-25 08:55:09 +08:00
Fabio Nunes 4f01691ef3 fix(vfs): apply the configured encoding to ASCII files (#4829)
A plain-ASCII file reads the same in any ASCII-compatible encoding, so it was always labelled UTF-8 and the first non-ASCII character typed into it was saved as UTF-8 even when the project or global encoding said otherwise. The configured project/global encoding now labels ASCII files too (decoding is unchanged), through one rule (ide_vfs::Fallback / resolve) shared by the editor, closed-file reads, bounded snapshots, search and VCS revisions. The .properties encoding keeps only decoding non-UTF-8 bytes, so an ASCII .properties file stays UTF-8 by default. An .editorconfig charset now applies to existing ASCII files (judged by their bytes, never relabelling UTF-16) on open, external reload and resource reload as well as to empty files.

Refs #4557

Co-authored-by: LittleGuava <[email protected]>
2026-11-25 08:46:36 +08:00
Delaruno20andDelaruno20 7d4c58a0f1 feat(notebook): fold cells and outputs in the notebook editor (#5650)
A chevron in each cell toolbar folds the cell to one line (its first non-blank line, or a Markdown heading's text) with its output count; clicking the line unfolds it. Code cells with outputs get Hide Output / Show Output, which folds only the outputs, and the notebook toolbar gets Collapse All Cells / Expand All Cells. Fold state is view state on NotebookSession; the .ipynb file is not modified. The singular output counts use their own catalog keys so they don't collide with the run output pane's "{name} output".

Co-authored-by: Delaruno20 <[email protected]>
2026-11-25 08:46:07 +08:00
l0ng-ai f6e51d9214 feat(color-scheme): TypeScript interface, type alias and type parameter colours (#5716)
The JavaScript and TypeScript colour page gets Interface name, Type alias and Type parameter under Classes. tsserver's interface, type and typeParameter semantic tokens carry their own classes, which fall back to the class name colour until set. JS./TS.INTERFACE, TYPE.ALIAS and TYPE_PARAMETER in an imported .icls now land on these entries instead of Class name.

Refs #5619
2026-11-25 08:34:34 +08:00
Mansur Akhmadiandmansur-akhmadi 2f0b0b4ad5 feat(editor): Scroll Up / Scroll Down actions (#5714)
Scroll Up and Scroll Down move the editor by one line without moving the caret or touching the selection and history. Bound to Ctrl+Up / Ctrl+Down in the IntelliJ and VS Code Windows keymaps (unbound on macOS, where IDEA removes them) and mapped from IDEA's EditorScrollUp / EditorScrollDown ids.

Fixes #5713

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-25 08:28:01 +08:00
Mansur Akhmadiandmansur-akhmadi cf33432204 feat(editor): Find Word at Caret / Find Previous Word at Caret (#5712)
Find Word at Caret and Find Previous Word at Caret jump to the next or previous occurrence of the selection, or of the identifier around the caret, without opening the find bar: case-sensitive, not whole words, anywhere in the file, and the query becomes the last search so Find Next continues with it. Bound to Ctrl+F3 / Ctrl+Shift+F3 in the IntelliJ Windows keymap and mapped from IDEA's FindWordAtCaret / FindPrevWordAtCaret ids.

Fixes #5711

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-25 08:27:14 +08:00
Vladislav Kuzminandprincipalwater acad0645d4 fix(database): verify PostgreSQL read-only startup settings (#5693)
A PostgreSQL pooler can reject or silently drop the default_transaction_read_only startup option of a read-only source. The native driver now keeps the pooler's SQLSTATE and message with a hint on what to configure (PgBouncer's track_extra_parameters), checks after login that the default is really on before running the startup script, and after a startup script checks the default again and rejects an open writable transaction. Ordinary connections pay no extra round trips.

Fixes #5686

Co-authored-by: principalwater <+[email protected]>
2026-11-25 08:22:19 +08:00
l0ng-ai 55b710fe53 fix(project): show why a project can't be reopened instead of [object Object] (#5715)
The local trust check called its Tauri commands with the raw invoke, which rejects with the backend's error object, so reopening a recent project whose folder was deleted showed [object Object]. Both local trust commands now go through callDesktop, which raises an IpcError with the backend's message.
2026-11-25 08:20:32 +08:00
l0ng-ai dd4d3325d4 fix(tools): Install on a tool without an installer opens the settings page on that tool (#5710)
Install in the Language Servers popup or an install notification, for a server the IDE can't install itself, opened Settings › Language Servers on the first language, away from the manual install command. It now opens the page on that tool (languages.servers#<tool>).
2026-11-25 07:35:32 +08:00
audichuang 5f437929c0 perf(search): count a long line's window offsets from the previous window (#5698)
A very long line is cut into 500-unit windows around its matches, and each window's UTF-16 text offset was counted from the line start: quadratic in the line length (101 s for a 20 MB line with a frequent term). Each window's offset now adds the UTF-16 length since the previous window's start, falling back to the line start if a window starts earlier. Output is unchanged, checked against the previous windowing on 3,000 random lines; adds an observe-only search_long_line bench.

Co-authored-by: audichuang <[email protected]>
2026-11-25 07:32:14 +08:00
Vladislav Kuzmin f9ed5027c8 test(run): use native paths for the Tomcat deployment context (#5700)
The Tomcat multi-deployment test compared the generated docBase with a path built from mixed separators, so it failed on Windows. Build the expected directory one component at a time and match the full escaped docBase attribute; the file-content check uses the same directory.

Fixes #5699

Co-authored-by: principalwater <[email protected]>
2026-11-25 07:31:26 +08:00
l0ng-ai 9cd1f45b35 fix(editor): read XAML's alpha-first hex colors in the color preview (#5709)
XAML writes hex colors alpha first (#AARRGGBB, #ARGB); in .axaml files the color gutter read them as CSS's #RRGGBBAA and showed the wrong swatch. The swatch, the picker's starting value and the written-back color now use the alpha-first order in Avalonia XAML; other languages keep CSS's order.
2026-11-25 07:30:54 +08:00
l0ng-ai 26e7847457 feat(languages): Avalonia XAML (.axaml) as its own language with an Avalonia language server (#5708)
.axaml files opened as plain XML. They are now the Avalonia XAML language: XML grammar, highlighting, folding and outline as before, XAML's 4-space indent, Surround With tag, and the axsg-lsp language server (installed by hand as a prerelease dotnet tool; the Language Servers page shows the command and takes a custom path), with LemMinX as the XML fallback. .xaml stays XML.

Fixes #5664
2026-11-25 07:28:42 +08:00
audichuang 0a146e4ac9 perf(run): mark the console scenario's sequential awaits as intentional (#5707)
The consoleLongLines perf scenario and the sample console stream await one wheel step, scroll position or output batch per frame on purpose; mark those awaits so no-await-in-loop no longer fails lint on main.

Co-authored-by: audichuang <[email protected]>
2026-11-25 07:21:42 +08:00
l0ng-ai cd42a59c01 fix(run): run shell scripts in a terminal by default (#5706)
Shell scripts ran on pipes with no TTY, so `read` prompts, `[ -t 0 ]` checks and `tput` did not behave as in a shell, and remote SSH runs got no PTY or TERM at all. New Shell Script run configurations and shell scripts run from the editor (by extension or by their #! line) now run in a terminal. A run configuration template still decides the default for new configurations.

Fixes #5624
2026-11-25 07:20:10 +08:00
Mansur Akhmadiandmansur-akhmadi a37e837043 feat(editor): editor appearance switches as View toggle actions (#5704)
Show Line Numbers, Show Indent Guides, Show Sticky Lines and Show Whitespaces are now View toggle actions (editor.toggleLineNumbers / toggleIndentGuides / toggleStickyLines / toggleWhitespaces): runnable from Find Action with their ON/OFF state and bindable to a key, writing the same global settings as the gutter's Appearance menu and Settings. IDEA's EditorGutterToggleGlobalLineNumbers / IndentLines / StickyLines map to them. The gutter's Appearance menu gains Show Sticky Lines and builds its items from the same table.

Closes #5703

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-25 07:10:00 +08:00
Mansur Akhmadiandmansur-akhmadi 08444a4187 feat(editor): Convert Indents to Spaces / to Tabs actions (#5702)
Adds IDEA's Convert Indents to Spaces and Convert Indents to Tabs (code.convertIndentsToSpaces / code.convertIndentsToTabs, Edit category, no default shortcut). They rewrite only the leading whitespace of the selected lines, or of the whole file without a selection, measured in columns with the editor's tab size; To Tabs keeps the columns short of the next tab stop as spaces. ConvertIndentsToSpaces / ConvertIndentsToTabs from imported IDEA keymaps and IdeaVim :action now resolve.

Closes #5701

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-25 07:08:25 +08:00
audichuang 6cc0a877be fix(templates): count packages from Gradle-synced and Eclipse source roots (#5688)
New Java and Kotlin classes got the wrong package line (and New offered Directory instead of Package) in JVM source roots whose marker the build-file pattern didn't recognise: source sets a Gradle sync reports (marker Gradle, e.g. src/gen) and Eclipse .classpath source folders. The pattern in templates/files/create.ts and project-tree/packages.ts now accepts both markers.

Co-authored-by: audichuang <[email protected]>
2026-11-25 07:07:22 +08:00
audichuang ed66588b0d fix(i18n): show branch, repository and module names as written in pickers (#5690)
In the Chinese UI a branch, repository folder or module named dev or test showed as 开发 / 测试, because Select looks option labels up in the text catalog. The remaining pickers with detected names now mark their options verbatim: the Branches popup's multi-repository headers, the Rebase dialog's branches, Stashes and Apply Patch repositories, the new agent task's project and base branch, Find in Files modules, Execute Gradle/Maven Task projects, the Dependency Analyzer module, and run configuration selects that load their options.

Co-authored-by: audichuang <[email protected]>
2026-11-25 07:07:16 +08:00
audichuang e1d3eca189 perf(project-tree): find the top-level selected paths in linear time (#5695)
Copy, Cut, Delete, Move and drag and drop in the Project view went through topLevelPaths, which compared every selected path with every other one: with 10,000 selected files ⌘C and Delete blocked the UI for about 2-3 s. outermostPaths looks each path's parent folders up in a map of the selected paths instead, once per folder, and returns the same paths in the same order (checked against the pairwise filter on random path sets with mixed separators, drive letters and UNC roots). The Delete dialog's file and folder counts use a set. Adds a projectTreeSelection perf scenario.

Co-authored-by: audichuang <[email protected]>
2026-11-25 07:05:05 +08:00
faysouandfaysou 50e6f242ec feat(plugins): let interactive components choose a file on the project host (#5655)
API 1.16 adds ui.pick-file (host::pick_file in the SDK): during an interactive command or view event a component can choose an existing file or a save destination, with a title, a suggested name and extension filters. It returns an absolute path on the project host, or none when dismissed. It uses the same prompt routing and path validation as pick-directory: the native dialog locally and the project host's chooser in remote windows. Choosing a file grants no capability; the component uses the file through the grants it already has.

The suggested name is reduced to a file name, so the dialog never starts in a directory the plugin names, and filters are capped and clipped like other prompt text. Checked-in plugin components are rebuilt for the WIT change.

Co-authored-by: faysou <[email protected]>
2026-11-25 06:59:08 +08:00
Vadim LazukandInf1mum 5567aff80a feat(database): preview the console's execution range with a border (#5694)
A console now borders the SQL an Execute would submit: the caret's statement, or the selected statements, using the same db_statements split the run makes, so what is shown and what is submitted cannot differ. While a run is in progress its submitted range stays bordered as the caret moves. The selection is never changed.

The border is one box around each statement's text, drawn on an editor layer, in the accent colour with a soft fill (light and dark themes). Typing waits for a 150 ms pause before splitting again; caret moves update at once.

Closes #5524

Co-authored-by: Inf1mum <[email protected]>
2026-11-25 06:32:30 +08:00
Mansur Akhmadiandmansur-akhmadi fedd5ffd4f feat(editor): Fill Paragraph action (#5681)
Edit › Fill Paragraph (code.fillParagraph, IDEA's FillParagraph) re-wraps the comment or plain-text paragraph at the caret to the hard wrap column: a run of line comments with the same marker, the * lines of a block comment up to a blank line or @tag, or non-blank lines of a plain text file. Code, string literals and read-only editors are left alone. No default shortcut, as in IDEA.

Closes #5680

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-25 06:26:46 +08:00
audichuang f16cfb507b perf(run): detect console links in linear time (#5649)
The path and JVM-frame patterns in findOutputLinks were unanchored, so on a line without a match they rescanned to the end from every start position: quadratic in the line length. Streaming 1,000 lines of 10 KiB into the Run console took 37.6 s with frames up to 1 s; the Build and Debug consoles share the same detection.

Each matcher now anchors on a fixed delimiter or extension suffix and walks the path back from there, so detection is linear, and the overlap check becomes a cursor. The links found are unchanged (compared with the previous findOutputLinks on 400,000 generated lines). Adds a consoleLongLines perf scenario.

Co-authored-by: audichuang <[email protected]>
2026-11-25 06:24:45 +08:00
Mansur Akhmadiandmansur-akhmadi 80459bae37 fix(keymap): list the Remove All Breakpoints actions in the keymap presets (#5687)
debug.removeAllBreakpoints and debug.removeAllBreakpointsInFile (added in #5675) were missing from the keymap presets, so the vim :action ids test failed on main. Both have no default shortcut in IDEA; they are listed with [] in intellij-macos, intellij-windows and vscode-macos.

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-25 06:22:10 +08:00
l0ng-ai 6cc82bd48e fix(java): tell the user when jdtls fails to sync a Gradle project (#5697)
When Buildship can't sync a Gradle build (a broken build script, a missing
toolchain, an init script error), jdtls only logs "Synchronize project X failed
due to an error connecting to the Gradle build." below error level. The import
failed silently: every Java file showed unresolved JDK types and nothing in the
UI said why.

That log now raises a "Gradle project sync failed" notification, once per
project and cause, with the deepest "Caused by" of the stack trace as the
reason. A sync that failed on an incompatible JDK is left to jdtls' following
"Can't use Java ... to import Gradle project ..." message, which already has its
own notification with Choose Gradle JVM / Download JDK, so the notification
waits briefly for it instead of showing both.

Refs #5669

Tested: ide-lsp unit tests for the log parsing (real Buildship logs) and a mock-server test for the once-only notification and the incompatible-JDK hand-off; ide-lsp clippy; locale catalog tests.
2026-11-25 06:21:07 +08:00
l0ng-ai e5c9e84c83 feat(editor): find a Vue component's usages from Code Vision and Find Usages on the file (#5696)
A .vue file now shows a "Show component usages" Code Vision entry at the top, and
Find Usages on a file in the project tree lists where it is used, not just
nothing.

The file's imports come from tsserver's fileReferences request (sent through
vtsls' typescript.tsserverRequest by the new lsp_file_references command). For a
.vue component, the default import binding at each import is then searched with
textDocument/references, so template tags like <Hello> and calls like
app.component('Hello', Hello) are listed too; the binding's own import line is
not repeated. Safe Delete on a file reuses the same search.

Vue files need vue-language-server installed for tsserver to resolve them.

Fixes #5603
2026-11-25 06:14:33 +08:00
l0ng-ai 5cae7ac316 feat(run): deploy several artifacts from one Tomcat run configuration (#5692)
The Deployment tab's "Deploy at the server startup" list now holds any
number of WAR artifacts, WAR files and exploded directories. + adds to
the list instead of replacing the deployment, − removes the selected
one, and the arrows reorder. Application context and context descriptor
edit the selected deployment, and a context path that two deployments
share is flagged.

The first deployment stays in the configuration's own fields, so
existing configurations work unchanged. The others are stored as a list
in `extraDeployments`. On launch, each deployment is exploded into its
own state directory (`deployments/<n>` below the runtime base) and gets
its own `conf/Catalina/localhost/<context>.xml`. A context used twice is
refused. Before launch builds every out-of-date WAR. Update actions
(resources, classes, redeploy) and the post-build class sync cover all
deployments.

Fixes #5607
2026-11-25 05:55:05 +08:00
l0ng-ai 5e3499026e feat(database): configurable keyword and identifier case for SQL Reformat Code (#5689)
Code Style › SQL gets a Case tab with Keywords and Identifiers, each To
upper / To lower / Do not change. Reformat Code applies them to every SQL
file and query console, bound to a data source or not. Keywords default to
upper case and identifiers stay as written.

Keywords are the dialect's reserved words, clause, join and predicate words
plus common DDL words, except where they are part of a qualified name
(`t.key`). Identifiers are unquoted names only. Quoted names, bind parameters
(`:name`, `@name`) and ClickHouse names, which are case-sensitive, keep
their case.

Fixes #5605
2026-11-25 05:44:48 +08:00
l0ng-ai 6cd463e9c1 feat(welcome): change any project's colour and icon from the project widget and Welcome screen (#5685)
Projects can show a custom icon instead of the coloured initials: an SVG or
PNG in `.openidea/icon.*` (or IntelliJ's `.idea/icon.*`, with `icon_dark.*`
used in dark themes). Change Project Icon… copies the chosen image there and
Reset Project Icon removes it.

The project context menu in the title bar project widget and on the Welcome
screen now offers Change Project Color…, Change Project Icon… and Reset
Project Icon for open projects as well as recent ones; the colour picker is
a workbench overlay so it opens from any of these places.

Fixes #5613
2026-11-25 05:36:17 +08:00
l0ng-ai 089b914c96 fix(agents): fit the session status strip to a narrow session (#5684)
In a narrow docked session the strip under the composer truncated nearly every item. It now gives way in steps: below 560px the provider shows its icon and the change/commit chips their count; below 420px a local task's branch and the task state (except a usage limit) are left out, keeping the changes and meters. Tooltips and accessible names keep the full text.

Fixes #5614
2026-11-25 05:22:07 +08:00
l0ng-ai 2523e17cbd feat(editor): colour JavaScript and TypeScript methods apart from functions (#5683)
tsserver's method/member tokens were mapped to the plain function class. Methods now also get an instance- or static-method class, with Identifiers › Instance method and Static method on the JavaScript and TypeScript colour scheme page; unset, they keep the function declaration/call styles so existing themes look the same. JetBrains scheme import maps INSTANCE_MEMBER_FUNCTION and STATIC_MEMBER_FUNCTION to them.

Fixes #5623
2026-11-25 05:13:27 +08:00
l0ng-ai 966e4cd03c feat(toolbar): add a Center group to Customize Main Toolbar (#5682)
Customize Main Toolbar now has Left, Center and Right groups (appearance.mainToolbar.center, empty by default). The Center group is centred on the whole title bar when the other groups leave room, otherwise pushed against the group it would overlap, as IDEA's main toolbar lays it out.

Fixes #5612
2026-11-25 05:06:00 +08:00
l0ng-ai 4fa84461ef feat(vcs): add a Git Branch status bar widget (#5679)
A Git Branch widget can now be switched on from the status bar's context menu (off by default). It shows the same branch label and incoming/outgoing markers as the toolbar widget, and a click opens Git Branches anchored above it. The popup state records which widget opened it, so each widget shows its own expanded state.

Fixes #5610
2026-11-25 04:57:31 +08:00
l0ng-ai d269570f72 feat(database): freeze the result grid's row numbers and add rows with ⌘/Ctrl-click (#5678)
The row-number column scrolled away with the data when a wide result was scrolled sideways. It is now sticky at the left edge (header included) and drawn above the cells passing under it.

Row numbers also select like a row header: ⌘/Ctrl-click adds or removes a row, Shift-click extends the lead range, dragging down the numbers selects whole rows. Copy, Copy Rows, the row context menu and the Aggregates panel use every selected row.

Fixes #5527
2026-11-25 04:51:37 +08:00
Vladislav Kuzmin 3927e70476 fix(run): scope JVM thread-dump test helpers to Unix (#5672)
The thread-dump tests' helpers in ide-jvm-attach and ide-host use Unix-only APIs, so the Windows test build failed to compile on main. Gate the helpers and the tests that use them to Unix.

Closes #5671

Co-authored-by: principalwater <[email protected]>
2026-11-25 04:43:07 +08:00
l0ng-ai af3e174702 fix(java): apply the Eclipse plugin to the project in the Gradle classpath init script (#5677)
Inside the Gradle classpath init script's closures a bare `apply plugin: 'eclipse'` resolves to the init script's own apply. On Gradle 7 the Eclipse plugin then can't get its project services (no IdeArtifactRegistry), applying java fails, and jdtls's Gradle import fails for every Gradle 7 project, leaving all Java files red. The script now calls project.apply; a test keeps bare apply calls out of it.

Fixes #5669
2026-11-25 04:37:46 +08:00
Mansur Akhmadiandmansur-akhmadi 7532ff30fd feat(debugger): Remove All Breakpoints In The Current File action (#5675)
Remove All Breakpoints In The Current File (Debugger.RemoveAllBreakpointsInFile) removes the line breakpoints of the file in the active editor, plus the method breakpoints and field watchpoints whose gutter icon is in that file; other files, name-only method breakpoints and exception breakpoints stay. It is in Find Action with no default shortcut. Imported IDEA keymaps and IdeaVim :action now map Debugger.RemoveAllBreakpoints and Debugger.RemoveAllBreakpointsInFile.

Closes #5674

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-25 04:03:10 +08:00
l0ng-ai 675e1ccd61 fix(editor): show hovers on the first lines while the caret is further down (#5676)
The sticky-scroll top scroll margin reserved the caret's enclosing header rows at all times. CodeMirror also treats that margin as covered when placing tooltips, so with the caret inside a method every hover on the first lines of a file (quick documentation, plugin decoration cards) was parked off screen though no sticky rows were showing. The caret's rows are now reserved only while the caret sits above where they would stick, which is when revealing it scrolls them in; otherwise the margin is the rows showing now.
2026-11-25 03:59:40 +08:00
Charlie.Weiandcharli117 00f482a7cc feat(plugins): Markdown hover cards for editor decorations (API 1.16) (#2622)
decorations.set-markdown (API 1.16) draws the same line-end labels as decorations.set and shows each item's markdown_hover as a hover card on the label or the decorated text. The card renders through the shared Markdown path (marked + DOMPurify, media and resource attributes stripped), uses the editor's hover styling, can be resized from its edges, and closes on Escape, an outside click, window blur or leaving the window. Set ids, the 10,000-item and 4 MiB limits and clear are shared with set. SDK: host::set_markdown_decorations and MarkdownDecoration, with a decorations fixture plugin.

Co-authored-by: charli117 <[email protected]>
2026-11-25 03:57:00 +08:00
Akbar Husain 6269c4e1e6 perf(run-db): resolve no-await-in-loop in run and database (#5673)
Enables oxlint's no-await-in-loop for src/features/run and src/features/database. Every await that stays sequential there carries the reason: launch tasks and derived tests run in order, debugger roots detach in order before the last one stops the shared process, retry loops classify each failure before the next attempt, credential and trust prompts must not stack, and schema introspection checks cancellation per schema. Tests that press keys and assert in sequence are annotated the same way. No behaviour changes.

Co-authored-by: akbar1214 <[email protected]>
2026-11-25 03:45:30 +08:00
faysouandfaysou 46b3a0bbc9 feat(plugins): support ranged reads in binary web editors (#4914)
A web custom editor declared with `binary = true` (API 1.16, web page with `layout = "tab"`) opens a file without creating a text document. Its page reads the file's size with `document.size()` and byte ranges of at most 1 MiB with `document.readRange(offset, length)`, so large binary formats such as Parquet can be read piece by piece. The path is always the editor's own file, never one the page supplies, and messages from the page to the plugin's code carry that file as the editor context.

The manifest field is rejected below API 1.16 and only allowed on tab-layout web editors; the docs and the API 1.16 notes list the new bridge methods.

Co-authored-by: faysou <[email protected]>
2026-11-25 03:40:24 +08:00
Akbar Husain f944a51e5a perf(editor): parallelize independent awaits and suppress intentional ones (#5652)
Independent awaits in the editor now run together, and the awaits that must stay sequential carry an explained no-await-in-loop suppression.

- Implementation and override gutter markers: base resolution, subclass outlines, super-method lookups and per-owner hierarchy walks run in parallel; results are merged in the original order, and outline/hierarchy requests stay deduplicated per pass.
- Inheritance graph and super-method walks resolve all bases of one level together; levels stay sequential.
- Introduce Variable verifies up to 30 occurrences in parallel; format requests for several ranges run together and edits are applied in range order.
- Python abstract members, Python hierarchy outlines, completion sources and embedded-document shutdown run in parallel, keeping declaration/source order.
- Budgeted walks, cancellation checks, ordered marker batches and Safe Delete's per-symbol search stay sequential.

Co-authored-by: akbar1214 <[email protected]>
2026-11-25 03:32:16 +08:00
Akbar Husain f943eee851 perf(vcs): resolve no-await-in-loop across VCS operations (#5657)
Clears the no-await-in-loop diagnostics under src/features/vcs. Pending-patch reads of the selected repositories now run in parallel (order kept); Git command sequences, confirmation and retry loops, cancellation checks and ordered UI or store updates stay sequential with narrow documented suppressions. The rule is enabled as an error for the VCS scope, next to evals, perf and smoke.

Co-authored-by: akbar1214 <[email protected]>
2026-11-25 03:27:12 +08:00
Akbar Husain 40379cdc91 perf(tooling): resolve no-await-in-loop in perf, evals and smoke (#5663)
Every no-await-in-loop diagnostic in evals/, perf/ and smoke/ is an intentionally sequential loop (measured inputs and frame pacing, shared editor and browser state, chained DAP requests, session and process lifecycle), so each gets a narrow documented suppression, and the rule is enabled as an error for those three directories so new ones are caught.

Co-authored-by: akbar1214 <[email protected]>
2026-11-25 02:53:34 +08:00
faysouandfaysou 1ad9189861 feat(editor): configure sticky lines by language (#5263)
Settings › Editor › General › Sticky Lines gains "Show sticky lines for:", a checkbox per language under the maximum line count. The editor stores the unchecked language ids with the line count; an editor of an unchecked language drops the sticky lines extension and its scroll margin, so Find and Go to Line use the full height. Applying the setting reconfigures open editors.

Co-authored-by: faysou <[email protected]>
2026-11-25 02:52:06 +08:00
Vadim LazukandInf1mum fba210e22d feat(php): devsense-php-ls as a selectable PHP language server (#5658)
DEVSENSE PHP Tools (devsense-php-ls) is one more selectable PHP language server in Settings › Languages & Frameworks › Language Servers, after Phoxite; Intelephense stays the default. Its engine is native (only the npm launcher needs Node), and while it serves it replaces laravel-lsp, as it answers the Laravel strings itself. Docs note which features need a DEVSENSE licence. A managed install can follow.

Fixes #5496

Co-authored-by: Inf1mum <[email protected]>
2026-11-25 02:37:03 +08:00
Vadim LazukandInf1mum 40c8e83084 feat(editor): cycle an identifier between snake, kebab, camel and Pascal case (#5666)
Code › Cycle Identifier Case (Shift+Alt+U in the IntelliJ keymaps; Find Action under camel, snake, kebab, Pascal) converts the identifier at each caret, which stays selected, or each selection to the next style: snake_case → SCREAMING_SNAKE_CASE → kebab-case → camelCase → PascalCase. The current style is read from the text; words split at separators, case changes and the end of an acronym; a single word goes name → Name → NAME, and a style that would write the text the same way is skipped.

Fixes #5615

Co-authored-by: Inf1mum <[email protected]>
2026-11-25 02:35:15 +08:00
Vadim LazukandInf1mum c6ea0ddab1 feat(welcome): Shift or Ctrl+click opens a recent project in a new window (#5667)
In the recent project lists (title bar project popup, Welcome screen, File › Open Recent), Shift+click or Ctrl+click (also ⌘+click on macOS) opens the project in a new window and Alt+click in this one, whatever "Open project in" says; Enter takes the same modifier keys. Local and SSH/WSL projects alike. A plain click or Enter is unchanged, and rows under Open Projects still switch to their window.

Fixes #5598

Co-authored-by: Inf1mum <[email protected]>
2026-11-25 02:31:53 +08:00
Mansur Akhmadiandmansur-akhmadi c3d1ba28fd feat(editor): Duplicate Entire Lines action (#5661)
Code › Duplicate Entire Lines (EditorDuplicateLines, no default shortcut, as in IDEA) copies every line a caret or selection touches below itself, even when only part of a line is selected, and moves the selection onto the copy. On a folded region's line it copies the folded block, as Duplicate Line or Selection does; that path now maps selections as well as carets onto the copy. Imported IDEA keymaps and IdeaVim :action map EditorDuplicateLines to it.

Fixes #5660

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-25 02:29:00 +08:00
l0ng-ai 75781a5731 fix(project): rename the type of a copied Java file to the copy's name (#5668)
Copying a .java file kept the type under its old name, so the copy failed to compile, and the default name "Foo copy.java" could never be a type name. A Java source now gets a default copy name its type can take (FooCopy.java, FooCopy2.java), and a copy under a new name renames the top-level type in it: its declaration, constructors and the copy's own references, not strings, comments or same-named members. Applies to Copy (F5) and to copy and paste in the Project view.

Fixes #5647
2026-11-25 02:25:17 +08:00
Vadim LazukandInf1mum 63f2f0280d fix(run): launch a Gradle-delegated run on the project's Java toolchain (#5656)
Build and run using Gradle started the main class on Gradle's own JVM: the openideaRun JavaExec task never set javaLauncher, and before Gradle 9 JavaExec does not default to the project's toolchain. With a toolchain newer than Gradle's JVM the class failed with UnsupportedClassVersionError. On Gradle 6.7+ the task now launches on the project's Java toolchain, as the application plugin's run does; a project without a toolchain still runs on Gradle's JVM.

Fixes #5594

Co-authored-by: Inf1mum <[email protected]>
2026-11-25 02:19:25 +08:00
faysouandfaysou cd3399df60 fix(vcs): keep selection history in the editor Git menu (#5654)
The shared Git submenu (#5611) dropped Show History for Selection from the editor's context menu. It is back for a right-click in the editor and stays out of the tab and Project view menus. The browser tests now use the shared menu's labels and groups, including keyboard navigation to Get from Version Control….

Co-authored-by: faysou <[email protected]>
2026-11-25 02:17:58 +08:00
faysouandfaysou fc4e4fa39a fix(markdown): keep large previews responsive when scrolling and switching tabs (#5249)
Fast scrolling could leave either pane of a Markdown split blank, and large previews were rebuilt on every tab switch.

- The source draws newly visible lines before painting a large scroll jump; the preview follows wrapped lines and table rows, handles trackpad gestures from their first wheel event, and updates its position while the scrollbar thumb is dragged (the Git log's scrollbar, resized as content grows).
- Recent Markdown tabs stay mounted while hidden (text editor wrappers can now opt into keepAlive); the hidden source view is detached as before and the preview is moved off screen on its own layer.
- Edits reuse unchanged equation and Mermaid SVGs, including diagrams with math labels; changing a TeX macro refreshes the equations that use it.
- Long embedded image payloads are folded in the source, and the Markdown parser skips the payload bytes of standalone images.

On a 5.85 MB document in WebKit, first open went from 22.9 s to 3.25 s and returning to the tab from 14.4 s to 0.24 s.

Co-authored-by: faysou <[email protected]>
2026-11-25 02:17:02 +08:00
faysouandfaysou 13e27f0133 fix(editor): calculate sticky scroll margins from the visible folded line (#5662)
The sticky-lines top margin used when scrolling the caret into view counted the headers enclosing the caret's source line, including headers a fold had hidden. Inside a folded block in a narrow split the extra rows made CodeMirror treat the visible fold placeholder as clipped and push the folded-code tooltip out of the viewport. The margin now starts from the caret's displayed line block, so outer scopes still count and unfolding restores the full margin.

Co-authored-by: faysou <[email protected]>
2026-11-25 02:09:48 +08:00
LU XIANGRUIandwildcatDownstairs f028109518 fix(java): colour unterminated string and char literals to the end of the line (#5566)
An unterminated Java string or char literal (`String s = "abc;`, `char c = 'a;`) is string-coloured up to the closing quote or the end of the line, as the IntelliJ lexer ends such a literal. @lezer/java has no token for it: error recovery leaves the quote as a one-character error node and parses the rest of the line as code. The new scan finds those error nodes, skips escaped quotes, and composes with the contextual-keyword and escape ranges in Java's syntaxRanges; nested spans inside the literal take the string colour. Unterminated text blocks already run to the end of the file and are unchanged.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-25 02:08:13 +08:00
ntbang0901 8492dc530a feat(run): Dump Threads for JVM run and debug sessions, with deadlocks (#5595)
Run › Dump Threads (Run tool window toolbar, for running Java applications, JAR applications, Gradle bootRun and Maven run goals) and Debug › Dump Threads (debugger toolbar menu) take a `Thread.print -l` of the JVM and open it in a thread viewer tab of the Run tool window: threads grouped by state with a filter and a toggle to hide JVM-internal threads, the selected thread's stack with navigable frames, deadlocks shown as a banner with the threads marked, and Refresh to take the next dump into the same tab.

- The run's JVM is the deepest HotSpot JVM of the run's process tree; Gradle runs, whose JVM forks under the daemon, are found by a stable -Dopenidea.run.token property instead, skipping Gradle's own JVMs.
- The attach listener is started only for a confirmed HotSpot JVM: the trigger file is private and created exclusively, a foreign socket is refused, and OpenJ9 is never sent SIGQUIT.
- A JVM a debugger holds suspended is dumped only when its listener is already open and the JDK is 17 or later; a debugged run's dump goes through its debug session, and Attach to Process links the session to the run.
- Remote runs, exited programs and JVMs with the attach mechanism disabled report why no dump was taken.
- The Run tool window comes forward when a dump opens, including one taken from the debugger.

Co-authored-by: ntbang0901 <[email protected]>
2026-11-25 02:01:59 +08:00
Floandflobo3 8bc7fd76be feat(i18n): add Russian (ru) UI language (#5626)
Russian joins the UI languages in Settings › Appearance & Behavior › System Settings › Language and Region and in the first-launch OS language detection, with the UI keys (Russian plural forms one / few / many / other) and the source-text catalog. Text not yet translated shows in English.

Co-authored-by: flobo3 <[email protected]>
2026-11-25 01:38:09 +08:00
l0ng-ai e8ac5d7bc2 test(i18n): allow the HotSwap section name to stay untranslated (#5665)
The Debugger settings page names its HotSwap section "HotSwap" in Chinese, as the existing HotSwap notification title is; the catalog test now lists it among the names kept in English, so it passes again on main.
2026-11-25 01:26:24 +08:00
l0ng-ai 12712253a8 fix(agents): let an open tool run grow instead of scrolling inside the chat (#5651)
Expanding a run such as "Ran 8 commands" showed its steps in a box capped at 16 rows with its own scrollbar. The run now lays out every step and scrolls with the conversation; a single tool call's output keeps its own 240px scroll area. The run's own follow-the-latest-call scrolling goes with its scroll area; the conversation's follow-to-end covers live runs.
2026-11-25 01:22:47 +08:00
RuyimgByCN b3e4bd63f1 feat(debug): reload classes after Recompile and builds, and sync exploded Tomcat deployments (#5601)
Settings › Build, Execution, Deployment › Debugger › HotSwap › Reload classes after compilation (Ask by default, Always, Never) decides what happens after a successful Build Project, Build Module or Recompile of a Java project while a debug session supports hot code replace: Ask offers "Reload '<file>.java' into the running debug session?", Always reloads at once, Never stays silent. The same setting applies to the language server's build-complete event, and overlapping prompts within two seconds are merged. After a single-file Recompile, classes that compiled cleanly are reloaded even if another file of the module still has errors.

Build completion is published as onBuildCompleted in contributions, and a running Tomcat with an exploded artifact deployment syncs its outputs after such a build (silently while it is debugged).

Co-authored-by: RuyimgByCN <[email protected]>
2026-11-25 01:20:59 +08:00
RuyimgByCN 748e5cee89 feat(build): add Build › Recompile for a single Java file (#5587)
Build › Recompile '<file>.java' (Shift+Cmd+F9 / Ctrl+Shift+F9, moved from Build Module, which keeps no default shortcut) compiles only the active Java file with javac and streams its output and diagnostics to the Build tool window. The menu, editor, tab and Project view entries name the file and are enabled only for local .java files.

- Maven modules resolve the classpath of the file's scope (compile for main sources, test for test sources) through dependency:build-classpath; the probe is now cancellable.
- Gradle projects get the source set's output, compile classpath, source folders and release from an init script.
- Projects without a build tool compile against their Project Structure roots, outputs and libraries.
- In a workspace the file's member project is used.
- javac gets -g, omits an empty -cp, and uses -source/-target on JDK 8; localized javac error and warning prefixes are parsed.

Co-authored-by: RuyimgByCN <[email protected]>
2026-11-25 00:59:59 +08:00
l0ng-ai d729ae8122 fix(search): keep multiline result names in one row (#5641)
Search Everywhere drew a result name containing line breaks over the rows below it, since names used white-space: pre in a fixed-height list. Names now stay on one line (line breaks collapse to spaces); code snippets keep white-space: pre for their indentation and tab stops.
2026-11-25 00:47:10 +08:00
l0ng-ai 503ed3b9bb fix(search): keep background scans off huge files and bound a search's line buffer (#5659)
The TODO index scans the whole project when it opens and rescans changed files, through the
Find in Files engine. That engine read a file line by line with no limit on a line's length, so a
database dump or bundle without line breaks was read whole into memory (a 2 GB single-line .sql
took the backend to 2.6 GB on every change) and searched in quadratic time, and every other large
file (logs, dumps) was read in full on each scan.

- Background scans (the TODO index, the files a usage search checks, the word candidates of a
  reference search) now leave out files over 2,500 KB, the code insight limit that IDEA's TODO and
  word indexes use (`idea.max.intellisense.filesize`).
- Every search caps its line buffer at 20 MB, IDEA's content-load limit: a longer line (or file,
  in a multi-line search) is not searched further instead of being read whole.

Fixes #5390
2026-11-25 00:45:06 +08:00
faysouandfaysou 1dd213964d test(boot): allow the workbench to mount within the startup deadline (#5636)
The slow-start boot test waited for the workbench's first render with Playwright's 10-second default, while OpenIDEA allows startup 60 seconds, so it failed on CI when Chromium was still loading the workbench. The test now runs with a 60-second timeout and uses it for that wait; it still advances the clock past the startup deadline and checks that the failure screen never appears.

Co-authored-by: faysou <[email protected]>
2026-11-25 00:12:31 +08:00
RuyimgByCN 5636fc0ecd fix(vcs): show declaration icons in the Commit changes tree (#5642)
The Commit tool window, the Commit dialog and the Local Changes tab resolved every file's icon from its name, so Java files showed the generic coffee cup instead of the class, interface, enum, test or Spring icons the Project tree and editor tabs show. Working-tree rows (and non-deleted amend preview rows) now take their icon from the shared file presentation cache; deleted files, added-then-deleted entries and ignored directories keep their file-type or folder icons.

Co-authored-by: RuyimgByCN <[email protected]>
2026-11-25 00:07:23 +08:00
Ilija Popivanov 5f64cce2a4 fix(editor): prevent paste when middle-click closes a tab (#5645)
On Linux, middle-clicking a tab could paste the primary selection into the editor that took focus: the shared tab strip closed the tab on mouse-down, so WebKitGTK delivered the release to the newly focused editor, which pasted. Tabs now close on the matching middle-button release, after cancelling its default action, and only when the button is released over the tab it was pressed on. This covers editor, tool window, database result and plugin tabs, which all use the shared strip.

Co-authored-by: ilijapopivanov <[email protected]>
2026-11-25 00:07:18 +08:00
Yann 4101e9d185 feat(deployment): upload files and folders directly into Remote Host (#5606)
Remote Host could only receive files through deployment mappings. Files and folders can now be dragged into it from the Project view or the desktop file manager, with the destination folder highlighted, and its context menu offers Upload Files… and Upload Folder…. Uploads go into the chosen folder without mappings or exclusion rules, keep each source's name, and ask before replacing files or merging folders.

Replacing a file uploads to a temporary name first and keeps the old file until the new one has its final name. Symbolic links and special files are skipped, transfers can be cancelled, and the affected listings are refreshed afterwards. Desktop drops are refused in Remote Development windows.

Co-authored-by: YannABC <[email protected]>
2026-11-24 23:59:44 +08:00
LU XIANGRUIandwildcatDownstairs a3ca576edd feat(editor): generate __init__ and properties in Python classes (#5354)
Generate (Cmd+N / Alt+Insert) in a Python class now also offers Constructor (__init__)… and Property…. The constructor takes the class fields chosen in a member chooser (fields with a value last, keeping it as the default) and is inserted before the first method; classes that get __init__ elsewhere (dataclasses, attrs, enums, named tuples, typed dicts, pydantic models) and classes that already define one get a hint instead. Property… offers class fields and attributes assigned on self, and writes a getter and setter over the private attribute, renaming a public class field to its private name so its value is kept.

Field values are read outside strings and comments, values spanning lines are skipped, and a one-line class body is split before inserting.

Closes #5329

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-24 23:51:43 +08:00
LU XIANGRUIandwildcatDownstairs 8b4e1e71fb feat(editor): Override Methods and Generate entries for Python classes (#5353)
Python classes had Implement Methods but no Override Methods or Generate. Override Methods (Ctrl+O) now opens a member chooser ("Select Methods to Override", grouped by declaring class) when the language server offers no code action, and Generate (Cmd+N / Alt+Insert) lists Override Methods and Implement Methods in Python editors.

The overridable methods follow the class's C3 linearization: for each name only the first definition in MRO order is offered, so the copied signature matches what super() calls; a @final, overload-only or name-mangled first definition hides the name. Class headers spanning several lines are read up to their closing colon, and inserting into a one-line class body (class C(Base): pass) splits it first. Overrides of one-line, static and non-ASCII methods are generated correctly, and missing imports for annotations are added.

Closes #5328

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-24 23:49:11 +08:00
LU XIANGRUIandwildcatDownstairs cdfc38231f feat(python): add the 'Method may be static' inspection (#5347)
PyCharm reports instance methods that never use self (PyMethodMayBeStatic); neither basedpyright nor Ruff's default rules do. The Python parser now reports a method's unused receiver (undecorated, not a dunder, a body that does more than pass, ..., a docstring or one raise, never naming the receiver, super or __class__), and a weak-warning inspection in the Python inheritance checks reports it, except for overrides, methods a subclass overrides, classes with an incompletely indexed hierarchy, and test code.

Alt+Enter offers Make method static. It searches the method's usages with the language server's references and applies only when every call goes through an instance (self.m(...), super().m(...)); otherwise it changes nothing, says how many usages may call it through a class and lists them in Find Usages. Suppressible with # noinspection PyMethodMayBeStatic.

Closes #5333

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-24 23:35:44 +08:00
Mr0Bread d18bd6144a refactor: one spawn_blocking helper instead of per-module copies (#5500)
ide-host carried eight private copies of the same blocking helper (spawn on the blocking pool, map a JoinError to IdeError::internal, flatten the closure's IdeResult), five private join_err mappers and about 50 inline spawn_blocking(..).await.map_err(join_err) sites. They now share ops::blocking and ops::blocking_value (for work that cannot fail) next to Host::blocking, which keeps spawning on the host's runtime. Error kind, message and runtime handle stay the same at every site; tests pin the value, error pass-through, panic mapping and runtime for each helper.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-24 23:29:14 +08:00
xiaohuiduanandxiaohuiduan 91cd0c058d feat(plugins): fetch plugin packages through the GitHub mirror prefix (#5492)
The Tools › Download sources GitHub mirror prefix carried language server, debugger and formatter archives but not plugin packages, which come from the same GitHub release host. Install, Update and Update All now try the mirror first and fall back to the official host; a mirror's failure, including bytes that fail the index digest or publisher signature, is that source's failure. The marketplace index itself is not mirrored, since it carries no signature of its own.

Packages are unpacked into a per-attempt staging folder and every exit except a verified one removes it, so nothing a mirror served stays where the install page reads. The app log records which source was tried, why a mirror failed and which one won. The failed-read test no longer depends on the OS's English wording.

Refs #3295

Co-authored-by: xiaohuiduan <[email protected]>
2026-11-24 23:23:07 +08:00
LU XIANGRUIandwildcatDownstairs 3ba9354159 feat(python): search PyPI package names in the Python Packages tool window (#5480)
The Python Packages tool window found a PyPI project only by its exact name, because PyPI has no search API. The first search now downloads PyPI's Simple index (PEP 691 JSON), keeps only the project names in the IDE cache directory, and refreshes them in the background once a day; a failed refresh keeps the old copy.

pypi_search matches names as PyPI normalises them: the exact name first, then names continuing with a separator, then other prefixes, then substrings. 50 results are listed with a note when there are more. The cache is written atomically, the scan honours cancellation, concurrent searches share one download, and an abandoned download stops after 10 seconds without a waiter. With another index configured, search results still wait for "Search PyPI for …".

Closes #5452

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-24 23:15:19 +08:00
Alexis 0eef66d793 feat(plugins): let web views embed declared and granted origins (#5618)
A plugin web view, custom editor or editor panel can list origins in a new frames field (API 1.16). Each origin must be https (or http to a loopback host), name one exact host with no path, and be covered by a net: capability of the manifest, so the install page shows it. Pages under that declaration's directory are served with a frame-src of the declared origins the user granted, and are revalidated instead of cached immutable, so declining or revoking a host takes effect on the next load. Without frames the CSP is unchanged, the plugin page cannot widen it, and the embedded page keeps the frame's sandbox without window.openidea.

Closes #5523

Co-authored-by: Rhombicdodecahedron <[email protected]>
2026-11-24 23:08:23 +08:00
712 changed files with 36909 additions and 2130 deletions

No files matched your search

+15
View File
@@ -0,0 +1,15 @@
{
"detector": {
"ignoreRules": [],
"ignoreFiles": [],
"ignoreValues": [
{
"rule": "gradient-text",
"value": "*",
"files": ["src/features/agents/Session.module.css"],
"createdAt": "2026-11-24T14:58:12.514Z",
"reason": "agent: .shimmer is an animated in-progress sweep on running-step labels (commit 18b286e7e, comment documents intent), not decorative gradient text"
}
]
}
}
+557
View File
@@ -0,0 +1,557 @@
{
"schemaVersion": 2,
"generatedAt": "2026-11-24T15:06:05+00:00",
"title": "Design System: OpenIDEA",
"extensions": {
"colorMeta": {
"workbench-blue": {
"role": "primary",
"displayName": "Workbench Blue",
"canonical": "#3871e1",
"tonalRamp": [
"oklch(15% 0.073 262)",
"oklch(25% 0.121 262)",
"oklch(35% 0.17 262)",
"oklch(48% 0.17 262)",
"oklch(60% 0.17 262)",
"oklch(72% 0.136 262)",
"oklch(84% 0.078 262)",
"oklch(95% 0.024 262)"
]
},
"link-blue": {
"role": "primary",
"displayName": "Link Blue",
"canonical": "#2f5eb9",
"tonalRamp": [
"oklch(15% 0.064 262)",
"oklch(25% 0.107 262)",
"oklch(35% 0.15 262)",
"oklch(48% 0.15 262)",
"oklch(60% 0.15 262)",
"oklch(72% 0.12 262)",
"oklch(84% 0.069 262)",
"oklch(95% 0.021 262)"
]
},
"selection-wash": {
"role": "primary",
"displayName": "Selection Wash",
"canonical": "#d0dffe",
"tonalRamp": [
"oklch(15% 0.034 262)",
"oklch(25% 0.057 262)",
"oklch(35% 0.08 262)",
"oklch(48% 0.08 262)",
"oklch(60% 0.08 262)",
"oklch(72% 0.064 262)",
"oklch(84% 0.037 262)",
"oklch(95% 0.011 262)"
]
},
"tab-wash": {
"role": "primary",
"displayName": "Tab Wash",
"canonical": "#e3ebfe",
"tonalRamp": [
"oklch(15% 0.026 262)",
"oklch(25% 0.043 262)",
"oklch(35% 0.06 262)",
"oklch(48% 0.06 262)",
"oklch(60% 0.06 262)",
"oklch(72% 0.048 262)",
"oklch(84% 0.027 262)",
"oklch(95% 0.009 262)"
]
},
"danger": {
"role": "status",
"displayName": "Danger",
"canonical": "#c54e58",
"tonalRamp": [
"oklch(15% 0.064 18)",
"oklch(25% 0.107 18)",
"oklch(35% 0.15 18)",
"oklch(48% 0.15 18)",
"oklch(60% 0.15 18)",
"oklch(72% 0.12 18)",
"oklch(84% 0.069 18)",
"oklch(95% 0.021 18)"
]
},
"warning": {
"role": "status",
"displayName": "Warning",
"canonical": "#a56906",
"tonalRamp": [
"oklch(15% 0.056 70)",
"oklch(25% 0.093 70)",
"oklch(35% 0.13 70)",
"oklch(48% 0.13 70)",
"oklch(60% 0.13 70)",
"oklch(72% 0.104 70)",
"oklch(84% 0.059 70)",
"oklch(95% 0.019 70)"
]
},
"success": {
"role": "status",
"displayName": "Success",
"canonical": "#338555",
"tonalRamp": [
"oklch(15% 0.047 152)",
"oklch(25% 0.079 152)",
"oklch(35% 0.11 152)",
"oklch(48% 0.11 152)",
"oklch(60% 0.11 152)",
"oklch(72% 0.088 152)",
"oklch(84% 0.05 152)",
"oklch(95% 0.016 152)"
]
},
"frame-grey": {
"role": "neutral",
"displayName": "Frame Grey",
"tonalRamp": [
"oklch(15% 0.005 265)",
"oklch(25% 0.009 265)",
"oklch(35% 0.012 265)",
"oklch(48% 0.012 265)",
"oklch(60% 0.012 265)",
"oklch(72% 0.01 265)",
"oklch(84% 0.005 265)",
"oklch(95% 0.002 265)"
]
},
"island-white": {
"role": "neutral",
"displayName": "Island White",
"tonalRamp": [
"oklch(15% 0.005 265)",
"oklch(25% 0.009 265)",
"oklch(35% 0.012 265)",
"oklch(48% 0.012 265)",
"oklch(60% 0.012 265)",
"oklch(72% 0.01 265)",
"oklch(84% 0.005 265)",
"oklch(95% 0.002 265)"
]
},
"raised-paper": {
"role": "neutral",
"displayName": "Raised Paper",
"tonalRamp": [
"oklch(15% 0.005 265)",
"oklch(25% 0.009 265)",
"oklch(35% 0.012 265)",
"oklch(48% 0.012 265)",
"oklch(60% 0.012 265)",
"oklch(72% 0.01 265)",
"oklch(84% 0.005 265)",
"oklch(95% 0.002 265)"
]
},
"ink": {
"role": "neutral",
"displayName": "Ink",
"tonalRamp": [
"oklch(15% 0.005 265)",
"oklch(25% 0.009 265)",
"oklch(35% 0.012 265)",
"oklch(48% 0.012 265)",
"oklch(60% 0.012 265)",
"oklch(72% 0.01 265)",
"oklch(84% 0.005 265)",
"oklch(95% 0.002 265)"
]
},
"ink-secondary": {
"role": "neutral",
"displayName": "Ink Secondary",
"tonalRamp": [
"oklch(15% 0.005 265)",
"oklch(25% 0.009 265)",
"oklch(35% 0.012 265)",
"oklch(48% 0.012 265)",
"oklch(60% 0.012 265)",
"oklch(72% 0.01 265)",
"oklch(84% 0.005 265)",
"oklch(95% 0.002 265)"
]
},
"ink-muted": {
"role": "neutral",
"displayName": "Ink Muted",
"tonalRamp": [
"oklch(15% 0.005 265)",
"oklch(25% 0.009 265)",
"oklch(35% 0.012 265)",
"oklch(48% 0.012 265)",
"oklch(60% 0.012 265)",
"oklch(72% 0.01 265)",
"oklch(84% 0.005 265)",
"oklch(95% 0.002 265)"
]
},
"ink-faint": {
"role": "neutral",
"displayName": "Ink Faint",
"tonalRamp": [
"oklch(15% 0.005 265)",
"oklch(25% 0.009 265)",
"oklch(35% 0.012 265)",
"oklch(48% 0.012 265)",
"oklch(60% 0.012 265)",
"oklch(72% 0.01 265)",
"oklch(84% 0.005 265)",
"oklch(95% 0.002 265)"
]
},
"hairline": {
"role": "neutral",
"displayName": "Hairline",
"tonalRamp": [
"oklch(15% 0.005 265)",
"oklch(25% 0.009 265)",
"oklch(35% 0.012 265)",
"oklch(48% 0.012 265)",
"oklch(60% 0.012 265)",
"oklch(72% 0.01 265)",
"oklch(84% 0.005 265)",
"oklch(95% 0.002 265)"
]
},
"control-edge": {
"role": "neutral",
"displayName": "Control Edge",
"tonalRamp": [
"oklch(15% 0.005 265)",
"oklch(25% 0.009 265)",
"oklch(35% 0.012 265)",
"oklch(48% 0.012 265)",
"oklch(60% 0.012 265)",
"oklch(72% 0.01 265)",
"oklch(84% 0.005 265)",
"oklch(95% 0.002 265)"
]
},
"frame-grey-dark": {
"role": "neutral",
"displayName": "Frame Grey (Dark)",
"tonalRamp": [
"oklch(15% 0.005 265)",
"oklch(25% 0.009 265)",
"oklch(35% 0.012 265)",
"oklch(48% 0.012 265)",
"oklch(60% 0.012 265)",
"oklch(72% 0.01 265)",
"oklch(84% 0.005 265)",
"oklch(95% 0.002 265)"
]
},
"island-dark": {
"role": "neutral",
"displayName": "Island (Dark)",
"tonalRamp": [
"oklch(15% 0.005 265)",
"oklch(25% 0.009 265)",
"oklch(35% 0.012 265)",
"oklch(48% 0.012 265)",
"oklch(60% 0.012 265)",
"oklch(72% 0.01 265)",
"oklch(84% 0.005 265)",
"oklch(95% 0.002 265)"
]
},
"ink-dark": {
"role": "neutral",
"displayName": "Ink (Dark)",
"tonalRamp": [
"oklch(15% 0.005 265)",
"oklch(25% 0.009 265)",
"oklch(35% 0.012 265)",
"oklch(48% 0.012 265)",
"oklch(60% 0.012 265)",
"oklch(72% 0.01 265)",
"oklch(84% 0.005 265)",
"oklch(95% 0.002 265)"
]
},
"ink-strong-dark": {
"role": "neutral",
"displayName": "Ink Strong (Dark)",
"tonalRamp": [
"oklch(15% 0.005 265)",
"oklch(25% 0.009 265)",
"oklch(35% 0.012 265)",
"oklch(48% 0.012 265)",
"oklch(60% 0.012 265)",
"oklch(72% 0.01 265)",
"oklch(84% 0.005 265)",
"oklch(95% 0.002 265)"
]
},
"ink-muted-dark": {
"role": "neutral",
"displayName": "Ink Muted (Dark)",
"tonalRamp": [
"oklch(15% 0.005 265)",
"oklch(25% 0.009 265)",
"oklch(35% 0.012 265)",
"oklch(48% 0.012 265)",
"oklch(60% 0.012 265)",
"oklch(72% 0.01 265)",
"oklch(84% 0.005 265)",
"oklch(95% 0.002 265)"
]
},
"control-edge-dark": {
"role": "neutral",
"displayName": "Control Edge (Dark)",
"tonalRamp": [
"oklch(15% 0.005 265)",
"oklch(25% 0.009 265)",
"oklch(35% 0.012 265)",
"oklch(48% 0.012 265)",
"oklch(60% 0.012 265)",
"oklch(72% 0.01 265)",
"oklch(84% 0.005 265)",
"oklch(95% 0.002 265)"
]
},
"selection-wash-dark": {
"role": "primary",
"displayName": "Selection Wash (Dark)",
"canonical": "#2a4371",
"tonalRamp": [
"oklch(15% 0.034 262)",
"oklch(25% 0.057 262)",
"oklch(35% 0.08 262)",
"oklch(48% 0.08 262)",
"oklch(60% 0.08 262)",
"oklch(72% 0.064 262)",
"oklch(84% 0.037 262)",
"oklch(95% 0.011 262)"
]
}
},
"typographyMeta": {
"title": {
"displayName": "Title",
"purpose": "Tool window titles, section headers, dialog titles; weight 600 is the main emphasis."
},
"body": {
"displayName": "Body",
"purpose": "Default UI text, menus, rows, buttons."
},
"label": {
"displayName": "Label",
"purpose": "Secondary metadata, chips, status bar, table cells; the most-used size."
},
"label-tiny": {
"displayName": "Label Tiny",
"purpose": "Stripe labels, counters, badges."
},
"input-large": {
"displayName": "Input Large",
"purpose": "Search Everywhere and other large query fields."
},
"code": {
"displayName": "Code",
"purpose": "Editor, console, terminal and every monospace preview; size and weights are user settings."
}
},
"shadows": [
{
"name": "shadow-popup",
"value": "0 6px 20px rgba(0, 0, 0, 0.12)",
"purpose": "Popups, menus, completion, floating toolbar (Light; Dark uses 0.45 alpha)."
},
{
"name": "shadow-dialog",
"value": "0 0 0 0.5px rgba(0, 0, 0, 0.1), 0 10px 24px rgba(0, 0, 0, 0.1), 0 24px 72px rgba(0, 0, 0, 0.2)",
"purpose": "Window-style shadow for dialogs (Light)."
},
{
"name": "shadow-tooltip",
"value": "0 4px 12px rgba(0, 0, 0, 0.12)",
"purpose": "Hover tooltips (Light)."
},
{
"name": "shadow-balloon",
"value": "0 8px 24px rgba(0, 0, 0, 0.14)",
"purpose": "Notification balloons (Light)."
}
],
"motion": [
{
"name": "ease",
"value": "cubic-bezier(0.2, 0, 0, 1)",
"purpose": "Default easing for every state transition."
},
{
"name": "dur-fast",
"value": "80ms",
"purpose": "Hover, press and focus changes on controls."
},
{
"name": "dur",
"value": "140ms",
"purpose": "Standard transitions such as popup fades."
},
{
"name": "dur-slow",
"value": "220ms",
"purpose": "Upper bound for any state transition."
}
],
"density": [
{
"name": "default",
"value": "rows 24px, fields/buttons 28px, titlebar 40px, tab bar 38px, status bar 30px, island gap 6px, island radius 10px"
},
{
"name": "compact",
"value": "rows 22px, fields/buttons 24px, titlebar/headers 32px, tab bar 32px, status bar 24px, island gap 4px, island radius 8px, chrome text -1px"
}
]
},
"components": [
{
"name": "Primary Button",
"kind": "button",
"refersTo": "button-primary",
"description": "The one default action in a dialog or form.",
"html": "<button class=\"ds-btn ds-btn-primary\">OK</button>",
"css": ".ds-btn { display:inline-flex; align-items:center; justify-content:center; height:var(--h-button,28px); min-width:72px; padding:0 16px; border:0; border-radius:var(--radius-control,4px); font-family:var(--font-ui); font-size:var(--fs-ui,13px); line-height:1; cursor:default; transition:background var(--dur-fast,80ms) var(--ease), color var(--dur-fast,80ms) var(--ease), box-shadow var(--dur-fast,80ms) var(--ease); } .ds-btn:focus-visible { outline:2px solid var(--focus-ring,#3871e1); outline-offset:1px; } .ds-btn-primary { background:var(--bg-button-primary,#3871e1); color:var(--fg-button-primary,#fff); } .ds-btn-primary:hover { background:var(--bg-button-primary-hover,#3366cc); }"
},
{
"name": "Secondary Button",
"kind": "button",
"refersTo": "button-secondary",
"description": "Every other dialog action: Cancel, Apply, Browse.",
"html": "<button class=\"ds-btn ds-btn-secondary\">Cancel</button>",
"css": ".ds-btn { display:inline-flex; align-items:center; justify-content:center; height:var(--h-button,28px); min-width:72px; padding:0 16px; border:0; border-radius:var(--radius-control,4px); font-family:var(--font-ui); font-size:var(--fs-ui,13px); line-height:1; cursor:default; transition:background var(--dur-fast,80ms) var(--ease), box-shadow var(--dur-fast,80ms) var(--ease); } .ds-btn:focus-visible { outline:2px solid var(--focus-ring,#3871e1); outline-offset:1px; } .ds-btn-secondary { background:var(--bg-button,#fff); color:var(--fg-strong,#000); box-shadow:inset 0 0 0 1px var(--border-button,#d1d3d9); } .ds-btn-secondary:hover { background:color-mix(in srgb, var(--bg-button,#fff) 94%, var(--fg-strong,#000)); }"
},
{
"name": "Ghost Button",
"kind": "button",
"refersTo": "button-ghost",
"description": "Low-emphasis text actions in headers and inline rows.",
"html": "<button class=\"ds-btn-ghost\">Show all</button>",
"css": ".ds-btn-ghost { display:inline-flex; align-items:center; height:var(--h-button,28px); padding:0 8px; border:0; background:transparent; border-radius:var(--radius-control,4px); color:var(--fg-secondary,#5f6269); font-family:var(--font-ui); font-size:var(--fs-ui,13px); cursor:default; transition:background var(--dur-fast,80ms) var(--ease), color var(--dur-fast,80ms) var(--ease); } .ds-btn-ghost:hover { background:var(--bg-toolbar-hover,#00000012); color:var(--fg-strong,#000); } .ds-btn-ghost:active { background:var(--bg-toolbar-pressed,#00000020); } .ds-btn-ghost:focus-visible { outline:2px solid var(--focus-ring,#3871e1); outline-offset:1px; }"
},
{
"name": "Toolbar Icon Button",
"kind": "button",
"refersTo": "icon-button",
"description": "Toolbar and tool window header actions; frameless at rest, toggles show Selection Wash.",
"html": "<div class=\"ds-iconbar\"><button class=\"ds-icon-btn\" aria-label=\"Refresh\"><svg width=\"16\" height=\"16\" viewBox=\"0 0 16 16\" fill=\"none\"><path d=\"M13 8a5 5 0 1 1-1.46-3.54M13 3v2.5h-2.5\" stroke=\"currentColor\" stroke-width=\"1.2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/></svg></button><button class=\"ds-icon-btn\" aria-label=\"Show options\" aria-pressed=\"true\"><svg width=\"16\" height=\"16\" viewBox=\"0 0 16 16\" fill=\"none\"><path d=\"M2.5 4.5h11M2.5 8h11M2.5 11.5h11\" stroke=\"currentColor\" stroke-width=\"1.2\" stroke-linecap=\"round\"/></svg></button></div>",
"css": ".ds-iconbar { display:flex; gap:2px; } .ds-icon-btn { display:inline-flex; align-items:center; justify-content:center; width:24px; height:24px; padding:0; border:0; background:transparent; border-radius:var(--radius-toolbar-button,6px); color:var(--fg-muted,#6c707e); cursor:default; transition:background var(--dur-fast,80ms) var(--ease), color var(--dur-fast,80ms) var(--ease); } .ds-icon-btn:hover { background:var(--bg-toolbar-hover,#00000012); color:var(--fg-strong,#000); } .ds-icon-btn:active { background:var(--bg-toolbar-pressed,#00000020); } .ds-icon-btn[aria-pressed=\"true\"] { background:var(--bg-toolbar-selected,#d0dffe); color:var(--fg-strong,#000); } .ds-icon-btn:focus-visible { outline:2px solid var(--focus-ring,#3871e1); outline-offset:-2px; }"
},
{
"name": "Text Field",
"kind": "input",
"refersTo": "input",
"description": "Framed text field; the frame doubles in Workbench Blue on focus.",
"html": "<input class=\"ds-input\" placeholder=\"Project name\" />",
"css": ".ds-input { height:var(--h-field,28px); padding:0 8px; border:0; appearance:none; border-radius:var(--radius-control,4px); background:var(--bg-field,#fff); color:var(--fg-strong,#000); font-family:var(--font-ui); font-size:var(--fs-ui,13px); outline:none; box-shadow:inset 0 0 0 1px var(--border-button,#d1d3d9); transition:box-shadow var(--dur-fast,80ms) var(--ease); } .ds-input::placeholder { color:var(--fg-faint,#9fa2a8); } .ds-input:focus { box-shadow:inset 0 0 0 1px var(--focus-ring,#3871e1), 0 0 0 1px var(--focus-ring,#3871e1); }"
},
{
"name": "Chip",
"kind": "chip",
"refersTo": "chip",
"description": "Flat read-only fact or picker trigger, sized like the toolbar widgets.",
"html": "<button class=\"ds-chip\"><svg width=\"14\" height=\"14\" viewBox=\"0 0 16 16\" fill=\"none\"><circle cx=\"5\" cy=\"4\" r=\"1.5\" stroke=\"currentColor\"/><circle cx=\"5\" cy=\"12\" r=\"1.5\" stroke=\"currentColor\"/><circle cx=\"11\" cy=\"6\" r=\"1.5\" stroke=\"currentColor\"/><path d=\"M5 5.5v5M11 7.5c0 2-2 2.5-6 3\" stroke=\"currentColor\"/></svg><span>main</span></button>",
"css": ".ds-chip { display:inline-flex; align-items:center; gap:var(--space-1,4px); height:22px; padding:0 6px; border:0; background:transparent; border-radius:var(--radius-toolbar-button,6px); color:var(--fg-secondary,#5f6269); font-family:var(--font-ui); font-size:var(--fs-small,12px); line-height:1; cursor:default; transition:background var(--dur-fast,80ms) var(--ease); } .ds-chip svg { color:var(--fg-muted,#6c707e); } .ds-chip:hover { background:var(--bg-toolbar-hover,#00000012); } .ds-chip:focus-visible { outline:2px solid var(--focus-ring,#3871e1); outline-offset:-2px; }"
},
{
"name": "Tree Rows",
"kind": "custom",
"refersTo": "list-row-selected",
"description": "24px rows with an inset rounded selection wash; unfocused selection turns neutral.",
"html": "<div class=\"ds-tree\" tabindex=\"0\"><div class=\"ds-row\">src</div><div class=\"ds-row ds-row-sel\">main.tsx</div><div class=\"ds-row\">workbench</div></div>",
"css": ".ds-tree { width:220px; padding:4px var(--tree-inset,6px); background:var(--bg-island,#fff); border-radius:var(--island-radius,10px); font-family:var(--font-ui); font-size:var(--fs-ui,13px); color:var(--fg,#000); outline:none; } .ds-row { height:var(--h-row,24px); display:flex; align-items:center; padding:0 8px; border-radius:var(--radius-row,4px); } .ds-row:hover { background:var(--bg-tree-hover,#0000000a); } .ds-row-sel, .ds-row-sel:hover { background:var(--bg-tree-selected-inactive,#e9eaee); } .ds-tree:focus .ds-row-sel { background:var(--bg-tree-selected,#d0dffe); }"
},
{
"name": "Island on Frame",
"kind": "card",
"description": "The signature layout unit: rounded islands 6px apart on the grey frame, flat at rest.",
"html": "<div class=\"ds-frame\"><div class=\"ds-island ds-side\"><div class=\"ds-head\">Project</div></div><div class=\"ds-island ds-main\"><code>fn main() {}</code></div></div>",
"css": ".ds-frame { display:flex; gap:var(--island-gap,6px); padding:var(--island-gap,6px); background:var(--bg-frame,#e9eaee); height:160px; } .ds-island { background:var(--bg-island,#fff); border-radius:var(--island-radius,10px); } .ds-side { width:140px; } .ds-main { flex:1; padding:12px; font-family:var(--font-mono); font-size:var(--fs-code,13px); color:var(--fg-editor,#080808); } .ds-head { height:40px; display:flex; align-items:center; padding:0 12px; font-family:var(--font-ui); font-size:var(--fs-ui,13px); font-weight:600; color:var(--fg-strong,#000); }"
},
{
"name": "Tooltip",
"kind": "custom",
"refersTo": "tooltip",
"description": "Floating hover help: one of the few surfaces allowed a shadow.",
"html": "<div class=\"ds-tooltip\">Run 'main' <span class=\"ds-kbd\">⌃R</span></div>",
"css": ".ds-tooltip { display:inline-flex; gap:8px; align-items:center; padding:6px 10px; border-radius:var(--radius-tooltip,6px); background:var(--bg-tooltip,#fff); color:var(--fg-tooltip,#000); border:1px solid var(--border-tooltip,#d1d3d9); box-shadow:var(--shadow-tooltip,0 4px 12px rgba(0,0,0,.12)); font-family:var(--font-ui); font-size:var(--fs-ui,13px); } .ds-kbd { font-family:var(--font-keys); color:var(--fg-muted,#6c707e); }"
}
],
"narrative": {
"northStar": "The Quiet Workbench",
"overview": "The interface is a workbench, not a showroom. Code, trees, logs and diffs are the work. The chrome around them stays quiet, so the eye goes to the content and a long session stays calm.\n\nThe visual language is the JetBrains new UI in its **Islands** form, and this document records it rather than inventing one. The tokens in `src/styles/tokens.css` take their values from the Islands Light and Islands Dark theme JSON and editor schemes, at 100% zoom. Component metrics follow the matching IntelliJ theme keys (a Swing `arc` is a diameter, so the CSS radius is half of it), and component CSS names the key it follows. Behaviour follows IDEA as well, from focus and selection to dialogs and drag and drop. Users bring their JetBrains muscle memory, so a layout, metric or state that looks or behaves differently from IDEA counts as a bug, not a style choice.\n\nEvery panel sits on a grey frame as a rounded island (10px corners, 6px gaps). Depth comes from that tonal step, not from decoration. The density is that of a professional desktop tool: 13px UI text, 24px rows, 28px controls, with a compact mode that tightens all of them.\n\nThe tokens are a theming contract, not one palette. The built-in themes are Islands Light (the default), Islands Dark, High Contrast, Solarized Light and Solarized Dark. Users can also change the accent colour, give tool windows a different background from the editor, set a background image, use contrast scrollbars, or adjust colours for red-green vision deficiency. Imported IntelliJ themes and plugin themes set the same tokens at runtime. A component that looks right only in Islands Light is broken.\n\nExpression is kept to precise details: one blue accent, controls with no frame until they're hovered, hairline frames on fields and secondary buttons, and fast state transitions. Three things are rejected outright. It must not look like a web app: no big rounded cards, airy marketing whitespace, decorative gradients or illustrations. It has no second accent colour. And it has no eye-catching animation.",
"keyCharacteristics": [
"JetBrains new UI (Islands): metrics and behaviour follow IntelliJ's theme keys.",
"Grey frame, rounded content islands, tonal layering only.",
"A single accent (Workbench Blue) for primary actions, focus, selection and the active tool window.",
"High density on a 4px grid. Compact mode is a first-class variant.",
"Controls are quiet at rest: toolbar buttons and chips have no frame until hover.",
"Semantic colour (status, VCS, diff, syntax) carries meaning and is never decoration.",
"Every colour and metric is a token in `src/styles/tokens.css`. Tokens are the public theme API for plugins."
],
"rules": [
{
"name": "The IDEA Reference Rule",
"body": "When tokens and this document don't answer a question, the answer is what IntelliJ IDEA does in the Islands theme, with the same metric and the same state behaviour. Take the value from the theme key, add it as a token, and name the key in a CSS comment.",
"section": "overview"
},
{
"name": "The One Accent Rule",
"body": "Workbench Blue is the only accent. Every other hue in the UI belongs to a functional vocabulary (status, VCS, diff, syntax, charts) and means something specific. If a new colour has no meaning to carry, it doesn't ship.",
"section": "colors"
},
{
"name": "The Token Only Rule",
"body": "Components never contain hex, `rgb()` or named colour literals. A new colour is a new token with a value in every theme variant, named for its purpose. Run `pnpm gen:theme-docs` afterwards.",
"section": "colors"
},
{
"name": "The Flat Scale Rule",
"body": "The UI uses 11, 12, 13 and 15px, and nothing in between. Emphasis is weight 600 or a stronger ink colour, not a bigger size.",
"section": "typography"
},
{
"name": "The User Owns Size Rule",
"body": "Sizes are tokens because users change them (UI font size, editor font, compact mode's -1px chrome offset). Never hard-code a font size.",
"section": "typography"
},
{
"name": "The Flat at Rest Rule",
"body": "No docked panel, island, row or control gets a shadow. A shadow means \"this floats over the workbench and will go away\". Depth inside the layout is only ever a tonal step.",
"section": "elevation"
}
],
"dos": [
"**Do** match IntelliJ IDEA's Islands theme for any metric or state that isn't tokenized yet. Take the value from the theme key and name the key in a CSS comment (for example `Button.arc 8 (radius 4)`).",
"**Do** take every colour and metric from `src/styles/tokens.css`, and add a token for every theme variant when you need a new one.",
"**Do** separate regions with a tonal step (frame against island) or a 1px hairline, never with a shadow.",
"**Do** keep toolbar buttons and chips without a frame at rest, with the toolbar hover wash over the full hit target.",
"**Do** draw frames and focus rings as inset box-shadows (1px at rest, doubled on focus), and keep the 2px Workbench Blue focus outline visible.",
"**Do** check every surface in Islands Light and Islands Dark at least, as the contribution guidelines require. Check High Contrast and compact density whenever a change touches colour or metrics.",
"**Do** keep transitions to state changes: 80ms (`--dur-fast`), 140ms (`--dur`) or at most 220ms (`--dur-slow`) with `--ease`, and none under reduced motion.",
"**Do** use icons from the `src/ui/icons.tsx` registry, drawn in `currentColor`."
],
"donts": [
"**Don't** make it look like a web app: no large rounded cards, airy marketing whitespace, decorative gradients, hero illustrations or corners above 10px. The project wash is the one gradient in the chrome. Progress shimmer counts as activity, not decoration.",
"**Don't** invent a look or behaviour where IDEA already has one. A custom variant of an IDEA pattern breaks muscle memory.",
"**Don't** add a second accent. Any hue other than Workbench Blue must carry status, VCS, diff, syntax or chart meaning.",
"**Don't** add attention-seeking animation: no bounces, no staggered entrances, and no state transition over 220ms. Looping animation is only for activity that is really happening (spinners, progress, loading shimmer, a running pulse, the caret), never decoration.",
"**Don't** put shadows on docked panels, islands, rows or controls.",
"**Don't** use sizes off the 11/12/13/15px scale, or hard-code a font size users can change.",
"**Don't** use hex, `rgb()` or named colours in component CSS or inline styles.",
"**Don't** use emoji as icons or decoration, or inline ad-hoc SVG in a feature."
]
}
}
+16
View File
@@ -147,6 +147,22 @@
"prefer-rest-params": "error",
"prefer-spread": "error"
}
},
{
"files": [
"evals/**/*.ts",
"perf/**/*.ts",
"smoke/**/*.ts",
"src/features/vcs/**/*.ts",
"src/features/vcs/**/*.tsx",
"src/features/run/**/*.ts",
"src/features/run/**/*.tsx",
"src/features/database/**/*.ts",
"src/features/database/**/*.tsx"
],
"rules": {
"no-await-in-loop": "error"
}
}
]
}
Generated
+3
View File
@@ -4320,6 +4320,7 @@ dependencies = [
"ide-http",
"ide-sdk",
"ide-ssh",
"libc",
"notify",
"open",
"oracledb",
@@ -4339,6 +4340,7 @@ dependencies = [
"toml_edit 0.25.17+spec-1.1.0",
"tracing",
"uuid",
"windows-sys 0.61.2",
"zeroize",
"zip",
]
@@ -4515,6 +4517,7 @@ dependencies = [
"toml 0.9.12+spec-1.1.0",
"tracing",
"tracing-subscriber",
"url",
"uuid",
"windows-sys 0.61.2",
"zip",
+323
View File
@@ -0,0 +1,323 @@
---
name: OpenIDEA
description: The IDE you know, rebuilt in Rust.
colors:
workbench-blue: "#3871e1"
link-blue: "#2f5eb9"
frame-grey: "#e9eaee"
island-white: "#ffffff"
raised-paper: "#f7f8f9"
ink: "#000000"
ink-secondary: "#5f6269"
ink-muted: "#6c707e"
ink-faint: "#9fa2a8"
hairline: "#e9eaee"
control-edge: "#d1d3d9"
selection-wash: "#d0dffe"
tab-wash: "#e3ebfe"
danger: "#c54e58"
warning: "#a56906"
success: "#338555"
frame-grey-dark: "#26282c"
island-dark: "#191a1c"
ink-dark: "#d1d3d9"
ink-strong-dark: "#dfe1e5"
ink-muted-dark: "#8c8f95"
control-edge-dark: "#40434a"
selection-wash-dark: "#2a4371"
typography:
title:
fontFamily: "Inter Variable, Inter, system-ui, -apple-system, sans-serif"
fontSize: "13px"
fontWeight: 600
lineHeight: 1.4
body:
fontFamily: "Inter Variable, Inter, system-ui, -apple-system, sans-serif"
fontSize: "13px"
fontWeight: 400
lineHeight: 1.4
label:
fontFamily: "Inter Variable, Inter, system-ui, -apple-system, sans-serif"
fontSize: "12px"
fontWeight: 400
lineHeight: 1.4
label-tiny:
fontFamily: "Inter Variable, Inter, system-ui, -apple-system, sans-serif"
fontSize: "11px"
fontWeight: 400
lineHeight: 1.4
input-large:
fontFamily: "Inter Variable, Inter, system-ui, -apple-system, sans-serif"
fontSize: "15px"
fontWeight: 400
code:
fontFamily: "JetBrains Mono, JetBrains Mono Variable, ui-monospace, Menlo, monospace"
fontSize: "13px"
fontWeight: 400
lineHeight: "22px"
fontFeature: "\"liga\" 0"
rounded:
small: "4px"
control: "4px"
row: "4px"
selection: "5px"
tab: "6px"
toolbar-button: "6px"
tooltip: "6px"
popup: "8px"
island: "10px"
popup-large: "10px"
dialog: "10px"
spacing:
space-0-5: "2px"
space-1: "4px"
space-1-5: "6px"
space-2: "8px"
space-3: "12px"
space-4: "16px"
components:
button-primary:
backgroundColor: "{colors.workbench-blue}"
textColor: "{colors.island-white}"
typography: "{typography.body}"
rounded: "{rounded.control}"
padding: "0 16px"
height: "28px"
button-secondary:
backgroundColor: "{colors.island-white}"
textColor: "{colors.ink}"
typography: "{typography.body}"
rounded: "{rounded.control}"
padding: "0 16px"
height: "28px"
button-ghost:
textColor: "{colors.ink-secondary}"
typography: "{typography.body}"
rounded: "{rounded.control}"
padding: "0 8px"
height: "28px"
icon-button:
textColor: "{colors.ink-muted}"
rounded: "{rounded.toolbar-button}"
size: "24px"
icon-button-selected:
backgroundColor: "{colors.selection-wash}"
textColor: "{colors.ink}"
rounded: "{rounded.toolbar-button}"
size: "24px"
input:
backgroundColor: "{colors.island-white}"
textColor: "{colors.ink}"
typography: "{typography.body}"
rounded: "{rounded.control}"
padding: "0 8px"
height: "28px"
chip:
textColor: "{colors.ink-secondary}"
typography: "{typography.label}"
rounded: "{rounded.toolbar-button}"
padding: "0 6px"
height: "22px"
tooltip:
backgroundColor: "{colors.island-white}"
textColor: "{colors.ink}"
typography: "{typography.body}"
rounded: "{rounded.tooltip}"
padding: "6px 10px"
list-row-selected:
backgroundColor: "{colors.selection-wash}"
textColor: "{colors.ink}"
rounded: "{rounded.row}"
height: "24px"
---
# Design System: OpenIDEA
## Overview
**Creative North Star: "The Quiet Workbench"**
The interface is a workbench, not a showroom. Code, trees, logs and diffs are the work. The chrome around them stays quiet, so the eye goes to the content and a long session stays calm.
The visual language is the JetBrains new UI in its **Islands** form, and this document records it rather than inventing one. The tokens in `src/styles/tokens.css` take their values from the Islands Light and Islands Dark theme JSON and editor schemes, at 100% zoom. Component metrics follow the matching IntelliJ theme keys (a Swing `arc` is a diameter, so the CSS radius is half of it), and component CSS names the key it follows. Behaviour follows IDEA as well, from focus and selection to dialogs and drag and drop. Users bring their JetBrains muscle memory, so a layout, metric or state that looks or behaves differently from IDEA counts as a bug, not a style choice.
Every panel sits on a grey frame as a rounded island (10px corners, 6px gaps). Depth comes from that tonal step, not from decoration. The density is that of a professional desktop tool: 13px UI text, 24px rows, 28px controls, with a compact mode that tightens all of them.
The tokens are a theming contract, not one palette. The built-in themes are Islands Light (the default), Islands Dark, High Contrast, Solarized Light and Solarized Dark. Users can also change the accent colour, give tool windows a different background from the editor, set a background image, use contrast scrollbars, or adjust colours for red-green vision deficiency. Imported IntelliJ themes and plugin themes set the same tokens at runtime. A component that looks right only in Islands Light is broken.
Expression is kept to precise details: one blue accent, controls with no frame until they're hovered, hairline frames on fields and secondary buttons, and fast state transitions. Three things are rejected outright. It must not look like a web app: no big rounded cards, airy marketing whitespace, decorative gradients or illustrations. It has no second accent colour. And it has no eye-catching animation.
### Named Rules
**The IDEA Reference Rule.** When tokens and this document don't answer a question, the answer is what IntelliJ IDEA does in the Islands theme, with the same metric and the same state behaviour. Take the value from the theme key, add it as a token, and name the key in a CSS comment.
**Key Characteristics:**
- JetBrains new UI (Islands): metrics and behaviour follow IntelliJ's theme keys.
- Grey frame, rounded content islands, tonal layering only.
- A single accent (Workbench Blue) for primary actions, focus, selection and the active tool window.
- High density on a 4px grid. Compact mode is a first-class variant.
- Controls are quiet at rest: toolbar buttons and chips have no frame until hover.
- Semantic colour (status, VCS, diff, syntax) carries meaning and is never decoration.
- Every colour and metric is a token in `src/styles/tokens.css`. Tokens are the public theme API for plugins.
## Colors
A near-neutral grey ramp with one cool blue accent. Status, VCS and syntax colours are functional vocabularies with fixed meanings. Values in the frontmatter are Islands Light (the default), and `-dark` keys are the Islands Dark counterparts. High Contrast, the Solarized themes, imported IntelliJ themes and plugin themes override the same tokens, so the names describe roles, not hexes.
### Project colour
- **Project wash** (`--project-color`): a radial tint of the project's colour (22% strength, 600 × 300px) that fades in from the frame's top-left corner, as the IDEA project gradient does. It identifies the project window. It is the one gradient in the chrome.
### Primary
- **Workbench Blue** (`--accent`): primary buttons, the focus ring, the selected-and-active stripe button, and search-match emphasis. The appearance setting can override it, so components reference `--accent`, never the hex.
- **Link Blue** (`--link`): inline links. In Dark it lightens to stay readable on the dark islands.
### Neutral
- **Frame Grey** (`--bg-frame`): the window frame behind the islands, and the stripes (the tool window button bars).
- **Island White** (`--bg-island`, `--bg-app`): editor and tool window surfaces. This is where the work lives.
- **Raised Paper** (`--bg-elev`, `--bg-dialog`): dialog bodies and inline popups, one tonal step off the island.
- **Ink** (`--fg`, `--fg-strong`): primary text. **Ink Secondary / Muted / Faint** (`--fg-secondary`, `--fg-muted`, `--fg-faint`): metadata, icons and placeholders, then disabled text.
- **Hairline** (`--border`): dividers between regions inside an island. **Control Edge** (`--border-button`, `--border-strong`): the 1px inset frame of fields and secondary buttons.
- **Selection Wash** (`--bg-tree-selected`, `--bg-selected`, `--bg-toolbar-selected`): the selected row in focused trees and lists, and pressed-on toolbar toggles. When the tree loses focus, the selection drops to the neutral `--bg-tree-selected-inactive`.
### Functional vocabularies
- **Status:** `--danger`, `--warning`, `--success` and `--info`, each with `--bg-feedback-*` and `--border-feedback-*` pairs for banners.
- **VCS and diff:** `--vcs-*` for file status in trees and tabs, `--gutter-*` for gutter marks, and `--diff-*` for diff fills and their error-stripe marks.
- **Syntax:** `--syn-*`, from the editor colour scheme. Users and plugins replace these per scheme.
### Named Rules
**The One Accent Rule.** Workbench Blue is the only accent. Every other hue in the UI belongs to a functional vocabulary (status, VCS, diff, syntax, charts) and means something specific. If a new colour has no meaning to carry, it doesn't ship.
**The Token Only Rule.** Components never contain hex, `rgb()` or named colour literals. A new colour is a new token with a value in every theme variant, named for its purpose. Run `pnpm gen:theme-docs` afterwards.
## Typography
**UI Font:** Inter Variable (with system-ui and -apple-system fallbacks)
**Code Font:** JetBrains Mono (with ui-monospace and Menlo fallbacks)
**Key Glyph Font:** the system UI font (`--font-keys`), so shortcut glyphs such as ⌘⇧⌥⌃↵ render as they do in native menus
**Character:** a neutral sans for chrome and a coding mono for content. Neither performs. Hierarchy comes from weight and colour, not size.
### Hierarchy
- **Title** (600, 13px, 1.4): tool window titles, section headers, dialog titles and emphasised names. Weight 600 is the system's main emphasis.
- **Body** (400, 13px, 1.4): default UI text, menus, tree and list rows, and buttons.
- **Label** (400, 12px): the most common size. It covers secondary metadata, chips, status bar items, table cells and hints.
- **Label Tiny** (400, 11px): stripe labels, counters and badges.
- **Input Large** (400, 15px): Search Everywhere and similar large query fields.
- **Code** (400, 13px, 22px line height): the editor, console, terminal and every monospace preview. Ligatures are off by default and follow the `editor.ligatures` setting. Users set the weights (`--fw-code`, `--fw-code-bold`) and the size.
### Named Rules
**The Flat Scale Rule.** The UI uses 11, 12, 13 and 15px, and nothing in between. Emphasis is weight 600 or a stronger ink colour, not a bigger size.
**The User Owns Size Rule.** Sizes are tokens because users change them (UI font size, editor font, compact mode's -1px chrome offset). Never hard-code a font size.
## Layout
The window is a grey frame holding docked islands: the editor in the centre, tool windows around it, stripes of tool window buttons on the edges (58px wide), a titlebar with the main toolbar (40px), and a status bar (30px). The status bar sits directly on the frame with no divider. Islands sit 6px apart and have 10px corners. Trees are inset 6px inside their island.
Spacing follows a 4px grid (`--space-0-5` to `--space-4`, 2–16px). It is used for gaps, with component heights doing most of the rhythm work: rows 24px, fields and buttons 28px, small controls 24px or 20px, tabs 28px in a 38px tab bar, and tool window headers 40px.
**Compact mode** (`data-compact`) is a full variant, not an afterthought. Rows drop to 22px, fields and buttons to 24px, the titlebar and headers to 32px, the status bar to 24px, the island gap to 4px and island corners to 8px, and chrome text gets 1px smaller. Every layout must hold in both modes.
The app is a desktop window. It is never a scrolling page: the document never scrolls, and every scroll region is its own scroller inside an island. Dialogs open about 10vh from the top and below the titlebar. Wide reading surfaces, such as an agent conversation, cap their width (900px) inside the island.
## Elevation & Depth
Static layout is flat and layered by tone. The grey frame sits under white islands (in Dark, a lighter frame under darker islands). Shadows exist only on surfaces that float above the layout: popups, menus, dialogs, tooltips, balloons, undocked tool windows and drag ghosts. Dialogs use a window-style shadow, because they are separate windows in spirit.
### Shadow Vocabulary
- **Popup** (`--shadow-popup`; Light `0 6px 20px rgba(0,0,0,0.12)`): popups, menus, completion and the floating editor toolbar.
- **Dialog** (`--shadow-dialog`): a hairline ring plus two soft drops, like a native window shadow.
- **Tooltip** (`--shadow-tooltip`) and **Balloon** (`--shadow-balloon`): small and medium drops for hover help and notifications.
### Named Rules
**The Flat at Rest Rule.** No docked panel, island, row or control gets a shadow. A shadow means "this floats over the workbench and will go away". Depth inside the layout is only ever a tonal step.
## Shapes
Corners scale with the size of the surface. Small controls get 4px (buttons, fields, combos, rows, small icon buttons). Toolbar buttons, chips, tabs and tooltips get 6px, and selection highlights get 5px. Popups get 8–10px, and islands and dialogs get 10px. Compact mode tightens island corners to 8px and combo corners to 2px. Frames are drawn as 1px inset box-shadows rather than borders, so they never shift layout and can double on focus. There are no pills, circles (apart from macOS window buttons and status dots), or rounding beyond 10px.
## Components
Quiet and dependable. Components don't call attention to themselves, they behave the same everywhere, and they come from `src/ui/` primitives before anything custom.
### Buttons
- **Shape:** gently rounded (4px). Minimum width 72px, 28px tall, 16px horizontal padding. The small variant is 24px tall with 10px padding.
- **Primary:** Workbench Blue fill with white text. Hover mixes it toward the strong ink colour (`--accent-hover`). Use it for one default action per dialog.
- **Secondary:** island-coloured with a 1px Control Edge inset frame. Hover darkens the fill by about 6%.
- **Ghost:** no fill or frame, secondary ink colour, 8px padding. Hover shows the toolbar hover wash and strong ink. Pressed is a stronger wash.
- **Focus:** a 2px Workbench Blue outline, 1px outside the button. **Disabled:** transparent fill, faint text and a hairline frame.
- **Motion:** background, colour and frame change over 80ms (`--dur-fast`) with `--ease`. There are no transitions under `prefers-reduced-motion`, and forced-colours mode gets a real border.
### Icon Buttons (toolbar actions)
- 20, 24 or 28px square, with 6px corners (4px at 20px). The icon is muted at rest.
- Hover shows the toolbar hover wash (`--bg-toolbar-hover`, a translucent ink) across the full hit target, and the icon turns strong ink. Pressed shows `--bg-toolbar-pressed`.
- A toggled-on button (`aria-pressed`) shows Selection Wash. The focus ring is drawn 2px inside the button.
- Tone variants (`danger`, `accent`) recolour only the icon.
### Chips
- **Style:** flat, like the main toolbar's project and branch widgets. They are 22px tall with 6px corners, have no fill or frame at rest, and use 12px secondary ink with a muted icon.
- **State:** a chip that opens a picker gets the toolbar hover wash. A read-only chip never changes on hover.
### Inputs / Fields
- **Style:** 28px tall with 8px horizontal padding and 4px corners. Island fill with a 1px Control Edge inset frame. Placeholders use the faint ink.
- **Focus:** the frame turns Workbench Blue and doubles with a 1px outer ring, drawn entirely with box-shadow.
- **Error:** the same doubled ring in `--danger`. **Disabled:** transparent fill, faint text and a hairline frame.
- Search fields have a muted leading icon. Monospace fields use the code font.
### Lists and Trees
- Rows are 24px (22px compact). The selection is a 4–5px rounded wash inset from the island edge, not a full-bleed bar.
- A focused selection uses Selection Wash, and an unfocused one drops to a neutral grey. Hover is a faint translucent wash. Search matches use `--bg-search-match`.
### Popups, Menus and Dialogs
- **Popups and menus:** `--bg-popup` with a 1px popup frame, 10px corners (`--radius-popup-large`) and the popup shadow.
- **Dialogs:** Raised Paper body with 10px corners and the dialog shadow. They behave like IDEA's dialogs, which are separate windows: the modal layer blocks the workbench but never dims it. The footer actions are right-aligned buttons. Focus returns to wherever it came from when the dialog closes.
### Tabs
- 28px tabs (24px compact) in a 38px bar, with 6px corners and 8px horizontal padding.
- As in IDEA, only the part holding focus accents its selected tab (`--bg-tab-selected` with `--border-tab-selected`). Elsewhere the selected tab drops to the neutral inactive pair.
- **Tooltips:** 6px corners with 6px × 10px padding, using `--bg-tooltip` (white in Light, dark grey in Dark) and the tooltip shadow.
### Tool Window Stripes (signature)
The edge bars of tool window buttons are 58px wide on Frame Grey, with icons over 11px labels. Hover and selected states are translucent ink washes. The selected button of the active tool window fills with Workbench Blue and white content. This is the one place the accent fills a large shape in the chrome, and it marks the active tool window.
## Do's and Don'ts
### Do:
- **Do** match IntelliJ IDEA's Islands theme for any metric or state that isn't tokenized yet. Take the value from the theme key and name the key in a CSS comment (for example `Button.arc 8 (radius 4)`).
- **Do** take every colour and metric from `src/styles/tokens.css`, and add a token for every theme variant when you need a new one.
- **Do** separate regions with a tonal step (frame against island) or a 1px hairline, never with a shadow.
- **Do** keep toolbar buttons and chips without a frame at rest, with the toolbar hover wash over the full hit target.
- **Do** draw frames and focus rings as inset box-shadows (1px at rest, doubled on focus), and keep the 2px Workbench Blue focus outline visible.
- **Do** check every surface in Islands Light and Islands Dark at least, as the contribution guidelines require. Check High Contrast and compact density whenever a change touches colour or metrics.
- **Do** keep transitions to state changes: 80ms (`--dur-fast`), 140ms (`--dur`) or at most 220ms (`--dur-slow`) with `--ease`, and none under reduced motion.
- **Do** use icons from the `src/ui/icons.tsx` registry, drawn in `currentColor`.
### Don't:
- **Don't** make it look like a web app: no large rounded cards, airy marketing whitespace, decorative gradients, hero illustrations or corners above 10px. The project wash is the one gradient in the chrome. Progress shimmer counts as activity, not decoration.
- **Don't** invent a look or behaviour where IDEA already has one. A custom variant of an IDEA pattern breaks muscle memory.
- **Don't** add a second accent. Any hue other than Workbench Blue must carry status, VCS, diff, syntax or chart meaning.
- **Don't** add attention-seeking animation: no bounces, no staggered entrances, and no state transition over 220ms. Looping animation is only for activity that is really happening (spinners, progress, loading shimmer, a running pulse, the caret), never decoration.
- **Don't** put shadows on docked panels, islands, rows or controls.
- **Don't** use sizes off the 11/12/13/15px scale, or hard-code a font size users can change.
- **Don't** use hex, `rgb()` or named colours in component CSS or inline styles.
- **Don't** use emoji as icons or decoration, or inline ad-hoc SVG in a feature.
+73
View File
@@ -0,0 +1,73 @@
# Product
<!-- impeccable:product-schema 1 -->
## Platform
web
The IDE is a Tauri desktop app for macOS, Windows and Linux. Its UI is a web frontend (React, CSS Modules) inside the system webview, with its own design language rather than each operating system's native one. Scope: this record covers the IDE application only. The openidea.sh docs site and home page (`docs/`) are out of scope.
## Users
- **Primary: JetBrains users who want something lighter.** They already know the IntelliJ IDEA keymap, tool windows and search-everything habits, and find IDEA heavy and slow. They do everyday multi-language development on the desktop: editing, navigating, refactoring, running and debugging, Git, terminal, database and HTTP clients.
- **Primary: developers working with AI coding agents.** They run CLI agents (Claude Code, Codex, Gemini CLI, Copilot, Cursor and others over ACP) inside the IDE as tasks, often several at once, each in its own Git worktree or in the checkout. They review the agents' diffs, answer their permission requests, and give agents the IDE's own tools through the built-in MCP server.
- **Secondary: people moving from VS Code or Eclipse.** Their keymaps are built in.
## Product Purpose
OpenIDEA brings the IntelliJ IDEA way of working to a native app with a Rust core: editor, code insight, debugger, Git, terminal, database and HTTP clients for 60+ languages. Success means people who know the IDEA way of working can switch without relearning anything, and it opens, responds and quits much faster while using a fraction of the memory.
## Positioning
"The IDE you know, rebuilt in Rust." The habits are familiar (keymap, tool windows, Search Everywhere, Alt+Enter), the app is open source (Apache 2.0), and performance is measured: on the published benchmark, the window opens in 0.9 s against 3.1 s and the app uses 169 MB against 2011 MB. Coding agents are part of the IDE (tasks, worktrees, diffs and the IDE's tools over MCP) rather than a separate chat app.
## Operating Context
- Long sessions in one desktop window: the editor in the middle, tool windows docked around it, and keyboard-first navigation (Search Everywhere, Find Action, Go to Class/File/Symbol).
- Local projects, and remote development over SSH or in dev containers through the `openidea-server` backend.
- Agent tasks running alongside the developer's own work, with diff review and permission prompts.
- Built-in themes: Islands Light (the default), Islands Dark, High Contrast, Solarized Light and Solarized Dark, with an option to follow the OS's light or dark mode. Users can import IntelliJ themes and `.icls` colour schemes, and plugins add more themes.
## Capabilities and Constraints
Hard constraints future work must preserve:
1. The default keymap and interaction habits stay the same as IDEA's.
2. All user-visible text is written in English and must also have a Chinese translation, through the text catalog (`T`, translated `aria-label`).
3. WebKit floor is Safari 15.4 (macOS 12). No regex lookbehind or `v` flag, no import attributes, and no newer runtime APIs in startup code. `scripts/check-webkit.ts` enforces this.
4. Design tokens in `src/styles/tokens.css` are the public theme API for plugins. Components use tokens only and never colour literals. A new token needs a value for every theme variant, and the docs must be regenerated with `pnpm gen:theme-docs`.
5. Every user operation is an action with a stable id, reachable from the keyboard and Find Action, not only by mouse.
6. No emoji as icons or decoration, in the UI or in user-visible text. Icons come from the `src/ui/icons.tsx` registry.
7. Performance (startup, memory, idle CPU) is the core selling point. UI work must not slow it down.
Other facts:
- Plugins are sandboxed WebAssembly components that add actions, completion, quick fixes, tool windows, custom editors, themes, file icons and languages. The plugin API is still a preview.
- UI is built from the primitives in `src/ui/` (Button, Dialog, Popup, Menu, List, Tree, Tabs and others). Workbench pieces come from contributions, not custom layout.
## Brand Commitments
- Name: OpenIDEA. Wordmarks are in `src-tauri/icons/source/` (`openidea-wordmark.svg` and `openidea-wordmark-dark.svg`).
- Not affiliated with JetBrains. IntelliJ IDEA is a trademark of JetBrains s.r.o.
- Voice is plain, short and factual. It states measurements with their conditions rather than superlatives.
## Evidence on Hand
- Benchmark table and method: `README.md`, `perf/compare`. The conditions are stated with it: freqtrade, warm caches, median of 5 runs, Windows 11, 32-core AMD.
- Demo video linked from `README.md`.
- No testimonials, customer logos or user counts exist. Do not fabricate them.
## Product Principles
1. **Familiar first.** Existing IDEA habits must keep working. New behaviour must not break that muscle memory.
2. **Speed is a feature.** Every surface is judged by how much it costs in startup time, memory and responsiveness.
3. **Keyboard reachable.** If something can be done, it is an action that can be found and bound.
4. **Agents work inside the IDE.** Agent work is reviewed and controlled with the IDE's own tools: diffs, worktrees and permissions.
5. **Themeable by contract.** Visual decisions go through tokens that themes and plugins can rely on.
## Accessibility & Inclusion
- Use real `<button>` and `<input>` elements or the primitives that render them. Every icon-only button has a translated `aria-label`.
- Keep focus visible and predictable. Dialogs and popups return focus to where it came from.
- A dark high-contrast theme (`dark-hc`) ships and must be kept working.
+4 -4
View File
@@ -15,12 +15,12 @@ pub use fingerprint::{LaunchFingerprint, launch_fingerprint, menu_fingerprint};
pub use launch_resources::process_launch_resources;
pub use modules::record_module_build;
pub use single::{
SingleFileTarget, compile_file_plan, find_javac, javac_step, module_classpath, module_classpaths,
single_file_classpath, single_file_target,
SingleFileTarget, compile_file_plan, compile_file_plan_cancellable, find_javac, gradle_compile_file_plan,
has_gradle_file_target, javac_step, module_classpath, module_classpaths, single_file_classpath, single_file_target,
};
pub use structure::{
StructureJdk, StructureRoots, artifact_file, artifact_output, language_release, structure_outputs, structure_plan,
structure_war_plan, structure_web_artifacts,
StructureJdk, StructureRoots, artifact_file, artifact_output, language_release, structure_compile_file_plan,
structure_outputs, structure_plan, structure_war_plan, structure_web_artifacts,
};
pub use up_to_date::{menu_up_to_date, record_menu_build};
+35 -7
View File
@@ -200,19 +200,22 @@ fn kotlin_line(line: &str) -> Option<RawMessage> {
kotlin_location(rest, severity)
}
/// javac: `A.java:12: error: msg` / `A.java:12: warning: [deprecation] msg`.
/// javac: `A.java:12: error: msg` / `A.java:12: warning: [deprecation] msg`
/// (and localized javac prefixes such as Chinese/Japanese `错误:` / `錯誤:` / `エラー:` / `警告:`).
fn javac_header(line: &str) -> Option<RawMessage> {
let (path, ln, col, rest) = path_line_col(line)?;
if !looks_like_source_path(path) {
return None;
}
let rest = rest.trim_start_matches(':').trim_start();
let (severity, msg) = if let Some(m) = rest.strip_prefix("error:") {
(Severity::Error, m)
} else {
let m = rest.strip_prefix("warning:")?;
(Severity::Warning, m)
};
let (severity, msg) = ["error:", "错误:", "錯誤:", "エラー:"]
.into_iter()
.find_map(|prefix| rest.strip_prefix(prefix).map(|m| (Severity::Error, m)))
.or_else(|| {
["warning:", "警告:"]
.into_iter()
.find_map(|prefix| rest.strip_prefix(prefix).map(|m| (Severity::Warning, m)))
})?;
Some(RawMessage::new(severity, msg.trim(), ColUnit::Char).at(path, ln, col))
}
@@ -555,6 +558,31 @@ mod tests {
assert_eq!(out[1].text, "[removal] finalize() has been deprecated");
}
#[test]
fn localized_javac_errors_and_warnings() {
let out = parse(
Format::Gradle,
"/p/src/A.java:12: 错误: 找不到符号\n\
\x20 Foo foo = new Foo();\n\
\x20 ^\n\
\x20 符号: 类 Foo\n\
\x20 位置: 类 A\n\
/p/src/B.java:5: 錯誤: 需要 ';'\n\
\x20 int x = 1\n\
\x20 ^\n\
/p/src/C.java:8: 警告: [deprecation] old() 已过时\n\
\x20 old();\n\
\x20 ^\n",
);
assert_eq!(out.len(), 3, "{out:?}");
assert_eq!(pos(&out[0]), (Severity::Error, "/p/src/A.java", 12, Some(9)));
assert_eq!(out[0].text, "找不到符号\n符号: 类 Foo\n位置: 类 A");
assert_eq!(pos(&out[1]), (Severity::Error, "/p/src/B.java", 5, Some(14)));
assert_eq!(out[1].text, "需要 ';'");
assert_eq!(pos(&out[2]), (Severity::Warning, "/p/src/C.java", 8, Some(5)));
assert_eq!(out[2].text, "[deprecation] old() 已过时");
}
#[test]
fn gradle_kotlin() {
let out = parse(
+353 -59
View File
@@ -1,4 +1,4 @@
//! Single-file Java compilation with `javac` for the Compile File action (#2476).
//! Single-file Java compilation with `javac` for the Recompile action (#2476).
//!
//! A module build (`-pl … -am`) still walks every upstream module, and packaging
//! walks the whole reactor; compiling one file only needs that file's module
@@ -6,12 +6,93 @@
use super::*;
use serde::{Deserialize, Serialize};
use std::fs;
use std::process::Command as ProcCommand;
/// Output file of the `dependency:build-classpath` probe, relative to each module.
const CP_FILE: &str = "target/ide-compile-cp.txt";
// Older records include undeclared reactor test outputs even in runtime classpaths.
const CLASSPATH_CACHE_VERSION: u32 = 1;
const GRADLE_COMPILE_CP_INIT_SCRIPT: &str = include_str!("../gradle-compile-cp.init.gradle");
pub(super) fn is_java_file(file: &Path) -> IdeResult<String> {
if file.extension().is_none_or(|ext| !ext.eq_ignore_ascii_case("java")) {
return Err(IdeError::invalid("only Java sources can be compiled as a single file"));
}
if !file.is_file() {
return Err(IdeError::not_found("no Java source found for single-file compilation"));
}
Ok(file.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default())
}
pub(super) fn is_test_source(rel: &str) -> bool {
let parts: Vec<&str> = rel.split(['/', '\\']).collect();
parts.windows(2).any(|w| w == ["src", "test"])
}
pub(super) fn java_home_major(env: &BTreeMap<String, String>) -> Option<u32> {
let home = env.get("JAVA_HOME").filter(|h| !h.trim().is_empty())?;
let release = fs::read_to_string(Path::new(home).join("release")).ok()?;
let value = release.lines().find_map(|l| l.trim().strip_prefix("JAVA_VERSION="))?;
let value = value.trim().trim_matches(['"', '\'']);
language_release(value)
}
/// `--release N` from JDK 9 on; older compilers only know `-source` / `-target`.
pub(super) fn release_args(level: Option<u32>, jdk_major: Option<u32>) -> Vec<String> {
let Some(level) = level else { return Vec::new() };
if jdk_major.is_none_or(|m| m >= 9) {
vec!["--release".into(), level.to_string()]
} else {
vec!["-source".into(), format!("1.{level}"), "-target".into(), format!("1.{level}")]
}
}
pub(super) fn join_classpath(entries: impl IntoIterator<Item = String>) -> String {
let separator = if cfg!(windows) { ";" } else { ":" };
let mut seen = HashSet::new();
let mut out = Vec::new();
for entry in entries {
if !entry.is_empty() && seen.insert(entry.clone()) {
out.push(entry);
}
}
out.join(separator)
}
#[allow(clippy::too_many_arguments)]
pub(super) fn build_javac_step(
javac: &str,
cwd: &Path,
out_dir: &Path,
classpath: &str,
sources: &[PathBuf],
release: Vec<String>,
file: &Path,
env: BTreeMap<String, String>,
) -> IdeResult<BuildStep> {
fs::create_dir_all(out_dir)
.map_err(|e| IdeError::internal(format!("cannot create {} ({e})", out_dir.display())))?;
// Raw `javac` prints `path:line: error: …`, the same form Gradle forwards.
let mut step = BuildStep::new(javac, &[], cwd, Format::Gradle);
step.args.extend(["-encoding".into(), "UTF-8".into(), "-g".into()]);
step.args.extend(["-d".into(), out_dir.to_string_lossy().into_owned()]);
if !classpath.is_empty() {
step.args.extend(["-cp".into(), classpath.to_owned()]);
}
// Classes of the module that were never built (or are older than their source) are read
// from its sources; only `file` is written, so a test compile never puts main classes
// into test-classes.
if !sources.is_empty() {
let separator = if cfg!(windows) { ";" } else { ":" };
step.args.push("-sourcepath".into());
step.args.push(sources.iter().map(|p| p.to_string_lossy()).collect::<Vec<_>>().join(separator));
step.args.push("-implicit:none".into());
}
step.args.extend(release);
step.args.push(file.to_string_lossy().into_owned());
step.env = env;
step.mkdirs = vec![out_dir.to_path_buf()];
Ok(step)
}
/// The resolved dependency classpath for one module and scope, tied to the same
/// inputs as its launch build so POM, JDK, settings and profile changes invalidate it.
@@ -41,12 +122,7 @@ pub struct SingleFileTarget {
/// Locates the linked Maven module owning a `.java` source file.
pub fn single_file_target(root: &Path, model: &BuildModel, file: &Path) -> IdeResult<SingleFileTarget> {
if file.extension().is_none_or(|ext| ext != "java") {
return Err(IdeError::invalid("only Java sources can be compiled as a single file"));
}
if !file.is_file() {
return Err(IdeError::not_found("no Java source found for single-file compilation"));
}
is_java_file(file)?;
let Some(m) = &model.maven else {
return Err(IdeError::not_found("no linked Maven project found for module"));
};
@@ -70,8 +146,7 @@ pub fn single_file_target(root: &Path, model: &BuildModel, file: &Path) -> IdeRe
let top_dir = subdir(root, &top.dir);
let pl = module.strip_prefix(&top_dir).map(|r| r.to_string_lossy().replace('\\', "/")).unwrap_or_default();
// Test sources see the test classpath and compile into test classes.
let parts: Vec<&str> = rel.split('/').collect();
let test = parts.windows(2).any(|w| w == ["src", "test"]);
let test = is_test_source(&rel);
let out_dir = module.join("target").join(if test { "test-classes" } else { "classes" });
Ok(SingleFileTarget { module, test, out_dir, top: top.clone(), pl, java_version: project.java_version })
}
@@ -112,7 +187,17 @@ pub fn find_javac(env: &BTreeMap<String, String>) -> String {
/// `mvn dependency:build-classpath` (which resolves without compiling anything,
/// so `-am` stays cheap). Entries are platform-separated (`;` on Windows).
pub fn single_file_classpath(root: &Path, model: &BuildModel, target: &SingleFileTarget) -> IdeResult<String> {
classpath(root, model, target, "test", false)
single_file_classpath_cancellable(root, model, target, &CancellationToken::new())
}
fn single_file_classpath_cancellable(
root: &Path,
model: &BuildModel,
target: &SingleFileTarget,
cancel: &CancellationToken,
) -> IdeResult<String> {
let scope = if target.test { "test" } else { "compile" };
classpath(root, model, target, scope, false, cancel)
}
/// Runtime (or test) dependency classpath for a launch module.
@@ -172,10 +257,12 @@ pub fn module_classpaths(
}
let scope = if test { "test" } else { "runtime" };
let targets: Vec<&SingleFileTarget> = probes.iter().map(|p| &p.0).collect();
let classpaths = match classpaths(root, model, &targets, scope, true) {
let classpaths = match classpaths(root, model, &targets, scope, true, cancel) {
Ok(classpaths) => classpaths,
// Another module's failure must not cost this launch its own probe.
Err(_) if targets.len() > 1 && !cancel.is_cancelled() => classpaths(root, model, &targets[..1], scope, true)?,
Err(_) if targets.len() > 1 && !cancel.is_cancelled() => {
classpaths(root, model, &targets[..1], scope, true, cancel)?
}
Err(e) => return Err(e),
};
if cancel.is_cancelled() {
@@ -236,8 +323,9 @@ fn classpath(
target: &SingleFileTarget,
scope: &str,
compile_first: bool,
cancel: &CancellationToken,
) -> IdeResult<String> {
Ok(classpaths(root, model, &[target], scope, compile_first)?.pop().unwrap())
Ok(classpaths(root, model, &[target], scope, compile_first, cancel)?.pop().unwrap())
}
/// The classpath of each of `targets` (modules of one reactor) from one Maven probe.
@@ -247,6 +335,7 @@ fn classpaths(
targets: &[&SingleFileTarget],
scope: &str,
compile_first: bool,
cancel: &CancellationToken,
) -> IdeResult<Vec<String>> {
let top = &targets[0].top;
let probe = CP_FILE;
@@ -274,16 +363,17 @@ fn classpaths(
}
args.extend(["dependency:build-classpath", output_arg.as_str(), scope_arg.as_str(), "-q"]);
let top_dir = subdir(root, &top.dir);
let mut command = ProcCommand::new(&top.command);
command.args(&args).envs(&top.env).current_dir(&top_dir);
let status = ide_core::process::prepare(&mut command)
.output()
.map_err(|e| IdeError::internal(format!("cannot resolve the compile classpath: {e}")))?;
if !status.status.success() {
let stdout = String::from_utf8_lossy(&status.stdout);
let stderr = String::from_utf8_lossy(&status.stderr);
let owned_args: Vec<String> = args.into_iter().map(str::to_owned).collect();
let out = process::run_bounded(&top.command, &owned_args, &top_dir, &top.env, cancel, |_, _| {}).map_err(|e| {
if e.kind == ide_core::error::ErrorKind::Cancelled {
e
} else {
IdeError::internal(format!("cannot resolve the compile classpath: {}", e.message))
}
})?;
if !out.success {
// Maven reports reactor/dependency failures on stdout, not only stderr.
let tail: Vec<&str> = stdout.lines().chain(stderr.lines()).filter(|l| !l.trim().is_empty()).collect();
let tail: Vec<&str> = out.text.lines().filter(|l| !l.trim().is_empty()).collect();
let tail = tail.iter().rev().take(5).rev().cloned().collect::<Vec<_>>().join("\n");
return Err(IdeError::internal(format!("cannot resolve the compile classpath:\n{tail}")));
}
@@ -325,39 +415,14 @@ fn target_classpath(root: &Path, model: &BuildModel, target: &SingleFileTarget)
})?;
let separator = if cfg!(windows) { ';' } else { ':' };
entries.extend(content.split([separator, '\n', '\r']).map(str::trim).filter(|e| !e.is_empty()).map(str::to_owned));
entries.dedup();
Ok(entries.join(&separator.to_string()))
Ok(join_classpath(entries))
}
/// The `javac` step compiling `file` into `target`'s output directory.
pub fn javac_step(target: &SingleFileTarget, file: &Path, classpath: &str, javac: &str) -> IdeResult<BuildStep> {
fs::create_dir_all(&target.out_dir)
.map_err(|e| IdeError::internal(format!("cannot create {} ({e})", target.out_dir.display())))?;
let mut step = BuildStep::new(javac, &[], &target.module, Format::Gradle);
// Raw `javac` prints `path:line: error: …`, the same form Gradle forwards.
step.args.push("-encoding".into());
step.args.push("UTF-8".into());
step.args.push("-d".into());
step.args.push(target.out_dir.to_string_lossy().into_owned());
step.args.push("-cp".into());
step.args.push(classpath.to_owned());
// Classes of the module that were never built (or are older than their source) are read
// from its sources; only `file` is written, so a test compile never puts main classes
// into test-classes.
let sources = source_roots(target);
if !sources.is_empty() {
let separator = if cfg!(windows) { ";" } else { ":" };
step.args.push("-sourcepath".into());
step.args.push(sources.iter().map(|p| p.to_string_lossy()).collect::<Vec<_>>().join(separator));
step.args.push("-implicit:none".into());
}
if let Some(version) = target.java_version {
step.args.push("--release".into());
step.args.push(version.to_string());
}
step.args.push(file.to_string_lossy().into_owned());
step.env = target.top.env.clone();
Ok(step)
let release = release_args(target.java_version, java_home_major(&target.top.env));
build_javac_step(javac, &target.module, &target.out_dir, classpath, &sources, release, file, target.top.env.clone())
}
/// The module's Java source folders that exist, generated ones included; test sources see
@@ -383,8 +448,18 @@ fn source_roots(target: &SingleFileTarget) -> Vec<PathBuf> {
/// Resolves the classpath and plans the `javac` invocation for one Java source.
pub fn compile_file_plan(root: &Path, model: &BuildModel, file: &Path) -> IdeResult<BuildPlan> {
compile_file_plan_cancellable(root, model, file, &CancellationToken::new())
}
/// Cancellable [`compile_file_plan`].
pub fn compile_file_plan_cancellable(
root: &Path,
model: &BuildModel,
file: &Path,
cancel: &CancellationToken,
) -> IdeResult<BuildPlan> {
let target = single_file_target(root, model, file)?;
let classpath = single_file_classpath(root, model, &target)?;
let classpath = single_file_classpath_cancellable(root, model, &target, cancel)?;
let javac = find_javac(&target.top.env);
let name = file.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
Ok(BuildPlan {
@@ -394,6 +469,140 @@ pub fn compile_file_plan(root: &Path, model: &BuildModel, file: &Path) -> IdeRes
})
}
fn gradle_for_file<'a>(
root: &Path,
model: &'a BuildModel,
file: &Path,
) -> Option<(&'a crate::GradleModel, &'a crate::GradleProject, PathBuf)> {
let file = normalize(file);
let file_ref = &file;
model
.gradle
.iter()
.flat_map(|g| {
let g_dir = normalize(&subdir(root, &g.dir));
let g_depth = g_dir.components().count();
g.projects.iter().filter_map(move |p| {
let p_dir = normalize(&subdir(root, &p.dir));
file_ref.starts_with(&p_dir).then_some((g, p, p_dir, g_depth))
})
})
.max_by_key(|(_, _, p_dir, g_depth)| (p_dir.components().count(), *g_depth))
.map(|(g, p, p_dir, _)| (g, p, p_dir))
}
/// Whether `file` lies inside a linked Gradle project of `model`.
pub fn has_gradle_file_target(root: &Path, model: &BuildModel, file: &Path) -> bool {
gradle_for_file(root, model, file).is_some()
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct GradleCompileCp {
out_dir: Option<String>,
#[serde(default)]
classpath: Vec<String>,
#[serde(default)]
src_dirs: Vec<String>,
release: Option<u32>,
}
/// Resolves the compile classpath from Gradle and plans a single-file `javac` step.
pub fn gradle_compile_file_plan(
root: &Path,
model: &BuildModel,
file: &Path,
cache: &Path,
cancel: &CancellationToken,
) -> IdeResult<BuildPlan> {
let name = is_java_file(file)?;
let (gradle, project, module_dir) = gradle_for_file(root, model, file)
.ok_or_else(|| IdeError::not_found("no linked Gradle project found for file"))?;
let rel = rel_str(&module_dir, file);
let test = is_test_source(&rel);
let scope = if test { "test" } else { "main" };
fs::create_dir_all(cache)?;
let init_script = cache.join("gradle-compile-cp.init.gradle");
fs::write(&init_script, GRADLE_COMPILE_CP_INIT_SCRIPT)?;
let args = vec![
"--console=plain".into(),
"-q".into(),
"-Dorg.gradle.configuration-cache=false".into(),
"--init-script".into(),
init_script.to_string_lossy().into_owned(),
format!("-Popenidea.target={}", project.path),
format!("-Popenidea.scope={scope}"),
"help".into(),
];
let gradle_dir = subdir(root, &gradle.dir);
let mut reported: Option<String> = None;
let out = process::run_bounded(&gradle.command, &args, &gradle_dir, &gradle.env, cancel, |_, line| {
if let Some(json) = line.strip_prefix("@openidea-compile-cp\t") {
reported = Some(json.to_owned());
}
})
.map_err(|e| {
if e.kind == ide_core::error::ErrorKind::Cancelled {
e
} else {
IdeError::internal(format!("cannot resolve the compile classpath: {}", e.message))
}
})?;
if !out.success {
let tail: Vec<&str> = out.text.lines().filter(|l| !l.trim().is_empty()).collect();
let tail = tail.iter().rev().take(5).rev().cloned().collect::<Vec<_>>().join("\n");
return Err(IdeError::internal(format!("cannot resolve the compile classpath:\n{tail}")));
}
let json = reported.ok_or_else(|| {
IdeError::internal(format!(
"cannot resolve the compile classpath: Gradle did not report source set '{scope}' for {}",
project.path
))
})?;
let cp: GradleCompileCp = serde_json::from_str(&json)
.map_err(|e| IdeError::internal(format!("cannot parse Gradle compile classpath: {e}")))?;
let out_dir = cp
.out_dir
.filter(|d| !d.trim().is_empty())
.map(PathBuf::from)
.unwrap_or_else(|| module_dir.join("build/classes/java").join(scope));
let mut cp_entries: Vec<String> = Vec::new();
if out_dir.is_dir() {
cp_entries.push(out_dir.to_string_lossy().into_owned());
}
if test {
let main_out = module_dir.join("build/classes/java/main");
if main_out.is_dir() {
cp_entries.push(main_out.to_string_lossy().into_owned());
}
}
for sibling in &gradle.projects {
let sibling_dir = subdir(root, &sibling.dir);
if sibling_dir == module_dir {
continue;
}
let classes = sibling_dir.join("build/classes/java/main");
if classes.is_dir() {
cp_entries.push(classes.to_string_lossy().into_owned());
}
}
cp_entries.extend(cp.classpath);
let classpath = join_classpath(cp_entries);
let mut sources: Vec<PathBuf> = cp.src_dirs.into_iter().map(PathBuf::from).filter(|p| p.is_dir()).collect();
if sources.is_empty() {
let fallback: &[&str] = if test { &["src/test/java", "src/main/java"] } else { &["src/main/java"] };
sources.extend(fallback.iter().map(|s| module_dir.join(s)).filter(|p| p.is_dir()));
}
let javac = find_javac(&gradle.env);
let release = release_args(cp.release.or(gradle.java_version), java_home_major(&gradle.env));
let step =
build_javac_step(&javac, &module_dir, &out_dir, &classpath, &sources, release, file, gradle.env.clone())?;
Ok(BuildPlan { system: BuildSystem::Gradle, title: format!("Compile {name}"), steps: vec![step] })
}
#[cfg(test)]
mod tests {
use super::*;
@@ -439,7 +648,8 @@ mod tests {
#[test]
fn target_finds_the_owning_module_and_the_test_scope() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
let root_buf = dunce::canonicalize(dir.path()).unwrap();
let root = root_buf.as_path();
let model = fixture(root);
let main = single_file_target(root, &model, &root.join("app/src/main/java/demo/Main.java")).unwrap();
assert_eq!(main.module, root.join("app"));
@@ -453,7 +663,8 @@ mod tests {
#[test]
fn target_rejects_non_java_missing_and_unlinked_files() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
let root_buf = dunce::canonicalize(dir.path()).unwrap();
let root = root_buf.as_path();
let model = fixture(root);
write(root, "app/pom.xml", "<project/>");
assert!(single_file_target(root, &model, &root.join("app/pom.xml")).is_err());
@@ -465,7 +676,8 @@ mod tests {
#[test]
fn javac_prefers_the_module_jdk_and_scopes_test_sources() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
let root_buf = dunce::canonicalize(dir.path()).unwrap();
let root = root_buf.as_path();
let model = fixture(root);
let file = root.join("app/src/test/java/demo/MainTest.java");
let target = single_file_target(root, &model, &file).unwrap();
@@ -501,7 +713,8 @@ mod tests {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
let root_buf = dunce::canonicalize(dir.path()).unwrap();
let root = root_buf.as_path();
fixture(root);
let script = root.join("mvnw");
fs::write(
@@ -532,6 +745,7 @@ mod tests {
assert!(cp.split(separator).count() >= 3, "{cp}");
let args = fs::read_to_string(root.join("args.txt")).unwrap();
assert!(!args.lines().any(|a| a == "compile" || a == "package"), "{args}");
assert!(args.lines().any(|a| a == "-Dmdep.includeScope=compile"), "{args}");
fs::create_dir_all(root.join("app/target/test-classes")).unwrap();
let target = single_file_target(root, &model, &root.join("app/src/test/java/demo/MainTest.java")).unwrap();
let cp = single_file_classpath(root, &model, &target).unwrap();
@@ -539,6 +753,8 @@ mod tests {
assert_eq!(paths[0], root.join("app/target/test-classes"));
assert!(paths.contains(&root.join("app/target/classes")), "{cp}");
assert!(!paths.contains(&root.join("lib/target/test-classes")), "{cp}");
let args = fs::read_to_string(root.join("args.txt")).unwrap();
assert!(args.lines().any(|a| a == "-Dmdep.includeScope=test"), "{args}");
}
/// Launches request Maven's matching scope without adding reactor test outputs.
@@ -548,7 +764,8 @@ mod tests {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
let root_buf = dunce::canonicalize(dir.path()).unwrap();
let root = root_buf.as_path();
fixture(root);
let script = root.join("mvnw");
fs::write(
@@ -605,7 +822,8 @@ mod tests {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
let root_buf = dunce::canonicalize(dir.path()).unwrap();
let root = root_buf.as_path();
fixture(root);
write(root, "lib/src/main/java/demo/Lib.java", "class Lib {}");
let script = root.join("mvnw");
@@ -646,7 +864,8 @@ mod tests {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
let root_buf = dunce::canonicalize(dir.path()).unwrap();
let root = root_buf.as_path();
fixture(root);
let script = root.join("mvnw");
// `dependency:build-classpath` reports reactor outputs as absolute paths. Keep
@@ -712,4 +931,79 @@ mod tests {
calls.push('x');
assert_eq!(fs::read_to_string(root.join("calls.txt")).unwrap(), calls);
}
#[test]
fn javac_step_omits_empty_classpath_and_uses_source_target_on_jdk_8() {
let dir = tempfile::tempdir().unwrap();
let root_buf = dunce::canonicalize(dir.path()).unwrap();
let root = root_buf.as_path();
let mut model = fixture(root);
let file = root.join("app/src/main/java/demo/Main.java");
let jdk8 = root.join("jdk8");
fs::create_dir_all(jdk8.join("bin")).unwrap();
fs::write(jdk8.join("release"), "JAVA_VERSION=\"1.8.0_372\"\n").unwrap();
let project = model.maven.as_mut().unwrap().projects.iter_mut().find(|p| p.dir == "app").unwrap();
project.java_version = Some(8);
let mut target = single_file_target(root, &model, &file).unwrap();
target.top.env.insert("JAVA_HOME".into(), jdk8.to_string_lossy().into_owned());
let step = javac_step(&target, &file, "", "javac").unwrap();
assert!(!step.args.iter().any(|a| a == "-cp"), "{:?}", step.args);
assert!(step.args.iter().any(|a| a == "-g"), "{:?}", step.args);
assert!(step.args.windows(4).any(|w| w == ["-source", "1.8", "-target", "1.8"]), "{:?}", step.args);
assert!(!step.args.iter().any(|a| a == "--release"), "{:?}", step.args);
}
#[cfg(unix)]
#[test]
fn gradle_single_file_compiles_with_source_set_classpath_and_siblings() {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().unwrap();
let root_buf = dunce::canonicalize(dir.path()).unwrap();
let root = root_buf.as_path();
write(root, "settings.gradle", "include ':lib', ':app'");
write(root, "lib/build.gradle", "plugins { id 'java' }");
write(root, "app/build.gradle", "plugins { id 'java' }");
write(root, "app/src/main/java/demo/App.java", "package demo; class App {}");
write(root, "app/src/test/java/demo/AppTest.java", "package demo; class AppTest {}");
fs::create_dir_all(root.join("lib/build/classes/java/main")).unwrap();
fs::create_dir_all(root.join("app/build/classes/java/main")).unwrap();
let wrapper = root.join("gradlew");
fs::write(
&wrapper,
"#!/bin/sh\nprintf '%s\\n' \"$@\" > gradle_args.txt\nscope='main'\nfor a in \"$@\"; do\ncase \"$a\" in -Popenidea.scope=*) scope=\"${a#-Popenidea.scope=}\" ;; esac\ndone\nprintf '@openidea-compile-cp\\t{\"outDir\":\"%s/app/build/classes/java/%s\",\"classpath\":[\"%s/deps/guava.jar\"],\"srcDirs\":[\"%s/app/src/%s/java\"],\"release\":17}\\n' \"$PWD\" \"$scope\" \"$PWD\" \"$PWD\" \"$scope\"\n",
)
.unwrap();
fs::set_permissions(&wrapper, fs::Permissions::from_mode(0o755)).unwrap();
let model = crate::load(root, &root.join("cache"), None);
let cache = root.join("cache");
let cancel = CancellationToken::new();
let main_file = root.join("app/src/main/java/demo/App.java");
let main_plan = gradle_compile_file_plan(root, &model, &main_file, &cache, &cancel).unwrap();
assert_eq!(main_plan.system, BuildSystem::Gradle);
assert_eq!(main_plan.title, "Compile App.java");
let step = &main_plan.steps[0];
let args = fs::read_to_string(root.join("gradle_args.txt")).unwrap();
assert!(args.lines().any(|a| a == "-Popenidea.target=:app"), "{args}");
assert!(args.lines().any(|a| a == "-Popenidea.scope=main"), "{args}");
let cp = &step.args[step.args.iter().position(|a| a == "-cp").unwrap() + 1];
let paths: Vec<_> = std::env::split_paths(cp).collect();
assert!(paths.contains(&root.join("app/build/classes/java/main")), "{cp}");
assert!(paths.contains(&root.join("lib/build/classes/java/main")), "{cp}");
assert!(paths.contains(&root.join("deps/guava.jar")), "{cp}");
assert!(step.args.windows(2).any(|w| w == ["--release", "17"]), "{:?}", step.args);
assert!(step.args.iter().any(|a| a == "-implicit:none"), "{:?}", step.args);
let test_file = root.join("app/src/test/java/demo/AppTest.java");
let test_plan = gradle_compile_file_plan(root, &model, &test_file, &cache, &cancel).unwrap();
assert_eq!(test_plan.title, "Compile AppTest.java");
let test_step = &test_plan.steps[0];
let args = fs::read_to_string(root.join("gradle_args.txt")).unwrap();
assert!(args.lines().any(|a| a == "-Popenidea.scope=test"), "{args}");
assert!(
test_step.args.windows(2).any(|w| w == ["-d", &root.join("app/build/classes/java/test").to_string_lossy()])
);
}
}
+157 -21
View File
@@ -162,16 +162,6 @@ fn classpath(entries: &[String]) -> String {
entries.join(if cfg!(windows) { ";" } else { ":" })
}
/// `--release N` from JDK 9 on; older compilers only know `-source` / `-target`.
fn release_args(level: Option<u32>, jdk: Option<&StructureJdk>) -> Vec<String> {
let Some(level) = level else { return Vec::new() };
if jdk.is_none_or(|j| j.major >= 9) {
vec!["--release".into(), level.to_string()]
} else {
vec!["-source".into(), format!("1.{level}"), "-target".into(), format!("1.{level}")]
}
}
/// `"17"`, `"1.8"`, `"JDK_17"` → the release number.
pub fn language_release(level: &str) -> Option<u32> {
let digits = level.trim().trim_start_matches("JDK_").trim_start_matches("jdk").replace('_', ".");
@@ -179,6 +169,25 @@ pub fn language_release(level: &str) -> Option<u32> {
digits.split(['.', ' ']).next()?.parse().ok().filter(|n| *n > 0)
}
fn structure_compiler(
root: &Path,
ps: &ProjectStructureSettings,
jdk: Option<&StructureJdk>,
language_level: &str,
) -> (Option<u32>, BTreeMap<String, String>, String) {
let module = root_module(root, ps);
let level = module
.map(|m| m.language_level.as_str())
.filter(|l| !l.trim().is_empty())
.or(Some(language_level))
.and_then(language_release);
let env: BTreeMap<String, String> = jdk
.map(|j| BTreeMap::from([("JAVA_HOME".to_owned(), j.home.to_string_lossy().into_owned())]))
.unwrap_or_default();
let javac = find_javac(&env);
(level, env, javac)
}
/// The Build / Rebuild plan of a project without a build tool, or `None` when it has no
/// Java sources under its source roots. `language_level`: the project's, unless the module
/// overrides it. Writes the javac argument files below `cache`.
@@ -203,16 +212,7 @@ pub fn structure_plan(
return Ok(None);
}
let (main_out, test_out) = structure_outputs(root, ps);
let module = root_module(root, ps);
let level = module
.map(|m| m.language_level.as_str())
.filter(|l| !l.trim().is_empty())
.or(Some(language_level))
.and_then(language_release);
let env: BTreeMap<String, String> = jdk
.map(|j| BTreeMap::from([("JAVA_HOME".to_owned(), j.home.to_string_lossy().into_owned())]))
.unwrap_or_default();
let javac = find_javac(&env);
let (level, env, javac) = structure_compiler(root, ps, jdk, language_level);
let args_dir = cache.join("javac");
fs::create_dir_all(&args_dir)
.map_err(|e| IdeError::internal(format!("cannot create {} ({e})", args_dir.display())))?;
@@ -241,7 +241,7 @@ pub fn structure_plan(
if !cp.is_empty() {
step.args.extend(["-cp".into(), classpath(cp)]);
}
step.args.extend(release_args(level, jdk));
step.args.extend(single::release_args(level, jdk.map(|j| j.major)));
step.args.push(format!("@{}", args_file.to_string_lossy()));
step.env = env.clone();
step.mkdirs = vec![out.to_path_buf()];
@@ -281,6 +281,47 @@ pub fn structure_plan(
Ok(Some(BuildPlan { system: BuildSystem::Javac, title: module_name(root), steps }))
}
/// Single-file `javac` plan for a Java project without a build tool (Project Structure).
pub fn structure_compile_file_plan(
root: &Path,
ps: &ProjectStructureSettings,
roots: &StructureRoots,
jdk: Option<&StructureJdk>,
language_level: &str,
file: &Path,
) -> IdeResult<BuildPlan> {
let name = single::is_java_file(file)?;
let rel = rel_str(root, file);
let test = if roots.tests.is_empty() {
single::is_test_source(&rel)
} else {
let file_norm = normalize(file);
roots.tests.iter().any(|t| file_norm.starts_with(normalize(t)))
};
let (main_out, test_out) = structure_outputs(root, ps);
let out_dir = if test { &test_out } else { &main_out };
let mut cp: Vec<String> = Vec::new();
if test && test_out.is_dir() {
cp.push(test_out.to_string_lossy().into_owned());
}
if main_out.is_dir() {
cp.push(main_out.to_string_lossy().into_owned());
}
cp.extend(library_entries(root, ps, test));
let cp = single::join_classpath(cp);
let mut src_roots: Vec<PathBuf> = Vec::new();
if test {
src_roots.extend(roots.tests.iter().filter(|p| p.is_dir()).cloned());
}
src_roots.extend(roots.sources.iter().filter(|p| p.is_dir()).cloned());
let (level, env, javac) = structure_compiler(root, ps, jdk, language_level);
let release = single::release_args(level, jdk.map(|j| j.major));
let step = single::build_javac_step(&javac, root, out_dir, &cp, &src_roots, release, file, env)?;
Ok(BuildPlan { system: BuildSystem::Javac, title: format!("Compile {name}"), steps: vec![step] })
}
/// Where an artifact goes: its output folder, else `out/artifacts/<name>`.
pub fn artifact_output(root: &Path, artifact: &ArtifactConfig) -> PathBuf {
resolve_dir(root, &artifact.output_directory)
@@ -1008,4 +1049,99 @@ mod tests {
layout(&["a.jar"]).run(&CancellationToken::new()).unwrap();
assert!(project.join("c.jar").is_file());
}
#[test]
fn plans_single_file_javac_for_main_test_and_jdk8() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().join("shop");
write(&root.join("src/com/a/Main.java"), "package com.a; class Main {}");
write(&root.join("test/com/a/MainTest.java"), "package com.a; class MainTest {}");
write(&root.join("out/production/shop/com/a/Helper.class"), "");
let ps = ProjectStructureSettings {
libraries: vec![
ProjectLibrary { name: "core".into(), classes: vec!["lib/core.jar".into()], ..Default::default() },
ProjectLibrary {
name: "junit".into(),
classes: vec!["lib/junit.jar".into()],
scope: DependencyScope::Test,
..Default::default()
},
],
..Default::default()
};
let roots =
StructureRoots { sources: vec![root.join("src")], tests: vec![root.join("test")], ..Default::default() };
let jdk21 = StructureJdk { home: PathBuf::from("/jdk21"), major: 21 };
let main_plan =
structure_compile_file_plan(&root, &ps, &roots, Some(&jdk21), "17", &root.join("src/com/a/Main.java"))
.unwrap();
assert_eq!(main_plan.system, BuildSystem::Javac);
assert_eq!(main_plan.title, "Compile Main.java");
let main_step = &main_plan.steps[0];
let cp = &main_step.args[main_step.args.iter().position(|a| a == "-cp").unwrap() + 1];
assert!(cp.contains("core.jar") && !cp.contains("junit.jar"), "{cp}");
assert!(main_step.args.windows(2).any(|w| w == ["--release", "17"]));
assert!(main_step.args.iter().any(|a| a == "-implicit:none"));
let jdk8 = StructureJdk { home: PathBuf::from("/jdk8"), major: 8 };
let test_plan =
structure_compile_file_plan(&root, &ps, &roots, Some(&jdk8), "8", &root.join("test/com/a/MainTest.java"))
.unwrap();
let test_step = &test_plan.steps[0];
let test_cp = &test_step.args[test_step.args.iter().position(|a| a == "-cp").unwrap() + 1];
assert!(test_cp.contains("out/production/shop") || test_cp.contains("out\\production\\shop"), "{test_cp}");
assert!(test_cp.contains("junit.jar"), "{test_cp}");
assert!(test_step.args.windows(4).any(|w| w == ["-source", "1.8", "-target", "1.8"]));
assert!(test_step.args.windows(2).any(|w| w[0] == "-d" && Path::new(&w[1]).ends_with("out/test/shop")));
}
#[test]
fn compiles_only_the_target_java_file_and_reports_errors() {
let exe = if cfg!(windows) { "javac.exe" } else { "javac" };
if !std::process::Command::new(exe).arg("-version").output().is_ok_and(|o| o.status.success()) {
return;
}
let tmp = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(tmp.path()).unwrap().join("demo");
let good = root.join("src/p/Good.java");
let broken_sibling = root.join("src/p/BrokenSibling.java");
let bad_target = root.join("src/p/BadTarget.java");
write(&good, "package p;\npublic class Good { public static int ok() { return 1; } }\n");
write(&broken_sibling, "package p;\npublic class BrokenSibling { MissingType field; }\n");
write(&bad_target, "package p;\npublic class BadTarget {\n UnknownSymbol field;\n}\n");
let ps = ProjectStructureSettings::default();
let roots = StructureRoots { sources: vec![root.join("src")], ..Default::default() };
let cancel = CancellationToken::new();
// 1. Valid file compiles cleanly without touching or failing on BrokenSibling.java.
let plan = structure_compile_file_plan(&root, &ps, &roots, None, "", &good).unwrap();
let events = std::sync::Mutex::new(Vec::new());
let result = run(&root, &plan, &cancel, &|e| events.lock().unwrap().push(e)).unwrap();
assert!(result.success, "expected single-file compile to succeed: {:?}", result.messages);
assert_eq!(result.errors, 0);
assert!(root.join("out/production/demo/p/Good.class").is_file());
assert!(!root.join("out/production/demo/p/BrokenSibling.class").exists());
// 2. Broken target fails, streams raw compiler output, and produces structured diagnostics.
let plan = structure_compile_file_plan(&root, &ps, &roots, None, "", &bad_target).unwrap();
let bad_events = std::sync::Mutex::new(Vec::new());
let bad_result = run(&root, &plan, &cancel, &|e| bad_events.lock().unwrap().push(e)).unwrap();
assert!(!bad_result.success);
assert!(bad_result.errors >= 1, "{bad_result:?}");
assert!(
bad_events.lock().unwrap().iter().any(|e| matches!(e, BuildEvent::Output { .. })),
"expected streamed output"
);
assert!(
bad_result.messages.iter().any(|m| {
m.severity == Severity::Error
&& m.path.as_ref().is_some_and(|p| <ide_core::IpcPath as AsRef<Path>>::as_ref(p) == bad_target)
&& m.range.is_some_and(|r| r.start.line == 2)
}),
"messages={:?}",
bad_result.messages
);
}
}
@@ -0,0 +1,58 @@
// OpenIDEA single-file javac classpath probe for Gradle projects.
// Prints the target source set's output directory, compile classpath, source dirs and release version.
import groovy.json.JsonOutput
def identity = { Project p -> try { p.identityPath.toString() } catch (ignored) { p.path } }
gradle.projectsEvaluated { g ->
def wantedTarget = g.rootProject.findProperty('openidea.target')?.toString() ?: ':'
def scope = g.rootProject.findProperty('openidea.scope')?.toString() ?: 'main'
def project = g.rootProject.allprojects.find { identity(it) == wantedTarget }
if (project == null && g.parent == null) {
project = g.rootProject.allprojects.find { it.path == wantedTarget }
}
if (project == null) return
def sets = project.extensions.findByName('sourceSets') ?: project.findProperty('sourceSets')
def ss = sets?.findByName(scope)
if (ss == null) return
def outDir = null
try { outDir = ss.java.destinationDirectory.get().asFile.canonicalPath } catch (ignored) {}
if (outDir == null) {
try { outDir = ss.output.classesDirs.files.iterator().next().canonicalPath } catch (ignored) {}
}
def cp = []
if (scope == 'test') {
def mainSet = sets.findByName('main')
try { mainSet?.output?.classesDirs?.files?.each { cp << it.canonicalPath } } catch (ignored) {}
}
try { ss.compileClasspath.files.each { cp << it.canonicalPath } } catch (ignored) {}
cp = cp.unique()
def srcDirs = []
try { ss.java.srcDirs.each { srcDirs << it.canonicalPath } } catch (ignored) {}
if (scope == 'test') {
def mainSet = sets.findByName('main')
try { mainSet?.java?.srcDirs?.each { srcDirs << it.canonicalPath } } catch (ignored) {}
}
srcDirs = srcDirs.unique()
def release = null
try {
def compileTask = project.tasks.findByName(ss.compileJavaTaskName)
release = compileTask?.options?.release?.getOrNull()
} catch (ignored) {}
if (release == null) {
try {
def java = project.extensions.findByName('java')
def lv = null
try { lv = java?.toolchain?.languageVersion?.getOrNull() } catch (ignored) {}
def target = java != null ? java.targetCompatibility : project.findProperty('targetCompatibility')
release = lv != null ? lv.asInt() : (target?.majorVersion as Integer)
} catch (ignored) {}
}
println '@openidea-compile-cp\t' + JsonOutput.toJson([outDir: outDir, classpath: cp, srcDirs: srcDirs, release: release])
}
+25
View File
@@ -336,6 +336,7 @@ pub struct CodeEditingSettings {
/// Next / previous error goes to errors only (skips warnings).
pub next_error_errors_only: bool,
pub sticky_lines_max: u32,
pub sticky_lines_disabled_languages: Vec<String>,
}
impl Default for CodeEditingSettings {
@@ -348,6 +349,7 @@ impl Default for CodeEditingSettings {
quick_doc_delay: 500,
next_error_errors_only: true,
sticky_lines_max: 5,
sticky_lines_disabled_languages: Vec::new(),
}
}
}
@@ -473,6 +475,12 @@ pub struct LanguageCodeStyle {
/// PHP: align `=` of consecutive assignment statements after formatting.
#[serde(skip_serializing_if = "Option::is_none")]
pub align_consecutive_assignments: Option<bool>,
/// SQL › Case › Keywords: `upper` | `lower` | `keep` (other languages ignore it).
#[serde(skip_serializing_if = "Option::is_none")]
pub keyword_case: Option<String>,
/// SQL › Case › Identifiers (unquoted names): `upper` | `lower` | `keep`.
#[serde(skip_serializing_if = "Option::is_none")]
pub identifier_case: Option<String>,
}
/// Editor › Code Style (General tab + per-language overrides).
@@ -585,3 +593,20 @@ mod folding_tests {
}
}
}
#[cfg(test)]
mod sticky_lines_tests {
use super::CodeEditingSettings;
#[test]
fn sticky_lines_language_exclusions_round_trip_and_default_to_empty() {
let old: CodeEditingSettings = serde_json::from_value(serde_json::json!({"stickyLinesMax": 3})).unwrap();
assert_eq!(old.sticky_lines_max, 3);
assert!(old.sticky_lines_disabled_languages.is_empty());
let json = serde_json::json!(["markdown", "rust"]);
let saved: CodeEditingSettings =
serde_json::from_value(serde_json::json!({"stickyLinesDisabledLanguages": json})).unwrap();
assert_eq!(saved.sticky_lines_disabled_languages, ["markdown", "rust"]);
assert_eq!(serde_json::to_value(saved).unwrap()["stickyLinesDisabledLanguages"], json);
}
}
+19 -2
View File
@@ -402,12 +402,14 @@ mod windows_job {
use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle, RawHandle};
use windows_sys::Win32::Foundation::{ERROR_MORE_DATA, INVALID_HANDLE_VALUE};
use windows_sys::Win32::System::JobObjects::{
AssignProcessToJobObject, CreateJobObjectW, JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE,
AssignProcessToJobObject, CreateJobObjectW, IsProcessInJob, JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE,
JOBOBJECT_BASIC_LIMIT_INFORMATION, JOBOBJECT_BASIC_PROCESS_ID_LIST, JOBOBJECT_EXTENDED_LIMIT_INFORMATION,
JobObjectBasicProcessIdList, JobObjectExtendedLimitInformation, QueryInformationJobObject,
SetInformationJobObject, TerminateJobObject,
};
use windows_sys::Win32::System::Threading::{IO_COUNTERS, OpenProcess, PROCESS_SET_QUOTA, PROCESS_TERMINATE};
use windows_sys::Win32::System::Threading::{
IO_COUNTERS, OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION, PROCESS_SET_QUOTA, PROCESS_TERMINATE,
};
/// A job object holding one launch's processes. The handle is kept open for the
/// launch's lifetime: `KILL_ON_JOB_CLOSE` ends anything still in the job when the
@@ -510,6 +512,21 @@ mod windows_job {
ok != 0
}
/// Whether the running process belongs to this specific launch's job.
pub fn contains_pid(&self, pid: u32) -> bool {
// SAFETY: a non-null result is a process handle owned by this call.
let handle = unsafe { OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid) };
if handle.is_null() {
return false;
}
// SAFETY: the process handle was just opened above and the job handle is owned here.
let handle = unsafe { OwnedHandle::from_raw_handle(handle) };
let mut contained = 0;
// SAFETY: both handles remain valid and `contained` is a writable BOOL.
(unsafe { IsProcessInJob(handle.as_raw_handle(), self.0.as_raw_handle(), &mut contained) }) != 0
&& contained != 0
}
/// Terminates every process in the job. `false` when the call failed (the job
/// handle is invalid): callers then fall back to `taskkill /T /F`. Termination is
/// asynchronous; poll [`Job::is_running`] (bounded by [`TREE_EXIT_WAIT`]) until
+2
View File
@@ -941,6 +941,8 @@ pub struct FileIconThemeOptions {
#[serde(default, rename_all = "camelCase")]
pub struct MainToolbarSettings {
pub left: Vec<String>,
/// Centred in the toolbar (between the other two groups when they leave too little room).
pub center: Vec<String>,
pub right: Vec<String>,
/// Widgets the user removed.
pub hidden: Vec<String>,
+28
View File
@@ -460,6 +460,16 @@ impl Default for ConsoleSettings {
}
}
/// Whether compiled classes are reloaded into running Java debug sessions after compilation.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum HotSwapPolicy {
#[default]
Ask,
Always,
Never,
}
/// Build, Execution, Deployment › Debugger (+ Data Views, Stepping, Python Debugger).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
@@ -487,6 +497,8 @@ pub struct DebuggerSettings {
pub debug_server_page: bool,
/// Flutter: saving a Dart file of a running debug session hot reloads the app.
pub flutter_hot_reload_on_save: bool,
/// Java: whether to reload changed classes into running debug sessions after compilation.
pub hot_swap_after_compile: HotSwapPolicy,
pub python: PythonDebuggerSettings,
}
@@ -508,6 +520,7 @@ impl Default for DebuggerSettings {
skip_library_code: true,
debug_server_page: false,
flutter_hot_reload_on_save: true,
hot_swap_after_compile: HotSwapPolicy::Ask,
python: PythonDebuggerSettings::default(),
}
}
@@ -718,4 +731,19 @@ mod tests {
let off: GitSettings = serde_json::from_str(r#"{"syncBranchOperations":false}"#).unwrap();
assert!(!off.sync_branch_operations);
}
#[test]
fn debugger_hotswap_after_compile_defaults_to_ask_and_roundtrips() {
let missing: DebuggerSettings = serde_json::from_str("{}").unwrap();
assert_eq!(missing.hot_swap_after_compile, HotSwapPolicy::Ask);
for (raw, expected) in
[("ask", HotSwapPolicy::Ask), ("always", HotSwapPolicy::Always), ("never", HotSwapPolicy::Never)]
{
let parsed: DebuggerSettings =
serde_json::from_str(&format!(r#"{{"hotSwapAfterCompile":"{raw}"}}"#)).unwrap();
assert_eq!(parsed.hot_swap_after_compile, expected);
let serialized = serde_json::to_value(&parsed).unwrap();
assert_eq!(serialized["hotSwapAfterCompile"], raw);
}
}
}
+27 -1
View File
@@ -1,5 +1,6 @@
//! Class-table snapshots of a debugged JVM, read over the HotSpot attach listener or, where
//! that is unavailable, counted by the debugger; and the JVM's objects through the debugger.
//! that is unavailable, counted by the debugger; the JVM's objects through the debugger; and
//! its thread dumps.
mod fallback;
mod heap;
@@ -10,6 +11,7 @@ mod snapshot;
pub(crate) mod test_support;
#[cfg(test)]
mod tests;
mod threads;
use crate::session::Session;
use crate::session::Suspension;
@@ -28,6 +30,8 @@ pub(crate) use inspect::{fields, instances, referrers, set_inspector, vm_target,
pub(crate) use scan::watch_for_attached_jvm;
pub(crate) use scan::{JvmFinder, attach_target, find_attached_jvm, find_local_jvm, local_jdwp_port};
use snapshot::{AttachProbe, JdkProbe, take_snapshot};
pub use threads::{JvmThreadDump, JvmThreadsResult, JvmThreadsUnavailable, run_jvm_thread_dump};
pub(crate) use threads::{debugged_run_thread_dump, session_thread_dump};
pub const JVM_MEMORY_ADAPTERS: &[&str] = &["java-debug", crate::kotlin::ADAPTER, crate::kotlin_lsp::ADAPTER];
pub const HISTOGRAM_TIMEOUT: Duration = Duration::from_secs(10);
@@ -190,6 +194,25 @@ fn histogram_pid(session: &Session) -> Result<Option<i32>, JvmMemoryUnavailable>
Ok(None)
}
/// Whether `session` is a JVM session attached to `run` that may hold `pid`: its JVM is `pid` or
/// not located yet.
pub(crate) fn attached_to_run(session: &Session, run: ide_core::RunId, pid: u32) -> bool {
let located = session.jvm_pid.load(Ordering::Acquire);
session.run == Some(run)
&& JVM_MEMORY_ADAPTERS.contains(&session.adapter.as_str())
&& !session.terminated.load(Ordering::Acquire)
&& (located <= 0 || located == i64::from(pid))
}
/// Whether `session` debugs the JVM `pid`: the program it launched or the JVM its attach found.
pub(crate) fn debugs_jvm(session: &Session, pid: u32) -> bool {
let jvm = if session.request == "launch" { launch_pid(session) } else { session.jvm_pid.load(Ordering::Acquire) };
JVM_MEMORY_ADAPTERS.contains(&session.adapter.as_str())
&& !session.terminated.load(Ordering::Acquire)
&& jvm > 0
&& jvm == i64::from(pid)
}
/// The JVM a launch session started: the one the IDE started for an app-launched (Kotlin)
/// session, else the program the adapter reported; 0 when neither is known.
pub(crate) fn launch_pid(session: &Session) -> i64 {
@@ -206,6 +229,8 @@ pub(crate) enum JvmTarget<'a> {
/// The JVM of an attach session. While `pid` is 0 it is looked up by `jdwp_port`, which is
/// `None` for a remote JVM.
Attached { pid: &'a AtomicI64, jdwp_port: Option<u16> },
/// A JVM the session debugs, found from outside it (in a run's process tree).
Known(i32),
/// Known without asking any JVM: no histogram can be taken, for this reason.
Unavailable(JvmMemoryUnavailable),
}
@@ -261,6 +286,7 @@ async fn histogram(
fn lookup(target: JvmTarget<'_>) -> Result<Lookup, JvmMemoryUnavailable> {
match target {
JvmTarget::Launched(pid) => Ok(Lookup::Tree(pid)),
JvmTarget::Known(pid) => Ok(Lookup::Known(pid)),
JvmTarget::Attached { pid, jdwp_port } => match i32::try_from(pid.load(Ordering::Acquire)) {
Ok(p) if p > 0 => Ok(Lookup::Known(p)),
_ => jdwp_port.map(Lookup::Scan).ok_or(JvmMemoryUnavailable::AttachedJvmNotFound),
+19 -1
View File
@@ -15,7 +15,8 @@ use std::time::Duration;
const VERSION_TIMEOUT: Duration = Duration::from_secs(2);
const FLAGS_TIMEOUT: Duration = Duration::from_secs(2);
/// The attach calls a snapshot or a heap dump makes, so tests can stand in for a JVM.
/// The attach calls a snapshot, a heap dump or a thread dump makes, so tests can stand in for a
/// JVM.
pub(crate) trait AttachProbe: Send + Sync {
fn has_listener(&self, pid: u32) -> bool;
/// Asks only the JVMs whose pid `may_query` accepts.
@@ -27,6 +28,11 @@ pub(crate) trait AttachProbe: Send + Sync {
fn heap_dump(&self, pid: u32, path: &Path, timeout: Duration) -> Result<HeapDumpReply, AttachError>;
/// `None` where the free space is not known.
fn free_bytes(&self, dir: &Path) -> Option<u64>;
fn thread_print(&self, pid: u32) -> Result<String, AttachError>;
/// Opens `pid`'s attach listener unless it runs; refuses a process not confirmed HotSpot.
fn ensure_listener(&self, pid: u32) -> Result<(), AttachError>;
/// Confirmed HotSpot and not one of Gradle's own JVMs; asks the JVM nothing.
fn is_application_jvm(&self, pid: u32) -> bool;
}
pub(super) struct JdkProbe {
@@ -73,6 +79,18 @@ impl AttachProbe for JdkProbe {
fn free_bytes(&self, dir: &Path) -> Option<u64> {
ide_heap::free_bytes(dir)
}
fn thread_print(&self, pid: u32) -> Result<String, AttachError> {
ide_jvm_attach::thread_print(pid, ide_jvm_attach::THREAD_DUMP_TIMEOUT)
}
fn ensure_listener(&self, pid: u32) -> Result<(), AttachError> {
ide_jvm_attach::ensure_listener(pid, ide_jvm_attach::LISTENER_START_TIMEOUT)
}
fn is_application_jvm(&self, pid: u32) -> bool {
ide_jvm_attach::is_application_jvm(pid)
}
}
fn alive(pid: u32) -> bool {
+361
View File
@@ -3,6 +3,7 @@ use super::heap::*;
use super::scan::*;
use super::snapshot::*;
use super::test_support::{BareSession, FakeInspector, bare_session, bare_session_of};
use super::threads::*;
use super::*;
use ide_core::CancellationToken;
use ide_jvm_attach::{AttachError, HeapDumpReply, HistogramRow, JavaVersion};
@@ -39,6 +40,13 @@ struct FakeProbe {
free: Option<u64>,
/// Answering this command stops the program: runs the hook.
stops_on: Option<(&'static str, StopHook)>,
thread_dumps: parking_lot::Mutex<VecDeque<Result<String, AttachError>>>,
/// Replies to `ensure_listener`, in order; `Ok` once empty.
listener_starts: parking_lot::Mutex<VecDeque<Result<(), AttachError>>>,
/// Pids `is_application_jvm` confirms.
application_jvms: Vec<u32>,
/// Pids `ensure_listener` was asked for.
ensured: parking_lot::Mutex<Vec<u32>>,
}
type StopHook = Box<dyn Fn() + Send + Sync>;
@@ -97,6 +105,10 @@ impl FakeProbe {
dump_bytes: 64,
free: None,
stops_on: None,
thread_dumps: parking_lot::Mutex::new(VecDeque::new()),
listener_starts: parking_lot::Mutex::new(VecDeque::new()),
application_jvms: Vec::new(),
ensured: parking_lot::Mutex::new(Vec::new()),
}
}
@@ -167,6 +179,20 @@ impl AttachProbe for FakeProbe {
fn free_bytes(&self, _dir: &Path) -> Option<u64> {
self.free
}
fn thread_print(&self, _pid: u32) -> Result<String, AttachError> {
self.enter("thread_print");
std::thread::sleep(self.delay);
self.leave();
self.thread_dumps.lock().pop_front().expect("unexpected thread dump request")
}
fn ensure_listener(&self, pid: u32) -> Result<(), AttachError> {
self.record("ensure_listener");
self.ensured.lock().push(pid);
self.listener_starts.lock().pop_front().unwrap_or(Ok(()))
}
fn is_application_jvm(&self, pid: u32) -> bool {
self.application_jvms.contains(&pid)
}
}
const FLAGS: &str = "-XX:+UseCompressedOops -XX:+StartAttachListener";
@@ -1160,6 +1186,341 @@ async fn jdk11_is_refused_while_the_link_is_suspended_before_dap_stops() {
assert!(!dir.exists());
}
const THREADS: &str = "Full thread dump OpenJDK 64-Bit Server VM (21.0.5+11-LTS mixed mode, sharing):\n\n\"main\" #1 [259] prio=5 os_prio=31 cpu=31.20ms elapsed=1.70s tid=0x1 nid=259 runnable [0x2]\n java.lang.Thread.State: RUNNABLE\n";
fn dumping_threads(listener: u32, dumps: Vec<Result<String, AttachError>>) -> FakeProbe {
let fake = FakeProbe::new(listener, Vec::new());
*fake.thread_dumps.lock() = dumps.into();
fake
}
fn threads_unavailable(r: JvmThreadsResult) -> JvmThreadsUnavailable {
match r {
JvmThreadsResult::Unavailable { reason } => reason,
other => panic!("{other:?}"),
}
}
fn threads_jvm(reason: JvmMemoryUnavailable) -> JvmThreadsUnavailable {
JvmThreadsUnavailable::Jvm { reason }
}
#[test]
fn threads_while_running_start_the_listener() {
let fake = dumping_threads(99, vec![Ok(THREADS.into())]);
let r = dump_threads(&fake, 12, false);
let JvmThreadsResult::Ready { dump } = r else { panic!("{r:?}") };
assert_eq!((dump.text.as_str(), dump.pid, dump.java_version.as_str()), (THREADS, 12, "21.0.5"));
assert!(!dump.taken_while_suspended);
assert_eq!(*fake.commands.lock(), ["ensure_listener", "thread_print"]);
}
#[test]
fn threads_while_suspended_without_listener_do_not_attach() {
let fake = dumping_threads(99, Vec::new());
assert_eq!(
threads_unavailable(dump_threads(&fake, 12, true)),
threads_jvm(JvmMemoryUnavailable::ListenerNotRunning)
);
assert!(fake.commands.lock().is_empty());
}
#[test]
fn threads_while_suspended_on_11_are_refused() {
let mut fake = dumping_threads(12, Vec::new());
fake.version = Some(JavaVersion { major: 11, text: "11.0.25".into() });
assert_eq!(
threads_unavailable(dump_threads(&fake, 12, true)),
threads_jvm(JvmMemoryUnavailable::UnsafeWhileSuspended { java_major: 11 })
);
fake.version = None;
assert_eq!(
threads_unavailable(dump_threads(&fake, 12, true)),
threads_jvm(JvmMemoryUnavailable::UnsafeWhileSuspended { java_major: 0 })
);
assert!(fake.commands.lock().is_empty());
}
#[test]
fn threads_while_suspended_on_17_use_the_running_listener() {
let mut fake = dumping_threads(12, vec![Ok(THREADS.into())]);
fake.version = Some(JavaVersion { major: 17, text: "17.0.13".into() });
let r = dump_threads(&fake, 12, true);
let JvmThreadsResult::Ready { dump } = r else { panic!("{r:?}") };
assert!(dump.taken_while_suspended);
assert_eq!(dump.java_version, "17.0.13");
assert_eq!(*fake.commands.lock(), ["thread_print"]);
}
#[test]
fn threads_of_a_tree_without_a_listener_go_to_its_first_application_jvm() {
// A shell (10) started a Gradle client (11) that started the program's JVM (12).
let mut fake = dumping_threads(99, vec![Ok(THREADS.into())]);
fake.application_jvms = vec![12];
let r = dump_tree(&fake, &[10, 11, 12], false);
let JvmThreadsResult::Ready { dump } = r else { panic!("{r:?}") };
assert_eq!(dump.pid, 12);
assert_eq!(*fake.ensured.lock(), [12]);
// No JVM at all: the reported pid is asked, which tells an exited program from a non-JVM.
let fake = dumping_threads(99, Vec::new());
*fake.listener_starts.lock() = vec![Err(AttachError::NotAJvm)].into();
assert_eq!(
threads_unavailable(dump_tree(&fake, &[10, 11], false)),
threads_jvm(JvmMemoryUnavailable::NoJvmProcess)
);
assert_eq!(*fake.ensured.lock(), [10]);
}
#[cfg(unix)]
#[tokio::test]
async fn launched_thread_dump_without_a_listener_finds_the_jvm_below_the_reported_pid() {
struct Child(std::process::Child);
impl Drop for Child {
fn drop(&mut self) {
let _ = self.0.kill();
let _ = self.0.wait();
}
}
let child = Child(std::process::Command::new("sleep").arg("30").spawn().unwrap());
let jvm = child.0.id();
let state = tokio::sync::Mutex::new(JvmMemoryState::default());
let mut fake = dumping_threads(0, vec![Ok(THREADS.into())]);
fake.application_jvms = vec![jvm];
let fake = Arc::new(fake);
let probe: Arc<dyn AttachProbe> = fake.clone();
let target = JvmTarget::Launched(std::process::id() as i32);
let r = thread_dump(&state, || false, |_| probe, target).await.unwrap();
let JvmThreadsResult::Ready { dump } = r else { panic!("{r:?}") };
assert_eq!(dump.pid, jvm);
assert_eq!(*fake.ensured.lock(), [jvm]);
}
#[tokio::test]
async fn a_session_debugs_the_jvm_it_launched_or_found() {
let attach = bare_session("attach");
attach.session.jvm_pid.store(4242, Ordering::Release);
assert!(debugs_jvm(&attach.session, 4242));
assert!(!debugs_jvm(&attach.session, 4243));
let launch = bare_session("launch");
launch.session.debuggee_pid.store(77, Ordering::Release);
assert!(debugs_jvm(&launch.session, 77));
let python = bare_session_of("debugpy", "attach");
python.session.jvm_pid.store(4242, Ordering::Release);
assert!(!debugs_jvm(&python.session, 4242));
attach.session.terminated.store(true, Ordering::Release);
assert!(!debugs_jvm(&attach.session, 4242));
// An attach whose JVM is not found yet debugs no pid.
assert!(!debugs_jvm(&bare_session("attach").session, 0));
}
#[tokio::test]
async fn a_session_attached_to_a_run_may_hold_its_jvm_before_it_is_located() {
let run = ide_core::RunId(7);
let mut bare = bare_session("attach");
Arc::get_mut(&mut bare.session).unwrap().run = Some(run);
// Gradle bootRun Debug opens no attach listener, so the attach-time scan finds no pid.
assert!(attached_to_run(&bare.session, run, 555));
assert!(!attached_to_run(&bare.session, ide_core::RunId(8), 555));
bare.session.jvm_pid.store(4242, Ordering::Release);
assert!(attached_to_run(&bare.session, run, 4242));
assert!(!attached_to_run(&bare.session, run, 555), "another JVM of the same run");
bare.session.terminated.store(true, Ordering::Release);
assert!(!attached_to_run(&bare.session, run, 4242));
let mut python = bare_session_of("debugpy", "attach");
Arc::get_mut(&mut python.session).unwrap().run = Some(run);
assert!(!attached_to_run(&python.session, run, 555));
assert!(!attached_to_run(&bare_session("attach").session, run, 555), "not linked to a run");
}
#[tokio::test]
async fn run_dump_through_a_linked_session_whose_jvm_is_not_located() {
// Stopped at a breakpoint, no listener: refused with the resume reason, no listener start.
let bare = stopped_attach(0);
let fake = Arc::new(dumping_threads(99, Vec::new()));
let probe: Arc<dyn AttachProbe> = fake.clone();
let r = known_pid_dump(&bare.session, |_| probe, 555).await.unwrap();
assert_eq!(threads_unavailable(r), threads_jvm(JvmMemoryUnavailable::ListenerNotRunning));
assert!(fake.commands.lock().is_empty());
// Running: the run's JVM is dumped under the session's turn.
let bare = bare_session("attach");
let fake = Arc::new(dumping_threads(99, vec![Ok(THREADS.into())]));
let probe: Arc<dyn AttachProbe> = fake.clone();
let r = known_pid_dump(&bare.session, |_| probe, 555).await.unwrap();
let JvmThreadsResult::Ready { dump } = r else { panic!("{r:?}") };
assert_eq!((dump.pid, dump.taken_while_suspended), (555, false));
assert_eq!(*fake.ensured.lock(), [555]);
}
/// A run's JVM held at a breakpoint by a debugger attached to it (Debug of `spring-boot:run`).
fn stopped_attach(pid: u32) -> BareSession {
let bare = bare_session("attach");
bare.session.jvm_pid.store(i64::from(pid), Ordering::Release);
bare.session.suspended.stopped(None, true);
bare
}
#[tokio::test]
async fn run_dump_of_a_suspended_debugged_jvm_takes_the_suspended_path() {
let bare = stopped_attach(4242);
let mut fake = dumping_threads(4242, Vec::new());
fake.version = Some(JavaVersion { major: 11, text: "11.0.25".into() });
let fake = Arc::new(fake);
let probe: Arc<dyn AttachProbe> = fake.clone();
let r = known_pid_dump(&bare.session, |_| probe, 4242).await.unwrap();
assert_eq!(threads_unavailable(r), threads_jvm(JvmMemoryUnavailable::UnsafeWhileSuspended { java_major: 11 }));
assert!(fake.commands.lock().is_empty());
// No listener: none is started, the JVM's Signal Dispatcher being stopped.
let fake = Arc::new(dumping_threads(99, Vec::new()));
let probe: Arc<dyn AttachProbe> = fake.clone();
let r = known_pid_dump(&bare.session, |_| probe, 4242).await.unwrap();
assert_eq!(threads_unavailable(r), threads_jvm(JvmMemoryUnavailable::ListenerNotRunning));
assert!(fake.commands.lock().is_empty());
let mut fake = dumping_threads(4242, vec![Ok(THREADS.into())]);
fake.version = Some(JavaVersion { major: 17, text: "17.0.13".into() });
let probe: Arc<dyn AttachProbe> = Arc::new(fake);
let r = known_pid_dump(&bare.session, |_| probe, 4242).await.unwrap();
let JvmThreadsResult::Ready { dump } = r else { panic!("{r:?}") };
assert!(dump.taken_while_suspended);
assert_eq!(dump.pid, 4242);
}
#[tokio::test]
async fn run_dump_of_a_debugged_jvm_waits_for_the_session_turn() {
let bare = bare_session("attach");
bare.session.jvm_pid.store(4242, Ordering::Release);
let fake = Arc::new(dumping_threads(99, Vec::new()));
let probe: Arc<dyn AttachProbe> = fake.clone();
let histogram = bare.session.jvm_memory.lock().await;
let mut queued = Box::pin(known_pid_dump(&bare.session, |_| probe, 4242));
assert!(tokio::time::timeout(Duration::from_millis(50), &mut queued).await.is_err());
// The program hits a breakpoint while the dump waits behind the session's histogram.
bare.session.suspended.stopped(None, true);
drop(histogram);
assert_eq!(threads_unavailable(queued.await.unwrap()), threads_jvm(JvmMemoryUnavailable::ListenerNotRunning));
assert!(fake.commands.lock().is_empty());
}
#[test]
fn threads_of_an_exited_program() {
let mut fake = dumping_threads(99, Vec::new());
fake.alive = false;
*fake.listener_starts.lock() = vec![Err(AttachError::NoListener)].into();
assert_eq!(threads_unavailable(dump_threads(&fake, 12, false)), threads_jvm(JvmMemoryUnavailable::ProgramExited));
assert_eq!(threads_unavailable(dump_threads(&fake, 12, true)), threads_jvm(JvmMemoryUnavailable::ProgramExited));
}
#[test]
fn thread_dump_errors_map_to_reasons() {
let fake = dumping_threads(12, vec![Err(AttachError::Timeout)]);
assert_eq!(threads_unavailable(dump_threads(&fake, 12, false)), threads_jvm(JvmMemoryUnavailable::TimedOut));
let fake = dumping_threads(99, Vec::new());
*fake.listener_starts.lock() = vec![Err(AttachError::ListenerDidNotStart)].into();
assert_eq!(threads_unavailable(dump_threads(&fake, 12, false)), JvmThreadsUnavailable::ListenerDidNotStart);
assert_eq!(*fake.commands.lock(), ["ensure_listener"]);
let mut fake = dumping_threads(99, Vec::new());
*fake.listener_starts.lock() = vec![Err(AttachError::NotAJvm), Err(AttachError::NotAJvm)].into();
assert_eq!(threads_unavailable(dump_threads(&fake, 12, false)), threads_jvm(JvmMemoryUnavailable::NoJvmProcess));
fake.alive = false;
assert_eq!(threads_unavailable(dump_threads(&fake, 12, false)), threads_jvm(JvmMemoryUnavailable::ProgramExited));
let fake = dumping_threads(12, vec![Err(AttachError::Command { code: 1, message: "no".into() })]);
let JvmThreadsUnavailable::Failed { message } = threads_unavailable(dump_threads(&fake, 12, false)) else {
panic!("not a failure")
};
assert!(message.contains("no"), "{message}");
}
#[test]
fn thread_results_serialize_with_camel_case_tags() {
let r = JvmThreadsResult::Unavailable { reason: threads_jvm(JvmMemoryUnavailable::ListenerNotRunning) };
assert_eq!(
serde_json::to_value(r).unwrap(),
serde_json::json!({"status": "unavailable", "reason": {"kind": "jvm", "reason": {"kind": "listenerNotRunning"}}})
);
let r = JvmThreadsResult::Unavailable { reason: JvmThreadsUnavailable::ListenerDidNotStart };
assert_eq!(
serde_json::to_value(r).unwrap(),
serde_json::json!({"status": "unavailable", "reason": {"kind": "listenerDidNotStart"}})
);
let dump = JvmThreadDump {
text: "t".into(),
pid: 7,
java_version: String::new(),
taken_while_suspended: true,
elapsed_ms: 3,
};
assert_eq!(
serde_json::to_value(JvmThreadsResult::Ready { dump }).unwrap(),
serde_json::json!({
"status": "ready",
"dump": {"text": "t", "pid": 7, "javaVersion": "", "takenWhileSuspended": true, "elapsedMs": 3}
})
);
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn threads_take_the_memory_lock() {
let pid = std::process::id();
let state = tokio::sync::Mutex::new(JvmMemoryState::default());
let mut fake = dumping_threads(pid, vec![Ok(THREADS.into())]);
*fake.histograms.lock() = vec![Ok(HISTOGRAM.into())].into();
fake.delay = Duration::from_millis(100);
let fake = Arc::new(fake);
let probe: Arc<dyn AttachProbe> = fake.clone();
let running = Suspension::default();
let (classes, threads) = tokio::join!(
snapshot(&state, &running, |_| probe.clone(), JvmTarget::Launched(pid as i32), None),
thread_dump(&state, || false, |_| probe.clone(), JvmTarget::Launched(pid as i32))
);
assert!(matches!(classes.unwrap(), JvmMemoryResult::Ready { .. }));
let threads = threads.unwrap();
assert!(matches!(threads, JvmThreadsResult::Ready { .. }), "{threads:?}");
assert_eq!(fake.max_in_flight.load(Ordering::SeqCst), 1);
assert_eq!(*fake.commands.lock(), ["histogram", "ensure_listener", "thread_print"]);
}
#[cfg(unix)]
#[tokio::test]
async fn queued_thread_dump_reads_suspension_under_the_lock() {
let pid = std::process::id();
let state = tokio::sync::Mutex::new(JvmMemoryState::default());
let suspended = Suspension::default();
let fake = Arc::new(dumping_threads(0, Vec::new()));
let probe: Arc<dyn AttachProbe> = fake.clone();
let running = state.lock().await;
let mut queued = Box::pin(thread_dump(&state, || suspended.get(), |_| probe, JvmTarget::Launched(pid as i32)));
assert!(tokio::time::timeout(Duration::from_millis(50), &mut queued).await.is_err());
// The program hits a breakpoint while the dump waits behind a class-table request.
suspended.stopped(None, true);
drop(running);
assert_eq!(threads_unavailable(queued.await.unwrap()), threads_jvm(JvmMemoryUnavailable::ListenerNotRunning));
assert!(fake.commands.lock().is_empty());
}
#[tokio::test]
async fn attached_thread_dump_keeps_the_scanned_jvm() {
let state = tokio::sync::Mutex::new(JvmMemoryState::default());
let jvm_pid = AtomicI64::new(0);
let mut fake = dumping_threads(4242, vec![Ok(THREADS.into())]);
fake.jdwp = Some((5005, 4242));
let probe: Arc<dyn AttachProbe> = Arc::new(fake);
let target = JvmTarget::Attached { pid: &jvm_pid, jdwp_port: Some(5005) };
let r = thread_dump(&state, || false, |_| probe, target).await.unwrap();
let JvmThreadsResult::Ready { dump } = r else { panic!("{r:?}") };
assert_eq!(dump.pid, 4242);
assert_eq!(jvm_pid.load(Ordering::SeqCst), 4242);
}
#[tokio::test]
async fn capability_matches_memory() {
for adapter in JVM_MEMORY_ADAPTERS.iter().copied().chain(["debugpy"]) {
+181
View File
@@ -0,0 +1,181 @@
//! A thread dump (`Thread.print -l`) of a debugged or running JVM.
use super::heap::capture_suspended;
use super::snapshot::{AttachProbe, JdkProbe, attach_failure, gone, pick_jvm_pid};
use super::{
JvmMemoryState, JvmMemoryUnavailable, JvmTarget, histogram_pid, keep_found, lookup, resolve_jvm,
safe_while_suspended, session_target, until_located,
};
use crate::session::Session;
use ide_core::{IdeError, IdeResult};
use ide_jvm_attach::AttachError;
use serde::{Deserialize, Serialize};
use specta::Type;
use std::sync::Arc;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct JvmThreadDump {
pub text: String,
pub pid: u32,
/// Empty when unknown.
pub java_version: String,
pub taken_while_suspended: bool,
/// Wall time of the `Thread.print` request.
pub elapsed_ms: u32,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(tag = "kind", rename_all = "camelCase", rename_all_fields = "camelCase")]
pub enum JvmThreadsUnavailable {
/// The reason a class table could not be read applies to the dump too.
Jvm {
reason: JvmMemoryUnavailable,
},
/// The JVM ignored the request to open its attach listener (`-XX:+DisableAttachMechanism`).
ListenerDidNotStart,
/// A run on a remote host, whose JVM this machine cannot attach to.
RemoteRun,
Failed {
message: String,
},
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(tag = "status", rename_all = "camelCase", rename_all_fields = "camelCase")]
pub enum JvmThreadsResult {
Ready { dump: JvmThreadDump },
Unavailable { reason: JvmThreadsUnavailable },
}
/// A thread dump of `pid`, a JVM no debugger holds. Blocking for up to the listener start and
/// dump timeouts, so callers run it in `spawn_blocking`.
pub fn run_jvm_thread_dump(pid: u32) -> JvmThreadsResult {
dump_threads(&JdkProbe { suspended: false }, pid, false)
}
pub(crate) async fn session_thread_dump(session: Arc<Session>) -> IdeResult<JvmThreadsResult> {
until_located(&session).await;
let launched = histogram_pid(&session);
// Detached, so a caller that gives up cannot release the lock while the JVM is still
// answering and let a class-table request run next to it.
tokio::spawn(async move {
let target = session_target(&session, launched);
let probe = |suspended| -> Arc<dyn AttachProbe> { Arc::new(JdkProbe { suspended }) };
thread_dump(&session.jvm_memory, || capture_suspended(&session), probe, target).await
})
.await
.map_err(|e| IdeError::internal(format!("JVM thread dump failed: {e}")))?
}
/// A thread dump of `pid`, a run's JVM that `session` debugs, taken as the session's own dump
/// is: a JVM the debugger holds suspended is never asked to open a listener.
pub(crate) async fn debugged_run_thread_dump(session: Arc<Session>, pid: u32) -> IdeResult<JvmThreadsResult> {
// Detached for the same reason as `session_thread_dump`.
tokio::spawn(async move {
let probe = |suspended| -> Arc<dyn AttachProbe> { Arc::new(JdkProbe { suspended }) };
known_pid_dump(&session, probe, pid).await
})
.await
.map_err(|e| IdeError::internal(format!("JVM thread dump failed: {e}")))?
}
pub(super) async fn known_pid_dump(
session: &Session,
probe: impl FnOnce(bool) -> Arc<dyn AttachProbe>,
pid: u32,
) -> IdeResult<JvmThreadsResult> {
let target =
i32::try_from(pid).map_or(JvmTarget::Unavailable(JvmMemoryUnavailable::NoJvmProcess), JvmTarget::Known);
thread_dump(&session.jvm_memory, || capture_suspended(session), probe, target).await
}
/// Takes the class-table lock, so a dump never runs beside a histogram or heap dump of the same
/// session; `suspended` and then `probe` are read once it is held.
pub(super) async fn thread_dump(
state: &tokio::sync::Mutex<JvmMemoryState>,
suspended: impl FnOnce() -> bool,
probe: impl FnOnce(bool) -> Arc<dyn AttachProbe>,
target: JvmTarget<'_>,
) -> IdeResult<JvmThreadsResult> {
let _turn = state.lock().await;
let suspended = suspended();
let lookup = match lookup(target) {
Ok(lookup) => lookup,
Err(reason) => return Ok(jvm(reason)),
};
let probe = probe(suspended);
let (found, outcome) = tokio::task::spawn_blocking(move || match resolve_jvm(lookup, &*probe, suspended) {
Ok((tree, found)) => (found, dump_tree(&*probe, &tree, suspended)),
Err(reason) => (None, jvm(reason)),
})
.await
.map_err(|e| IdeError::internal(format!("JVM thread dump failed: {e}")))?;
keep_found(target, found);
Ok(outcome)
}
/// `tree` starts with the session's reported pid, followed by its descendants: the JVM is the
/// first with a listener, else the first application JVM (the reported pid may be a shell or a
/// Gradle client), else the reported pid.
pub(super) fn dump_tree(probe: &dyn AttachProbe, tree: &[i32], suspended: bool) -> JvmThreadsResult {
let jvm_pid = pick_jvm_pid(tree, |p| probe.has_listener(p))
.or_else(|| pick_jvm_pid(tree, |p| probe.is_application_jvm(p)))
.or_else(|| tree.first().and_then(|&p| u32::try_from(p).ok()).filter(|&p| p > 0));
match jvm_pid {
Some(pid) => dump_threads(probe, pid, suspended),
None => jvm(JvmMemoryUnavailable::NoJvmProcess),
}
}
/// Blocking. A JVM a debugger holds suspended cannot open a listener (its Signal Dispatcher is
/// stopped), and one below 17 hangs even with one, so it is asked only when both are ruled out.
pub(crate) fn dump_threads(probe: &dyn AttachProbe, pid: u32, suspended: bool) -> JvmThreadsResult {
if suspended {
if !probe.has_listener(pid) {
return jvm(gone(probe, pid));
}
} else if let Err(e) = probe.ensure_listener(pid) {
return failure(probe, pid, e);
}
let version = probe.version(pid);
if suspended && !safe_while_suspended(version.as_ref()) {
return jvm(JvmMemoryUnavailable::UnsafeWhileSuspended { java_major: version.map_or(0, |v| v.major) });
}
let started = std::time::Instant::now();
let text = match probe.thread_print(pid) {
Ok(text) => text,
Err(e) => return failure(probe, pid, e),
};
let elapsed_ms = u32::try_from(started.elapsed().as_millis()).unwrap_or(u32::MAX);
JvmThreadsResult::Ready {
dump: JvmThreadDump {
text,
pid,
java_version: version.map(|v| v.text).unwrap_or_default(),
taken_while_suspended: suspended,
elapsed_ms,
},
}
}
fn failure(probe: &dyn AttachProbe, pid: u32, error: AttachError) -> JvmThreadsResult {
let reason = match error {
AttachError::ListenerDidNotStart => JvmThreadsUnavailable::ListenerDidNotStart,
// A program that exited leaves no perf-data file, so it fails the HotSpot check too.
AttachError::NotAJvm if probe.alive(pid) => {
JvmThreadsUnavailable::Jvm { reason: JvmMemoryUnavailable::NoJvmProcess }
}
AttachError::NotAJvm => JvmThreadsUnavailable::Jvm { reason: JvmMemoryUnavailable::ProgramExited },
e => match attach_failure(probe, pid, e, "thread dump") {
Ok(reason) => JvmThreadsUnavailable::Jvm { reason },
Err(e) => JvmThreadsUnavailable::Failed { message: e.message },
},
};
JvmThreadsResult::Unavailable { reason }
}
fn jvm(reason: JvmMemoryUnavailable) -> JvmThreadsResult {
JvmThreadsResult::Unavailable { reason: JvmThreadsUnavailable::Jvm { reason } }
}
+40 -2
View File
@@ -27,7 +27,7 @@ use adapter::{AdapterLauncher, AdapterSpec, ProcessLauncher};
use connection::{Connection, DapError};
pub use exception_classes::{ExceptionClassBreakpoint, ExceptionClassSupport};
use futures::future::join_all;
use ide_core::{DebugSessionId, IdeError, IdeResult, SharedSink};
use ide_core::{DebugSessionId, IdeError, IdeResult, RunId, SharedSink};
use ide_language::LanguageRegistry;
pub use js_cdp::JsResponseRule;
pub use js_debug::JsResponseBody;
@@ -460,6 +460,15 @@ fn child_name(configuration: &Value, parent: &str) -> String {
}
}
/// `extra_json` key naming the run whose JVM an attach debugs; IDE-side, never sent to the
/// adapter.
pub const RUN_LINK: &str = "__openideaRun";
fn take_run_link(arguments: &mut Value) -> Option<RunId> {
let run = arguments.as_object_mut()?.remove(RUN_LINK)?;
serde_json::from_value(run).ok()
}
/// Builds the `launch`/`attach` arguments: our fields first, then `extra_json` merged on top.
pub fn launch_arguments(config: &LaunchConfig) -> IdeResult<Value> {
// VS Code puts `type`, `request` and `name` in the arguments; js-debug picks launch
@@ -1047,7 +1056,7 @@ impl DebugManager {
adapter_name: String,
parent: Option<DebugSessionId>,
request: String,
arguments: Value,
mut arguments: Value,
spec: AdapterSpec,
reuse_port: Option<u16>,
exception_classes: Option<Arc<dyn ide_jvm_inspect::ExceptionClassBreakpoints>>,
@@ -1067,6 +1076,7 @@ impl DebugManager {
.flatten();
let mut session = Session::new(id, owner, name, adapter_name, parent, request, conn, spec, io.port, io.child);
session.exception_classes = exception_classes;
session.run = take_run_link(&mut arguments);
let session = Arc::new(session);
if let Some(launch_type) = arguments.get("type").and_then(Value::as_str) {
let _ = session.launch_type.set(launch_type.to_owned());
@@ -1967,6 +1977,34 @@ impl DebugManager {
jvm_memory::session_heap_dump(session, dir, cancel).await
}
/// `Thread.print -l` of the session's JVM, taking the session's class-table turn. A JVM the
/// debugger holds suspended is asked only when it is 17 or later and its listener already
/// runs: otherwise the request would hang until the program resumes.
pub async fn jvm_thread_dump(&self, s: DebugSessionId) -> IdeResult<JvmThreadsResult> {
let session = self.session(s)?;
jvm_memory::session_thread_dump(session).await
}
/// `Thread.print -l` of `pid`, the JVM of `run`, when a live session debugs it (a build
/// tool's run started for Debug, Attach to Process): taken as [`Self::jvm_thread_dump`] takes
/// it, under that session's turn and suspension. `None` when no session debugs `pid`.
pub async fn debugged_jvm_thread_dump(&self, run: RunId, pid: u32) -> Option<IdeResult<JvmThreadsResult>> {
let session = self.jvm_session_of(run, pid)?;
Some(jvm_memory::debugged_run_thread_dump(session, pid).await)
}
/// A session attached to `run` first: one whose JVM is not located yet (its attach-time scan
/// found no listener) still holds `pid`.
fn jvm_session_of(&self, run: RunId, pid: u32) -> Option<Arc<Session>> {
let sessions = self.live_sessions();
let linked = || sessions.iter().filter(|s| jvm_memory::attached_to_run(s, run, pid));
linked()
.find(|s| jvm_memory::debugs_jvm(s, pid))
.or_else(|| linked().next())
.or_else(|| sessions.iter().find(|s| jvm_memory::debugs_jvm(s, pid)))
.cloned()
}
/// Gives the session the backend for [`Self::jvm_memory_instances`] and the debugger's class
/// counts; the UI is told to reload the session's capabilities.
pub fn set_jvm_inspector(
+5 -1
View File
@@ -8,7 +8,7 @@ use crate::{Breakpoint, BreakpointState, DataBreakpoint, DebugManager, FunctionB
use ide_core::event::DebugEvent;
#[cfg(unix)]
use ide_core::process::process_tree;
use ide_core::{DebugSessionId, IdeEvent, TaskId};
use ide_core::{DebugSessionId, IdeEvent, RunId, TaskId};
use parking_lot::Mutex;
use serde_json::{Value, json};
use std::collections::{BTreeSet, HashMap};
@@ -117,6 +117,9 @@ pub(crate) struct Session {
pub jvm_located: watch::Sender<bool>,
pub kotlin_mirror: Mutex<Option<crate::kotlin::SourceMirror>>,
pub jvm_memory: tokio::sync::Mutex<crate::JvmMemoryState>,
/// The run whose JVM this session attached to (Debug of a build tool's run, Attach to
/// Process on a run): that run's thread dumps go through this session.
pub run: Option<RunId>,
pub stream_tracer: parking_lot::Mutex<Option<Arc<dyn ide_jvm_inspect::StreamTracer>>>,
/// Given at start: the class breakpoints must be armed before `configurationDone`.
pub(crate) exception_classes: Option<Arc<dyn ide_jvm_inspect::ExceptionClassBreakpoints>>,
@@ -333,6 +336,7 @@ impl Session {
jvm_located: watch::channel(false).0,
kotlin_mirror: Mutex::new(None),
jvm_memory: tokio::sync::Mutex::default(),
run: None,
stream_tracer: parking_lot::Mutex::new(None),
exception_classes: None,
exception_turn: tokio::sync::Mutex::default(),
+49
View File
@@ -3074,6 +3074,55 @@ async fn local_attach_finds_its_jvm_before_the_debugger_connects() {
assert_eq!(session.jvm_pid.load(Ordering::Acquire), 4242);
}
/// Gradle bootRun Debug: the JVM has no attach listener, so the session never learns its pid. The
/// run's dump still goes through the session and, the program being stopped, signals nothing.
#[cfg(unix)]
#[tokio::test]
async fn a_run_dump_goes_through_the_session_attached_to_the_run() {
let h = harness(Script::default());
let project = tempfile::tempdir().unwrap();
let mut cfg = remote_attach("java-debug", project.path());
let mut extra: Value = serde_json::from_str(cfg.extra_json.as_deref().unwrap()).unwrap();
extra[RUN_LINK] = json!(7);
cfg.extra_json = Some(extra.to_string());
let id = h.start(cfg).await.unwrap();
h.wait_event(|e| matches!(e, DebugEvent::Stopped { .. })).await;
assert!(h.request("attach")["arguments"].get(RUN_LINK).is_none(), "IDE-side only");
let session = h.manager.session(id).unwrap();
assert_eq!((session.run, session.jvm_pid.load(Ordering::Acquire)), (Some(RunId(7)), 0));
// `sleep` stands in for the JVM: a SIGQUIT would end it.
let mut jvm = std::process::Command::new("sleep").arg("30").spawn().unwrap();
let pid = jvm.id();
assert_eq!(h.manager.jvm_session_of(RunId(7), pid).map(|s| s.id), Some(id));
assert!(h.manager.jvm_session_of(RunId(8), pid).is_none());
let dump = h.manager.debugged_jvm_thread_dump(RunId(7), pid).await.unwrap().unwrap();
let alive = jvm.try_wait().unwrap().is_none();
let _ = jvm.kill();
let _ = jvm.wait();
assert_eq!(
dump,
JvmThreadsResult::Unavailable {
reason: JvmThreadsUnavailable::Jvm { reason: JvmMemoryUnavailable::ListenerNotRunning }
}
);
assert!(alive, "the stopped JVM was signalled");
}
/// A run's Dump Threads reaches the session attached to the run's JVM, not the plain run path.
#[cfg(unix)]
#[tokio::test]
async fn a_run_jvm_is_found_by_the_session_attached_to_it() {
let h = harness(Script::default());
h.manager.set_jvm_finder(Arc::new(|port, _| (port == 5005).then_some(4242)));
let mut cfg = java_config("attach");
cfg.extra_json = Some(json!({"hostName": "127.0.0.1", "port": 5005}).to_string());
let id = h.start(cfg).await.unwrap();
assert_eq!(h.manager.jvm_session_of(RunId(1), 4242).map(|s| s.id), Some(id));
assert!(h.manager.jvm_session_of(RunId(1), 4243).is_none());
assert!(h.manager.debugged_jvm_thread_dump(RunId(1), 4243).await.is_none());
}
#[cfg(unix)]
#[tokio::test]
async fn local_attach_remembers_its_jdwp_port() {
+14 -1
View File
@@ -17,7 +17,7 @@ specta.workspace = true
toml.workspace = true
toml_edit.workspace = true
blake3.workspace = true
tokio.workspace = true
tokio = { workspace = true, features = ["net"] }
tracing.workspace = true
parking_lot.workspace = true
notify.workspace = true
@@ -38,6 +38,19 @@ rsa = { version = "0.10.0-rc.18", features = ["sha2", "pkcs5"] }
zeroize = "1"
open = "5"
[target.'cfg(unix)'.dependencies]
libc = "0.2"
[target.'cfg(windows)'.dependencies]
windows-sys = { version = "0.61", features = [
"Win32_Foundation",
"Win32_NetworkManagement_IpHelper",
"Win32_Networking_WinSock",
"Win32_System_Diagnostics_ToolHelp",
"Win32_System_Threading",
"Win32_System_JobObjects",
] }
[dev-dependencies]
tokio = { workspace = true, features = ["rt-multi-thread", "macros", "net"] }
ide-ssh = { workspace = true, features = ["testing"] }
+108 -7
View File
@@ -12,7 +12,7 @@ use ide_core::{CancellationToken, IdeError, IdeResult, error::ErrorKind};
use serde::{Deserialize, Serialize};
use specta::Type;
use sqlx::{
Column, ColumnIndex, Connection, Decode, Executor, Row, SqlSafeStr, Sqlite, TypeInfo, ValueRef,
Column, ColumnIndex, ConnectOptions, Connection, Decode, Executor, Row, SqlSafeStr, Sqlite, TypeInfo, ValueRef,
mysql::{MySqlConnectOptions, MySqlConnection, MySqlSslMode},
pool::PoolConnection,
postgres::{PgConnectOptions, PgConnection, PgSslMode},
@@ -135,7 +135,7 @@ impl Context {
}
macro_rules! sqlx_pool {
($manager:ident, $handle:ident, $options:ty, $connection:ty, $driver:expr, $query:expr) => {
($manager:ident, $handle:ident, $options:ty, $connection:ty, $driver:expr, $query:expr $(, $after_init:ident)?) => {
pub struct $manager {
options: $options,
init: Arc<Vec<String>>,
@@ -170,7 +170,7 @@ macro_rules! sqlx_pool {
async fn connect(&self) -> Result<Self::Connection, Self::Error> {
tokio::time::timeout(self.timeout, async {
let mut conn = <$connection>::connect_with(&self.options).await?;
let mut conn = self.options.connect().await?;
let context_sql = |value: Option<String>| {
value.map(|v| {
if $driver == DbDriver::Postgres {
@@ -183,6 +183,9 @@ macro_rules! sqlx_pool {
for sql in self.init.iter() {
sqlx::raw_sql(sqlx::AssertSqlSafe(sql.clone())).execute(&mut conn).await?;
}
$(if !self.init.is_empty() {
self.options.$after_init(&mut conn).await?;
})?
let row = sqlx::raw_sql(sqlx::AssertSqlSafe($query.to_owned())).fetch_one(&mut conn).await?;
let context = Context::new(context_sql(row.try_get(0)?));
Ok($handle {
@@ -209,7 +212,88 @@ macro_rules! sqlx_pool {
};
}
sqlx_pool!(PgManager, PgHandle, PgConnectOptions, PgConnection, DbDriver::Postgres, "SHOW search_path");
#[derive(Clone)]
struct PostgresOptions {
connection: PgConnectOptions,
read_only: bool,
}
const PG_READ_ONLY_HINT: &str = "Read-only requires the pooler to track default_transaction_read_only for each client. \
For PgBouncer, check track_extra_parameters.";
impl PostgresOptions {
async fn connect(&self) -> Result<PgConnection, sqlx::Error> {
let mut conn = self.connection.connect().await?;
// A pooler can silently discard startup options. Check before giving the startup script a connection.
self.verify_read_only(&mut conn).await?;
Ok(conn)
}
async fn verify_read_only(&self, conn: &mut PgConnection) -> Result<(), sqlx::Error> {
if self.read_only && !pg_setting_on(conn, "SHOW default_transaction_read_only").await? {
return Err(sqlx::Error::Configuration(
format!(
"PostgreSQL did not enable the requested default_transaction_read_only setting. \
Check the Advanced properties and startup script. {PG_READ_ONLY_HINT}"
)
.into(),
));
}
Ok(())
}
async fn verify_startup_script(&self, conn: &mut PgConnection) -> Result<(), sqlx::Error> {
self.verify_read_only(conn).await?;
if self.read_only && !pg_setting_on(conn, "SHOW transaction_read_only").await? {
return Err(sqlx::Error::Configuration(
"The startup script left a writable transaction open on a read-only PostgreSQL source.".into(),
));
}
Ok(())
}
}
async fn pg_setting_on(conn: &mut PgConnection, show: &'static str) -> Result<bool, sqlx::Error> {
let row = sqlx::raw_sql(show).fetch_one(conn).await?;
Ok(row.try_get::<&str, _>(0)? == "on")
}
fn postgres_read_only_hint(read_only: bool, code: Option<&str>, message: &str) -> Option<&'static str> {
match (read_only, code, message) {
(
true,
Some("08P01"),
"unsupported startup parameter in options: default_transaction_read_only"
| "unsupported startup parameter: default_transaction_read_only",
) => Some(PG_READ_ONLY_HINT),
(true, Some("08P01"), "unsupported startup parameter: options") => Some(
"This endpoint rejects PostgreSQL startup options. Use an endpoint that supports and tracks \
default_transaction_read_only for each client.",
),
_ => None,
}
}
fn postgres_connect_error(error: sqlx::Error, read_only: bool) -> IdeError {
let hint =
error.as_database_error().and_then(|db| postgres_read_only_hint(read_only, db.code().as_deref(), db.message()));
let mut error = db_err(error);
if let Some(hint) = hint {
error.message.push_str(". ");
error.message.push_str(hint);
}
error
}
sqlx_pool!(
PgManager,
PgHandle,
PostgresOptions,
PgConnection,
DbDriver::Postgres,
"SHOW search_path",
verify_startup_script
);
sqlx_pool!(MysqlManager, MysqlHandle, MySqlConnectOptions, MySqlConnection, DbDriver::Mysql, "SELECT DATABASE()");
pub struct ServerPool<M: ManageConnection> {
@@ -980,17 +1064,18 @@ impl Pool {
if let Some(n) = setup.statement_cache {
opts = opts.statement_cache_capacity(n);
}
let mut manager = PgManager { options: opts, init: init.clone(), timeout };
let options = PostgresOptions { connection: opts, read_only: source.read_only };
let mut manager = PgManager { options, init: init.clone(), timeout };
// Open once directly so authentication failures retain their database error.
let first = match manager.connect().await {
Err(e) if source.ssl == DbSslMode::Prefer && tls_failed(&e) => {
tracing::info!("TLS handshake failed, connecting without TLS (SSL mode Prefer): {e}");
manager.options = manager.options.clone().ssl_mode(PgSslMode::Disable);
manager.options.connection = manager.options.connection.clone().ssl_mode(PgSslMode::Disable);
manager.connect().await
}
first => first,
}
.map_err(db_err)?;
.map_err(|e| postgres_connect_error(e, source.read_only))?;
let pool = Bb8Pool::builder().max_size(MAX).connection_timeout(timeout).build_unchecked(manager);
let _ = pool.add(first);
Ok(Pool::Postgres(ServerPool { inner: pool, closed: AtomicBool::new(false) }))
@@ -1632,6 +1717,22 @@ mod tests {
}
}
#[test]
fn postgres_read_only_guidance_identifies_what_the_pooler_rejected() {
let rejected = "unsupported startup parameter in options: default_transaction_read_only";
assert_eq!(postgres_read_only_hint(true, Some("08P01"), rejected), Some(PG_READ_ONLY_HINT));
let direct = "unsupported startup parameter: default_transaction_read_only";
assert_eq!(postgres_read_only_hint(true, Some("08P01"), direct), Some(PG_READ_ONLY_HINT));
let options = postgres_read_only_hint(true, Some("08P01"), "unsupported startup parameter: options").unwrap();
assert!(options.contains("rejects PostgreSQL startup options"));
assert_eq!(postgres_read_only_hint(false, Some("08P01"), rejected), None);
assert_eq!(postgres_read_only_hint(true, Some("28P01"), rejected), None);
assert_eq!(
postgres_read_only_hint(true, Some("08P01"), "unsupported startup parameter: extra_float_digits"),
None
);
}
#[test]
fn prefer_retries_without_tls_only_after_a_failed_handshake() {
use std::io;
+436
View File
@@ -0,0 +1,436 @@
//! An approved foreground helper behind a loopback relay owned by the IDE.
use crate::DbExternalTunnel;
use ide_core::{IdeError, IdeResult, error::ErrorKind, process};
use parking_lot::Mutex;
use std::io;
use std::net::{IpAddr, Ipv4Addr, SocketAddr, SocketAddrV4};
use std::path::Path;
use std::process::{Child, Command, Stdio};
use std::sync::{Arc, Weak};
use std::time::Duration;
use tokio::net::{TcpListener, TcpSocket, TcpStream};
use tokio::sync::Semaphore;
use tokio::task::{JoinHandle, JoinSet};
#[cfg(target_os = "linux")]
#[path = "external_tunnel/linux.rs"]
mod platform;
#[cfg(target_os = "macos")]
#[path = "external_tunnel/macos.rs"]
mod platform;
#[cfg(windows)]
#[path = "external_tunnel/windows.rs"]
mod platform;
#[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
mod platform {
use super::*;
pub(super) async fn owns_socket(_: &Arc<Helper>, _: SocketAddr, _: Option<SocketAddr>) -> io::Result<bool> {
Err(io::Error::new(io::ErrorKind::Unsupported, "socket ownership cannot be verified on this OS"))
}
}
const STARTUP_TIMEOUT: Duration = Duration::from_secs(30);
const CONNECTION_TIMEOUT: Duration = Duration::from_secs(3);
const POLL_INTERVAL: Duration = Duration::from_millis(100);
const MAX_CONNECTIONS: usize = 128;
static VERIFICATION_SLOTS: Semaphore = Semaphore::const_new(8);
static HELPERS: Mutex<ActiveHelpers> = Mutex::new(ActiveHelpers { stopping: false, children: Vec::new() });
struct ActiveHelpers {
stopping: bool,
children: Vec<Weak<Helper>>,
}
/// Stop the IDE's external TCP tunnel processes before desktop exit or restart.
pub fn stop_external_tunnels_on_exit() {
let children = {
let mut active = HELPERS.lock();
active.stopping = true;
std::mem::take(&mut active.children)
};
for helper in children.into_iter().filter_map(|child| child.upgrade()) {
helper.stop();
}
}
pub(super) struct ExternalTunnel {
port: u16,
// Keep the address reserved even after the helper exits, until the last route reference drops.
_listener: Arc<TcpListener>,
helper: Weak<Helper>,
task: JoinHandle<()>,
}
impl ExternalTunnel {
pub(super) fn validate(config: &DbExternalTunnel, target: (&str, u16)) -> IdeResult<()> {
helper_target(config, target).map(|_| ())
}
pub(super) async fn open(config: &DbExternalTunnel, target: (&str, u16)) -> IdeResult<Self> {
if !cfg!(any(target_os = "linux", target_os = "macos", windows)) {
return Err(IdeError::unavailable("External TCP tunnel socket ownership cannot be verified on this OS"));
}
let listener = Arc::new(loopback_socket()?.listen(128)?);
let port = listener.local_addr()?.port();
let reservation = loopback_socket()?;
let endpoint = reservation.local_addr()?;
let arguments = helper_arguments(config, target, endpoint.port())?;
drop(reservation);
let helper = launch_helper(Path::new(&config.executable), &arguments)?;
let ready = tokio::time::timeout(STARTUP_TIMEOUT, async {
loop {
if !helper.is_alive() {
return Err(IdeError::new(
ErrorKind::Io,
"The external TCP tunnel helper exited before opening its loopback listener. \
Check the helper command in a terminal.",
));
}
if verify_socket(&helper, endpoint, None).await.map_err(|error| {
IdeError::new(ErrorKind::Io, format!("Could not verify the external TCP tunnel listener: {error}"))
})? {
return Ok(());
}
tokio::time::sleep(POLL_INTERVAL).await;
}
})
.await;
ready.map_err(|_| {
IdeError::new(
ErrorKind::Io,
format!(
"The external TCP tunnel helper did not open an owned listener at {endpoint} before the startup timeout. \
Check that the command binds to 127.0.0.1 and uses {{localPort}}."
),
)
})??;
let watched_helper = Arc::downgrade(&helper);
let task = tokio::spawn(relay(Arc::clone(&listener), endpoint, helper));
Ok(Self { port, _listener: listener, helper: watched_helper, task })
}
pub(super) fn port(&self) -> u16 {
self.port
}
pub(super) fn is_closed(&self) -> bool {
self.task.is_finished() || self.helper.upgrade().is_none_or(|helper| !helper.is_alive())
}
}
impl Drop for ExternalTunnel {
fn drop(&mut self) {
self.task.abort();
}
}
fn loopback_socket() -> io::Result<TcpSocket> {
let socket = TcpSocket::new_v4()?;
#[cfg(windows)]
platform::make_exclusive(&socket)?;
socket.bind(SocketAddrV4::new(Ipv4Addr::LOCALHOST, 0).into())?;
Ok(socket)
}
fn helper_target<'a>(config: &DbExternalTunnel, (host, port): (&'a str, u16)) -> IdeResult<(&'a str, u16)> {
let executable = Path::new(&config.executable);
if !executable.is_absolute() || executable.file_name().is_none() || config.executable.contains('\0') {
return Err(IdeError::invalid("Choose an absolute path to the external TCP tunnel executable"));
}
#[cfg(windows)]
if !executable.extension().is_some_and(|extension| extension.eq_ignore_ascii_case("exe")) {
return Err(IdeError::invalid("Choose an .exe file for the external TCP tunnel"));
}
let host = host.trim();
let host = host
.strip_prefix('[')
.and_then(|host| host.strip_suffix(']'))
.filter(|host| host.parse::<std::net::Ipv6Addr>().is_ok())
.unwrap_or(host);
let dns = host.strip_suffix('.').unwrap_or(host);
if host.parse::<IpAddr>().is_err()
&& (dns.len() > 253
|| !dns.split('.').all(|label| {
let bytes = label.as_bytes();
bytes.len() <= 63
&& bytes.first().is_some_and(u8::is_ascii_alphanumeric)
&& bytes.last().is_some_and(u8::is_ascii_alphanumeric)
&& bytes.iter().all(|byte| byte.is_ascii_alphanumeric() || *byte == b'-')
}))
{
return Err(IdeError::invalid("Enter a DNS name or IP address for the external TCP tunnel"));
}
if port == 0 {
return Err(IdeError::invalid("Enter a valid destination port for the external TCP tunnel"));
}
if !config.arguments.iter().any(|arg| arg.contains("{localPort}")) {
return Err(IdeError::invalid("Include {localPort} in the external TCP tunnel arguments"));
}
if config.arguments.iter().any(|arg| arg.contains('\0')) {
return Err(IdeError::invalid("External TCP tunnel arguments cannot contain NUL characters"));
}
Ok((host, port))
}
fn helper_arguments(config: &DbExternalTunnel, target: (&str, u16), local_port: u16) -> IdeResult<Vec<String>> {
let (host, port) = helper_target(config, target)?;
let target = if host.contains(':') { format!("[{host}]:{port}") } else { format!("{host}:{port}") };
let (local_port, port) = (local_port.to_string(), port.to_string());
let placeholders =
[("{host}:{port}", target.as_str()), ("{localPort}", &local_port), ("{host}", host), ("{port}", &port)];
Ok(config
.arguments
.iter()
.map(|arg| {
let mut remaining = arg.as_str();
let mut expanded = String::with_capacity(arg.len());
while let Some(start) = remaining.find('{') {
expanded.push_str(&remaining[..start]);
remaining = &remaining[start..];
if let Some((value, tail)) = placeholders
.into_iter()
.find_map(|(key, value)| remaining.strip_prefix(key).map(|tail| (value, tail)))
{
expanded.push_str(value);
remaining = tail;
} else {
expanded.push('{');
remaining = &remaining[1..];
}
}
expanded.push_str(remaining);
expanded
})
.collect())
}
fn launch_helper(executable: &Path, arguments: &[String]) -> IdeResult<Arc<Helper>> {
let mut active = HELPERS.lock();
if active.stopping {
return Err(IdeError::cancelled());
}
let helper = Arc::new(Helper::spawn(executable, arguments).map_err(|error| {
IdeError::new(ErrorKind::Io, format!("Could not start the external TCP tunnel helper: {error}"))
})?);
active.children.retain(|child| child.strong_count() > 0);
active.children.push(Arc::downgrade(&helper));
Ok(helper)
}
struct Helper {
child: Option<Child>,
#[cfg(windows)]
job: process::Job,
}
impl Helper {
fn spawn(executable: &Path, arguments: &[String]) -> io::Result<Self> {
let mut command = Command::new(executable);
command
.args(arguments)
.current_dir(executable.parent().expect("validated absolute executable path"))
.env_clear()
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null());
// Keep user config discovery available without inheriting database or project variables.
for key in [
"PATH",
"HOME",
"XDG_CONFIG_HOME",
"XDG_CACHE_HOME",
"XDG_DATA_HOME",
"XDG_RUNTIME_DIR",
"USERPROFILE",
"APPDATA",
"LOCALAPPDATA",
"SYSTEMROOT",
"WINDIR",
"TMPDIR",
"TEMP",
"TMP",
"SSH_AUTH_SOCK",
"NO_PROXY",
"no_proxy",
] {
if let Some(value) = process::host_var_os(key) {
command.env(key, value);
}
}
for key in ["HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "http_proxy", "https_proxy", "all_proxy"] {
if let Some(value) = process::host_var_os(key)
&& value.to_str().is_some_and(credential_free_proxy)
{
command.env(key, value);
}
}
#[cfg(unix)]
{
use std::os::unix::process::CommandExt;
// Membership of this group is an authorization check. A separate session limits
// membership to this child and its descendants; the leader also owns the group.
// SAFETY: setsid is async-signal-safe and does not access Rust state after fork.
unsafe {
command.pre_exec(|| if libc::setsid() == -1 { Err(io::Error::last_os_error()) } else { Ok(()) });
}
}
#[cfg(windows)]
{
platform::spawn_suspended(command)
}
#[cfg(not(windows))]
{
Ok(Self { child: Some(command.spawn()?) })
}
}
fn child(&self) -> &Child {
self.child.as_ref().expect("the live helper owns its child handle")
}
#[cfg(unix)]
fn pid(&self) -> u32 {
self.child().id()
}
fn is_alive(&self) -> bool {
#[cfg(unix)]
{
loop {
let mut info = std::mem::MaybeUninit::<libc::siginfo_t>::zeroed();
// Keep the group leader unreaped so its id cannot be reused before group cleanup.
// SAFETY: valid output buffer and the id of the child owned by `self`.
let result = unsafe {
libc::waitid(
libc::P_PID,
self.pid(),
info.as_mut_ptr(),
libc::WEXITED | libc::WNOHANG | libc::WNOWAIT,
)
};
if result == 0 {
// SAFETY: the buffer was zeroed and waitid returned successfully.
return unsafe { info.assume_init().si_pid() == 0 };
}
if io::Error::last_os_error().kind() != io::ErrorKind::Interrupted {
return false;
}
}
}
#[cfg(windows)]
{
use std::os::windows::io::AsRawHandle;
use windows_sys::Win32::Foundation::WAIT_TIMEOUT;
use windows_sys::Win32::System::Threading::WaitForSingleObject;
// SAFETY: the owned child handle stays open through this non-blocking check.
unsafe { WaitForSingleObject(self.child().as_raw_handle(), 0) == WAIT_TIMEOUT }
}
#[cfg(not(any(unix, windows)))]
{
false
}
}
fn stop(&self) {
#[cfg(windows)]
let _ = self.job.terminate();
#[cfg(unix)]
process::kill_tree_of(self.pid());
}
}
fn credential_free_proxy(value: &str) -> bool {
let url = if value.contains("://") {
reqwest::Url::parse(value)
} else {
reqwest::Url::parse(&format!("http://{value}"))
};
url.is_ok_and(|url| {
matches!(url.scheme(), "http" | "https" | "socks4" | "socks4a" | "socks5" | "socks5h")
&& url.host().is_some()
&& url.username().is_empty()
&& url.password().is_none()
&& matches!(url.path(), "" | "/")
&& url.query().is_none()
&& url.fragment().is_none()
})
}
impl Drop for Helper {
fn drop(&mut self) {
self.stop();
#[cfg(unix)]
if let Some(mut child) = self.child.take() {
// A helper blocked in the kernel must not hold up the async caller during cleanup.
if !matches!(child.try_wait(), Ok(Some(_))) {
let _ = std::thread::Builder::new().spawn(move || child.wait());
}
}
}
}
async fn relay(listener: Arc<TcpListener>, endpoint: SocketAddr, helper: Arc<Helper>) {
let mut connections = JoinSet::new();
let mut liveness = tokio::time::interval(Duration::from_secs(1));
liveness.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
loop {
tokio::select! {
_ = liveness.tick() => {
if !helper.is_alive() { break; }
}
accepted = listener.accept(), if connections.len() < MAX_CONNECTIONS => {
let Ok((mut client, _)) = accepted else {
// Transient errors such as descriptor exhaustion affect new sockets only.
tokio::time::sleep(POLL_INTERVAL).await;
continue;
};
let helper = Arc::clone(&helper);
connections.spawn(async move {
if let Ok(Ok(mut upstream)) = tokio::time::timeout(CONNECTION_TIMEOUT, connect_verified(&helper, endpoint)).await {
let _ = tokio::io::copy_bidirectional(&mut client, &mut upstream).await;
true
} else {
false
}
});
}
finished = connections.join_next(), if !connections.is_empty() => {
if matches!(finished, Some(Ok(false)))
// A slow ownership probe must not interrupt already verified connections.
&& matches!(tokio::time::timeout(CONNECTION_TIMEOUT, verify_socket(&helper, endpoint, None)).await, Ok(Ok(false)))
{
break;
}
}
}
}
}
async fn connect_verified(helper: &Arc<Helper>, endpoint: SocketAddr) -> io::Result<TcpStream> {
let upstream = TcpStream::connect(endpoint).await?;
let peer = upstream.local_addr()?;
// TCP connect can complete before the helper accepts. Check the server's half of this
// exact connection, keeping all client bytes in the IDE until that socket has an owner.
loop {
if !helper.is_alive() {
return Err(io::Error::new(io::ErrorKind::BrokenPipe, "external TCP tunnel helper exited"));
}
if verify_socket(helper, endpoint, Some(peer)).await? && helper.is_alive() {
return Ok(upstream);
}
tokio::time::sleep(POLL_INTERVAL).await;
}
}
async fn verify_socket(helper: &Arc<Helper>, local: SocketAddr, peer: Option<SocketAddr>) -> io::Result<bool> {
let _slot = VERIFICATION_SLOTS.acquire().await.map_err(io::Error::other)?;
platform::owns_socket(helper, local, peer).await
}
#[cfg(all(test, any(target_os = "linux", target_os = "macos", windows)))]
mod tests;
@@ -0,0 +1,92 @@
use super::{Helper, io};
use std::fs::{self, File};
use std::io::{BufRead, BufReader, Read};
use std::net::{SocketAddr, SocketAddrV4};
use std::sync::Arc;
pub(super) async fn owns_socket(helper: &Arc<Helper>, local: SocketAddr, peer: Option<SocketAddr>) -> io::Result<bool> {
let helper = Arc::clone(helper);
tokio::task::spawn_blocking(move || {
let (SocketAddr::V4(local), peer) = (local, peer) else { return Ok(false) };
let peer = match peer {
Some(SocketAddr::V4(peer)) => Some(peer),
None => None,
_ => return Ok(false),
};
let state = if peer.is_some() { "01" } else { "0A" };
for (table, ipv6) in [("/proc/net/tcp", false), ("/proc/net/tcp6", true)] {
let file = match File::open(table) {
Ok(file) => file,
Err(error) if ipv6 && error.kind() == io::ErrorKind::NotFound => continue,
Err(error) => return Err(error),
};
let local = address(local, ipv6);
let peer = peer.map(|peer| address(peer, ipv6));
// Kernel rows are small, but bound the time spent scanning a busy host's table.
for line in BufReader::new(file.take(8 * 1024 * 1024)).lines().skip(1) {
let line = line?;
let mut fields = line.split_ascii_whitespace().skip(1);
let (Some(left), Some(right), Some(current_state)) = (fields.next(), fields.next(), fields.next())
else {
continue;
};
if left != local || current_state != state || peer.as_deref().is_some_and(|peer| peer != right) {
continue;
}
let Some(inode) = fields.nth(5).and_then(|inode| inode.parse::<u64>().ok()).filter(|inode| *inode != 0)
else {
continue;
};
if group_holds_socket(helper.pid(), inode)? {
return Ok(true);
}
}
}
Ok(false)
})
.await
.map_err(io::Error::other)?
}
fn address(address: SocketAddrV4, ipv6: bool) -> String {
let ip = address.ip();
let port = address.port();
if !ipv6 {
return format!("{:08X}:{port:04X}", u32::from_ne_bytes(ip.octets()));
}
let octets = ip.to_ipv6_mapped().octets();
let [a, b, c, d] = octets.as_chunks::<4>().0 else { unreachable!() };
format!(
"{:08X}{:08X}{:08X}{:08X}:{port:04X}",
u32::from_ne_bytes(*a),
u32::from_ne_bytes(*b),
u32::from_ne_bytes(*c),
u32::from_ne_bytes(*d)
)
}
fn group_holds_socket(group: u32, inode: u64) -> io::Result<bool> {
let group = i32::try_from(group).map_err(io::Error::other)?;
let target = format!("socket:[{inode}]");
for process in fs::read_dir("/proc")? {
let Ok(process) = process else { continue };
let name = process.file_name();
let Some(pid) = name.to_str().and_then(|name| name.parse::<libc::pid_t>().ok()).filter(|pid| *pid > 0) else {
continue;
};
// SAFETY: this only queries the process group of the enumerated pid.
if unsafe { libc::getpgid(pid) } != group {
continue;
}
let Ok(descriptors) = fs::read_dir(process.path().join("fd")) else { continue };
for descriptor in descriptors.flatten() {
if fs::read_link(descriptor.path()).is_ok_and(|link| link.as_os_str() == target.as_str()) {
// SAFETY: check membership again after examining the fd directory.
if unsafe { libc::getpgid(pid) } == group {
return Ok(true);
}
}
}
}
Ok(false)
}
@@ -0,0 +1,61 @@
use super::{Helper, io};
use std::net::{IpAddr, SocketAddr};
use std::process::Stdio;
use std::sync::Arc;
use tokio::io::AsyncReadExt;
const MAX_OUTPUT: u64 = 64 * 1024;
pub(super) async fn owns_socket(helper: &Arc<Helper>, local: SocketAddr, peer: Option<SocketAddr>) -> io::Result<bool> {
let group = helper.pid().to_string();
let sockets = format!("-iTCP:{}", local.port());
let state = if peer.is_some() { "-sTCP:ESTABLISHED" } else { "-sTCP:LISTEN" };
let mut probe = tokio::process::Command::new("/usr/sbin/lsof")
.args(["-nP", "-a", "-g", &group, &sockets, state, "-Fgn"])
.env_clear()
.stdin(Stdio::null())
.stderr(Stdio::null())
.stdout(Stdio::piped())
.kill_on_drop(true)
.spawn()?;
let mut output = Vec::new();
probe.stdout.take().expect("stdout is piped").take(MAX_OUTPUT + 1).read_to_end(&mut output).await?;
if output.len() as u64 > MAX_OUTPUT {
return Err(io::Error::other("loopback socket ownership output exceeded its limit"));
}
let status = probe.wait().await?;
if !status.success() {
// lsof uses exit 1 for a successful scan with no matching descriptors.
return if status.code() == Some(1) && output.is_empty() {
Ok(false)
} else {
Err(io::Error::other("loopback socket ownership query failed"))
};
}
let mut owned = false;
for line in String::from_utf8_lossy(&output).lines() {
match line.as_bytes().first() {
Some(b'p') => owned = false,
Some(b'g') => owned = line[1..] == group,
Some(b'n') if owned => {
let (left, right) =
line[1..].split_once("->").map_or((&line[1..], None), |(left, right)| (left, Some(right)));
if address(left) == Some(local) && right.and_then(address) == peer && right.is_some() == peer.is_some()
{
return Ok(true);
}
}
_ => {}
}
}
Ok(false)
}
fn address(value: &str) -> Option<SocketAddr> {
let address = value.parse::<SocketAddr>().ok()?;
let ip = match address.ip() {
IpAddr::V6(ip) => ip.to_ipv4_mapped().map_or(IpAddr::V6(ip), IpAddr::V4),
ip => ip,
};
Some(SocketAddr::new(ip, address.port()))
}
+188
View File
@@ -0,0 +1,188 @@
use super::*;
use std::io::{Read, Write};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
const EXAMPLE: &[u8; 4] = b"test";
const FIXTURE: &str = "external_tunnel::tests::fixture_entry";
fn config(mode: &str) -> crate::DbExternalTunnel {
crate::DbExternalTunnel {
executable: std::env::current_exe().unwrap().to_str().unwrap().to_owned(),
arguments: vec!["--exact".into(), FIXTURE.into(), "--skip".into(), format!("wire-{mode}-{{localPort}}")],
}
}
const TARGET: (&str, u16) = ("db.example", 5432);
// The test binary doubles as a foreground helper without an external interpreter.
#[test]
fn fixture_entry() {
let Some(fixture) = std::env::args().find(|arg| arg.starts_with("wire-")) else { return };
#[cfg(unix)]
// SAFETY: these calls only inspect the current process's session and group.
assert_eq!(unsafe { libc::getsid(0) }, unsafe { libc::getpgrp() });
let (mode, port) = fixture.strip_prefix("wire-").unwrap().split_once('-').unwrap();
let endpoint = SocketAddrV4::new(Ipv4Addr::LOCALHOST, port.parse().unwrap());
match mode {
"exit" => (),
"idle" => std::thread::sleep(Duration::from_secs(60)),
"waiting" => {
let observer = std::env::args()
.find_map(|arg| arg.strip_prefix("observer-port-").and_then(|port| port.parse::<u16>().ok()))
.unwrap();
let _observer = std::net::TcpStream::connect((Ipv4Addr::LOCALHOST, observer)).unwrap();
std::thread::sleep(Duration::from_secs(60));
}
"tree" => {
let mut child = Command::new(std::env::current_exe().unwrap())
.args(["--exact", FIXTURE, "--skip", &format!("wire-echo-{port}")])
.spawn()
.unwrap();
assert!(child.wait().unwrap().success());
}
"echo" | "once" => {
let socket = std::net::TcpListener::bind(endpoint).unwrap();
std::thread::sleep(Duration::from_millis(150));
for stream in socket.incoming() {
let mut stream = stream.unwrap();
let mut bytes = [0; EXAMPLE.len()];
if stream.read_exact(&mut bytes).is_ok() {
stream.write_all(&bytes).unwrap();
stream.write_all(&endpoint.port().to_be_bytes()).unwrap();
if mode == "once" {
let _ = stream.read(&mut [0]);
break;
}
}
}
}
_ => unreachable!(),
}
}
#[tokio::test]
async fn forwards_multiple_connections_to_the_helpers_child_and_cleans_up() {
let tunnel = ExternalTunnel::open(&config("tree"), TARGET).await.unwrap();
let mut helper_port = 0;
for _ in 0..2 {
let result = tokio::time::timeout(Duration::from_secs(5), async {
let mut db = TcpStream::connect((Ipv4Addr::LOCALHOST, tunnel.port())).await.unwrap();
db.write_all(EXAMPLE).await.unwrap();
let mut bytes = [0; EXAMPLE.len()];
db.read_exact(&mut bytes).await.unwrap();
assert_eq!(&bytes, EXAMPLE);
db.read_u16().await.unwrap()
});
helper_port = result.await.unwrap();
}
assert_ne!(helper_port, tunnel.port());
assert!(!tunnel.is_closed());
drop(tunnel);
tokio::time::timeout(Duration::from_secs(5), async {
loop {
if TcpStream::connect((Ipv4Addr::LOCALHOST, helper_port)).await.is_err() {
break;
}
tokio::time::sleep(POLL_INTERVAL).await;
}
})
.await
.unwrap();
}
#[tokio::test]
async fn reports_a_helper_that_exits_without_listening() {
let result = ExternalTunnel::open(&config("exit"), TARGET).await;
assert!(result.err().unwrap().message.contains("exited"));
}
#[tokio::test]
async fn dropping_startup_stops_the_helper_before_it_listens() {
let observer = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await.unwrap();
let mut settings = config("waiting");
settings.arguments.extend(["--skip".into(), format!("observer-port-{}", observer.local_addr().unwrap().port())]);
let startup = tokio::spawn(async move { ExternalTunnel::open(&settings, TARGET).await });
let (mut helper_socket, _) =
tokio::time::timeout(Duration::from_secs(10), observer.accept()).await.unwrap().unwrap();
assert!(!startup.is_finished());
startup.abort();
assert!(startup.await.err().unwrap().is_cancelled());
let error = tokio::time::timeout(Duration::from_secs(5), helper_socket.read_u8()).await.unwrap().unwrap_err();
// Terminating the helper can reset its observer socket on Windows.
assert!(matches!(error.kind(), io::ErrorKind::UnexpectedEof | io::ErrorKind::ConnectionReset), "{error}");
}
#[tokio::test]
async fn refuses_an_unrelated_established_loopback_socket() {
let unrelated = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await.unwrap();
let endpoint = unrelated.local_addr().unwrap();
let settings = config("idle");
let arguments = helper_arguments(&settings, TARGET, endpoint.port()).unwrap();
let helper = Arc::new(Helper::spawn(Path::new(&settings.executable), &arguments).unwrap());
assert!(helper.is_alive());
assert!(!verify_socket(&helper, endpoint, None).await.unwrap());
let listener = loopback_socket().unwrap().listen(128).unwrap();
let relay_endpoint = listener.local_addr().unwrap();
let task = tokio::spawn(relay(Arc::new(listener), endpoint, helper));
tokio::time::timeout(Duration::from_secs(10), async {
let mut db = TcpStream::connect(relay_endpoint).await.unwrap();
db.write_all(EXAMPLE).await.unwrap();
let (mut accepted, _) = unrelated.accept().await.unwrap();
assert_eq!(accepted.read_u8().await.unwrap_err().kind(), io::ErrorKind::UnexpectedEof);
task.await.unwrap();
})
.await
.unwrap();
}
#[tokio::test]
async fn a_dead_helper_keeps_its_relay_port_reserved_until_the_route_drops() {
let tunnel = ExternalTunnel::open(&config("once"), TARGET).await.unwrap();
let endpoint = SocketAddrV4::new(Ipv4Addr::LOCALHOST, tunnel.port());
tokio::time::timeout(Duration::from_secs(5), async {
let mut db = TcpStream::connect(endpoint).await.unwrap();
db.write_all(EXAMPLE).await.unwrap();
let mut bytes = [0; EXAMPLE.len()];
db.read_exact(&mut bytes).await.unwrap();
assert_eq!(&bytes, EXAMPLE);
db.read_u16().await.unwrap();
drop(db);
while !tunnel.is_closed() {
tokio::time::sleep(POLL_INTERVAL).await;
}
})
.await
.unwrap();
assert!(std::net::TcpListener::bind(endpoint).is_err());
}
#[test]
fn only_credential_free_proxy_addresses_reach_the_helper() {
assert!(credential_free_proxy("proxy.example:3128"));
assert!(credential_free_proxy("socks5h://proxy.example:1080"));
assert!(!credential_free_proxy("https://user:[email protected]:3128"));
assert!(!credential_free_proxy("https://proxy.example:3128/?secret=value"));
}
#[test]
fn expands_only_literal_arguments_and_validates_the_target() {
let settings = crate::DbExternalTunnel {
executable: config("echo").executable,
arguments: vec!["--port={localPort}".into(), "{host}:{port}".into(), "a b \"quotes\"".into()],
};
let arguments = helper_arguments(&settings, TARGET, 12345).unwrap();
assert_eq!(arguments, ["--port=12345", "db.example:5432", "a b \"quotes\""]);
assert!(helper_arguments(&settings, ("--some-option", 5432), 12345).is_err());
}
#[test]
fn brackets_an_ipv6_host_port_pair_but_preserves_the_raw_host_argument() {
let settings = crate::DbExternalTunnel {
executable: config("echo").executable,
arguments: vec!["{localPort}".into(), "{host}:{port}".into(), "{host}".into(), "[{host}]:{port}".into()],
};
let arguments = helper_arguments(&settings, ("[2001:db8::a]", 6432), 12345).unwrap();
assert_eq!(arguments, ["12345", "[2001:db8::a]:6432", "2001:db8::a", "[2001:db8::a]:6432"]);
}
@@ -0,0 +1,161 @@
use super::{Helper, io, process};
use std::net::{Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4};
use std::os::windows::io::{AsRawHandle, AsRawSocket, FromRawHandle, OwnedHandle};
use std::os::windows::process::CommandExt;
use std::process::Command;
use std::sync::Arc;
use tokio::net::TcpSocket;
use windows_sys::Win32::Foundation::{ERROR_INSUFFICIENT_BUFFER, INVALID_HANDLE_VALUE, NO_ERROR};
use windows_sys::Win32::NetworkManagement::IpHelper::{
GetExtendedTcpTable, MIB_TCP_STATE_ESTAB, MIB_TCP_STATE_LISTEN, MIB_TCP6ROW_OWNER_PID, MIB_TCPROW_OWNER_PID,
TCP_TABLE_OWNER_PID_ALL,
};
use windows_sys::Win32::Networking::WinSock::{
AF_INET, AF_INET6, SO_EXCLUSIVEADDRUSE, SOCKET_ERROR, SOL_SOCKET, WSAGetLastError, setsockopt,
};
use windows_sys::Win32::System::Diagnostics::ToolHelp::{
CreateToolhelp32Snapshot, TH32CS_SNAPTHREAD, THREADENTRY32, Thread32First, Thread32Next,
};
use windows_sys::Win32::System::Threading::{CREATE_SUSPENDED, OpenThread, ResumeThread, THREAD_SUSPEND_RESUME};
pub(super) fn make_exclusive(socket: &TcpSocket) -> io::Result<()> {
let enabled = 1i32;
// SAFETY: the socket is open and the option value remains valid for this call.
let result = unsafe {
setsockopt(
socket.as_raw_socket() as usize,
SOL_SOCKET,
SO_EXCLUSIVEADDRUSE,
(&raw const enabled).cast(),
size_of::<i32>() as i32,
)
};
if result == SOCKET_ERROR {
// SAFETY: reads the last Winsock error on the calling thread.
return Err(io::Error::from_raw_os_error(unsafe { WSAGetLastError() }));
}
Ok(())
}
pub(super) fn spawn_suspended(mut command: Command) -> io::Result<Helper> {
let mut child = command.creation_flags(CREATE_SUSPENDED | process::CREATE_NO_WINDOW).spawn()?;
let Some(job) = process::Job::for_child(&child) else {
// The child has never executed, so there are no descendants to terminate.
let _ = child.kill();
return Err(io::Error::other("could not contain the external tunnel helper in a Windows job"));
};
let helper = Helper { child: Some(child), job };
resume_initial_thread(helper.child().id())?;
Ok(helper)
}
fn resume_initial_thread(pid: u32) -> io::Result<()> {
// SAFETY: the snapshot handle is owned here, and each enumeration call writes a sized entry.
unsafe {
let snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
if snapshot == INVALID_HANDLE_VALUE {
return Err(io::Error::last_os_error());
}
let snapshot = OwnedHandle::from_raw_handle(snapshot);
let mut entry = THREADENTRY32 { dwSize: size_of::<THREADENTRY32>() as u32, ..Default::default() };
let mut has_entry = Thread32First(snapshot.as_raw_handle(), &mut entry);
while has_entry != 0 {
if entry.th32OwnerProcessID == pid {
let thread = OpenThread(THREAD_SUSPEND_RESUME, 0, entry.th32ThreadID);
if thread.is_null() {
return Err(io::Error::last_os_error());
}
let thread = OwnedHandle::from_raw_handle(thread);
return match ResumeThread(thread.as_raw_handle()) {
1 => Ok(()),
u32::MAX => Err(io::Error::last_os_error()),
_ => Err(io::Error::other("external tunnel helper was not in its initial suspended state")),
};
}
entry.dwSize = size_of::<THREADENTRY32>() as u32;
has_entry = Thread32Next(snapshot.as_raw_handle(), &mut entry);
}
}
Err(io::Error::other("could not find the external tunnel helper's suspended thread"))
}
pub(super) async fn owns_socket(helper: &Arc<Helper>, local: SocketAddr, peer: Option<SocketAddr>) -> io::Result<bool> {
let helper = Arc::clone(helper);
tokio::task::spawn_blocking(move || {
let state = if peer.is_some() { MIB_TCP_STATE_ESTAB as u32 } else { MIB_TCP_STATE_LISTEN as u32 };
let table = tcp_table(u32::from(AF_INET))?;
// SAFETY: this is the AF_INET owner-PID table, whose rows contain only integers.
for row in unsafe { rows::<MIB_TCPROW_OWNER_PID>(&table)? } {
if row.dwState == state
&& v4_address(row.dwLocalAddr, row.dwLocalPort) == local
&& peer.is_none_or(|peer| v4_address(row.dwRemoteAddr, row.dwRemotePort) == peer)
&& helper.job.contains_pid(row.dwOwningPid)
{
return Ok(true);
}
}
let table = tcp_table(u32::from(AF_INET6))?;
// SAFETY: this is the AF_INET6 owner-PID table, whose rows contain only integers.
for row in unsafe { rows::<MIB_TCP6ROW_OWNER_PID>(&table)? } {
if row.dwState == state
&& mapped_address(row.ucLocalAddr, row.dwLocalPort) == Some(local)
&& peer.is_none_or(|peer| mapped_address(row.ucRemoteAddr, row.dwRemotePort) == Some(peer))
&& helper.job.contains_pid(row.dwOwningPid)
{
return Ok(true);
}
}
Ok(false)
})
.await
.map_err(io::Error::other)?
}
fn v4_address(address: u32, port: u32) -> SocketAddr {
SocketAddrV4::new(Ipv4Addr::from(address.to_ne_bytes()), u16::from_be(port as u16)).into()
}
fn mapped_address(address: [u8; 16], port: u32) -> Option<SocketAddr> {
let address = Ipv6Addr::from(address).to_ipv4_mapped()?;
Some(SocketAddrV4::new(address, u16::from_be(port as u16)).into())
}
fn tcp_table(family: u32) -> io::Result<Vec<u32>> {
const MAX_TABLE: u32 = 8 * 1024 * 1024;
let mut size = 0;
let mut buffer = Vec::<u32>::new();
for _ in 0..3 {
// SAFETY: the buffer has the supplied capacity and u32 alignment for the owner-PID table.
let result = unsafe {
GetExtendedTcpTable(
if buffer.is_empty() { std::ptr::null_mut() } else { buffer.as_mut_ptr().cast() },
&mut size,
0,
family,
TCP_TABLE_OWNER_PID_ALL,
0,
)
};
match result {
NO_ERROR => return Ok(buffer),
ERROR_INSUFFICIENT_BUFFER if size <= MAX_TABLE => {
buffer.resize(size.div_ceil(size_of::<u32>() as u32) as usize, 0);
size = (buffer.len() * size_of::<u32>()) as u32;
}
_ => return Err(io::Error::from_raw_os_error(result as i32)),
}
}
Err(io::Error::other("the TCP socket ownership table did not stabilize"))
}
// `T` must be the matching Windows owner-PID row for this table, with no invalid bit patterns.
unsafe fn rows<T>(table: &[u32]) -> io::Result<&[T]> {
let Some((&count, data)) = table.split_first() else {
return Err(io::Error::other("missing TCP socket ownership table header"));
};
if align_of::<T>() > align_of::<u32>() || count as usize > std::mem::size_of_val(data) / size_of::<T>() {
return Err(io::Error::other("invalid TCP socket ownership table size"));
}
// SAFETY: the caller supplies the matching row layout; alignment and length are checked above.
Ok(unsafe { std::slice::from_raw_parts(data.as_ptr().cast(), count as usize) })
}
+1 -9
View File
@@ -1,6 +1,7 @@
//! A trusted local driver profile is shared by data sources. JDBC URLs and properties
//! can run driver-specific initialization. A project source may connect only with the
//! settings its user last accepted in the dialog; the approval lives outside the project.
use crate::local_settings::persist_local;
use crate::{DataSource, DbManager, QueryResult, ResultColumn};
use ide_core::{CancellationToken, IdeError, IdeResult};
use serde::{Deserialize, Serialize};
@@ -30,15 +31,6 @@ pub struct DbJdbcDriver {
pub url_template: String,
}
fn persist_local(path: &Path, data: &[u8]) -> IdeResult<()> {
let dir = path.parent().expect("registry paths have a parent");
std::fs::create_dir_all(dir)?;
let mut tmp = tempfile::NamedTempFile::new_in(dir)?;
std::io::Write::write_all(&mut tmp, data)?;
tmp.persist(path).map_err(|e| IdeError::from(e.error))?;
Ok(())
}
fn local_jar(jar: &str) -> IdeResult<&Path> {
if jar.contains(if cfg!(windows) { ';' } else { ':' }) {
return Err(IdeError::invalid("A JDBC JAR path contains the system classpath separator"));
+129 -150
View File
@@ -4,7 +4,12 @@
pub mod catalog;
mod clickhouse;
mod external_tunnel;
pub use external_tunnel::stop_external_tunnels_on_exit;
mod jdbc;
mod local_settings;
mod route;
mod tunnel_approval;
pub use jdbc::{DbJdbcDriver, jdbc_driver_classes};
pub mod conn;
pub mod history;
@@ -25,8 +30,8 @@ pub use conn::{Held, Pool, QueryResult, ResultColumn, TruncatedCell};
pub use history::HistoryEntry;
pub use plan::{PlanNode, PlanProperty};
pub use source::{
DataSource, DbColor, DbDriver, DbIntrospection, DbOptions, DbProperty, DbSchemaSelection, DbSnowflake,
DbSnowflakeAuth, DbSsh, DbSshAuth, DbSslMode, DbTxMode, DbVisibilityChange,
DataSource, DbColor, DbDriver, DbExternalTunnel, DbIntrospection, DbOptions, DbProperty, DbSchemaSelection,
DbSnowflake, DbSnowflakeAuth, DbSsh, DbSshAuth, DbSslMode, DbTxMode, DbVisibilityChange,
};
pub use sql::{CellValue, DbRowEdit, SortKey};
@@ -252,17 +257,14 @@ pub struct Databases {
/// Connections of one project's data sources, keyed by connection target (see [`split_target`]).
pub struct DbManager {
root: PathBuf,
pools: Mutex<HashMap<String, Arc<Pool>>>,
/// SSH tunnels by data source id, shared by the pools of its databases
/// (closed with the last of them).
tunnels: Mutex<HashMap<String, Arc<Tunnel>>>,
/// Serialises opening tunnels so concurrent connects share one.
tunnel_open: tokio::sync::Mutex<()>,
pools: Mutex<HashMap<String, Arc<route::ConnectionSlot>>>,
routes: route::Routes,
local_external_tunnels: bool,
/// App-wide SSH connections and host-key trust.
ssh: Arc<SshManager>,
saved_passwords: SecretStore,
saved_passwords: Arc<SecretStore>,
/// Directory of the global data sources and their saved passwords ([`DbManager::with_global_sources`]).
global: Option<(PathBuf, SecretStore)>,
global: Option<(PathBuf, Arc<SecretStore>)>,
history: Arc<HistoryStore>,
/// What introspection read of each data source, kept between runs.
catalogs: catalog::CatalogStore,
@@ -421,15 +423,15 @@ impl DbManager {
}
}
Self {
saved_passwords: SecretStore::new(passwords, &root),
saved_passwords: Arc::new(SecretStore::new(passwords, &root)),
global: None,
history,
catalogs,
recorder,
root,
pools: Mutex::default(),
tunnels: Mutex::default(),
tunnel_open: tokio::sync::Mutex::new(()),
routes: Mutex::default(),
local_external_tunnels: false,
ssh,
session_passwords: Mutex::default(),
on_disk: Mutex::default(),
@@ -441,7 +443,7 @@ impl DbManager {
/// Also lists the global data sources stored in `dir` (the app data directory).
pub fn with_global_sources(mut self, dir: PathBuf) -> Self {
let passwords = self.saved_passwords.scoped(&dir);
self.global = Some((dir, passwords));
self.global = Some((dir, Arc::new(passwords)));
self
}
@@ -471,7 +473,7 @@ impl DbManager {
}
}
fn store_of(&self, source: &DataSource) -> &SecretStore {
fn store_of(&self, source: &DataSource) -> &Arc<SecretStore> {
match &self.global {
Some((_, store)) if source.global => store,
_ => &self.saved_passwords,
@@ -511,13 +513,7 @@ impl DbManager {
.find(|s| s.id == id)
.ok_or_else(|| IdeError::not_found(format!("no data source {id}")))?
.resolved()?;
if let Some(db) = database {
// The configured schema belongs to the configured database.
if source.driver == DbDriver::Snowflake && !source.database.eq_ignore_ascii_case(db) {
source.options.default_schema.clear();
}
source.database = db.to_owned();
}
source.select_database(database);
Ok(source)
}
@@ -698,7 +694,10 @@ impl DbManager {
if !saved {
return None;
}
self.store_of(source).get(&key)
// The OS may wait for the user to unlock the credential store. A cancelled connection
// must be able to stop waiting without starting its helper when the prompt is answered.
let store = Arc::clone(self.store_of(source));
tokio::task::spawn_blocking(move || store.get(&key)).await.ok().flatten()
}
async fn password(&self, source: &DataSource) -> Option<String> {
@@ -736,36 +735,6 @@ impl DbManager {
}
}
/// Opens the SSH tunnel of `source` when it has one, returning the settings to
/// connect with (the tunnel's local end instead of the database host).
/// `shared` reuses (or registers) the data source's tunnel for its pools; Test
/// Connection opens a private one.
async fn endpoint(
&self,
source: &DataSource,
ssh_secret: Option<String>,
shared: bool,
) -> IdeResult<(DataSource, Option<Arc<Tunnel>>)> {
let Some(ssh) = source.ssh.as_ref().filter(|s| s.enabled && tunneled(source.driver)) else {
return Ok((source.clone(), None));
};
let local = |t: &Tunnel| DataSource { host: "127.0.0.1".into(), port: Some(t.port()), ..source.clone() };
let _opening = if shared { Some(self.tunnel_open.lock().await) } else { None };
if shared {
let existing = self.tunnels.lock().get(&source.id).filter(|t| !t.is_closed()).cloned();
if let Some(t) = existing {
return Ok((local(&t), Some(t)));
}
}
let session = self.ssh_session(source, ssh, ssh_secret).await?;
let (target_host, target_port) = tunnel_target(source);
let t = Arc::new(Tunnel::open(session, target_host, target_port).await?);
if shared {
self.tunnels.lock().insert(source.id.clone(), t.clone());
}
Ok((local(&t), Some(t)))
}
/// The SSH session the tunnel of `source` goes through: its shared SSH configuration's, or one
/// opened with the settings typed in the data source.
async fn ssh_session(
@@ -818,23 +787,35 @@ impl DbManager {
source: &DataSource,
password: Option<String>,
ssh_secret: Option<String>,
) -> IdeResult<String> {
if source.external_tunnel.is_some() {
return Err(IdeError::invalid("Review the external tunnel in the local Test Connection dialog"));
}
self.test_connection(source, password, ssh_secret, route::RouteUse::Test).await
}
pub async fn test_external_tunnel(&self, source: &DataSource, password: Option<String>) -> IdeResult<String> {
self.external_config(source)?;
self.test_connection(source, password, None, route::RouteUse::ReviewedExternalTest).await
}
async fn test_connection(
&self,
source: &DataSource,
password: Option<String>,
ssh_secret: Option<String>,
purpose: route::RouteUse,
) -> IdeResult<String> {
let source = &source.resolved()?;
let password = match password {
Some(p) => Some(p),
None => self.password(source).await,
};
let (target, tunnel) = self.endpoint(source, ssh_secret, false).await?;
let (target, _tunnel) = self.endpoint(source, ssh_secret, purpose).await?;
self.restore_sso(source).await;
let connected = self.open_pool(&target, password.as_deref(), true).await;
self.keep_sso(source).await;
let pool = connected.map_err(|e| {
through_tunnel(
e,
source,
tunnel.is_some().then(|| self.ssh_label(source.ssh.as_ref().expect("tunneled"))).as_deref(),
)
})?;
let pool = connected.map_err(|e| self.connection_error(e, source))?;
if let Pool::Jdbc(p) = &pool {
let version = p.version.clone();
pool.close().await;
@@ -855,7 +836,8 @@ impl DbManager {
_ => pool.rows(version, 1).await,
};
pool.close().await;
let strict = matches!(source.driver, DbDriver::Clickhouse | DbDriver::Snowflake);
let strict =
source.external_tunnel.is_some() || matches!(source.driver, DbDriver::Clickhouse | DbDriver::Snowflake);
let rows = if strict { result? } else { result.unwrap_or_default() };
let v = rows.into_iter().next().and_then(|r| r.into_iter().next().flatten());
Ok(v.unwrap_or_else(|| "Connected".into()))
@@ -881,11 +863,15 @@ impl DbManager {
if source.driver != tool.driver() {
return Err(IdeError::invalid(format!("{} cannot connect to {}", tool.program(), source.name)));
}
self.pool(id).await?;
// Keep the same route as the connected pool for the entire tool invocation.
let connection = self.connection(id).await?;
let target = connection.target(&source);
let password = self.password(&source).await;
// Holding the tunnel keeps it open while the tool runs, even if the tree disconnects.
let (target, _tunnel) = self.endpoint(&source, None, true).await?;
let prepared = tools::prepare(job, executable, &target, password.as_deref())?;
let mut prepared = tools::prepare(job, executable, &target, password.as_deref())?;
if source.external_tunnel.is_some() {
// libpq gives PGHOSTADDR precedence over --host when choosing the TCP peer.
prepared.env.push(("PGHOSTADDR".into(), target.host.clone()));
}
tools::run(executable, &prepared.args, &prepared.env, prepared.input.as_deref(), cancel, on_output).await
}
@@ -911,90 +897,6 @@ impl DbManager {
.ok_or_else(|| IdeError::internal("no server version"))
}
pub fn is_connected(&self, id: &str) -> bool {
self.pools.lock().get(id).is_some_and(|p| !p.is_closed())
}
/// Connected targets (data source ids, `<id>:<database>`).
pub fn connected(&self) -> Vec<String> {
self.pools.lock().iter().filter(|(_, p)| !p.is_closed()).map(|(id, _)| id.clone()).collect()
}
/// The pool of target `id`, connecting first if needed.
pub async fn pool(&self, id: &str) -> IdeResult<Arc<Pool>> {
let (source_id, _) = split_target(id);
// A dropped SSH session leaves every pool through it unusable: start over.
if self.tunnels.lock().get(source_id).is_some_and(|t| t.is_closed()) {
self.disconnect_source(source_id).await;
}
let cached = self.pools.lock().get(id).cloned();
if let Some(p) = cached {
if !p.is_closed() {
return Ok(p);
}
// The connection broke (a custom JDBC session whose TCP connection was dropped): reconnect.
self.disconnect(id).await;
}
let source = self.source(id)?;
let password = self.password(&source).await;
let (target, tunnel) = self.endpoint(&source, None, true).await?;
self.restore_sso(&source).await;
let connected = self.open_pool(&target, password.as_deref(), false).await;
self.keep_sso(&source).await;
let pool = match connected {
Ok(p) => Arc::new(p),
Err(e) => {
self.drop_unused_tunnel(source_id);
return Err(through_tunnel(
e,
&source,
tunnel.is_some().then(|| self.ssh_label(source.ssh.as_ref().expect("tunneled"))).as_deref(),
));
}
};
// Another caller may have connected meanwhile; keep theirs.
let kept = self.pools.lock().entry(id.to_owned()).or_insert_with(|| pool.clone()).clone();
if !Arc::ptr_eq(&kept, &pool) {
// Ours lost the race: close it rather than leave its session open on the server.
pool.close().await;
} else if let Some(secs) = source.options.keep_alive_secs.filter(|s| *s > 0) {
keep_alive(&pool, Duration::from_secs(secs.into()));
}
Ok(kept)
}
/// Closes the tunnel of `source_id` once none of its targets is connected.
fn drop_unused_tunnel(&self, source_id: &str) {
let in_use = self.pools.lock().keys().any(|k| split_target(k).0 == source_id);
if !in_use {
self.tunnels.lock().remove(source_id);
}
}
/// Disconnects target `id` (one database of a data source).
pub async fn disconnect(&self, id: &str) {
// A held connection would keep the pool from closing; manual mode stays on.
let session = self.sessions.lock().get(id).cloned();
if let Some(s) = session {
end_session(&s).await;
}
self.cursors.release_target(id);
let pool = self.pools.lock().remove(id);
if let Some(p) = pool {
p.close().await;
}
self.drop_unused_tunnel(split_target(id).0);
}
/// Disconnects every database of data source `id`.
pub async fn disconnect_source(&self, id: &str) {
let targets: Vec<String> = self.pools.lock().keys().filter(|t| split_target(t).0 == id).cloned().collect();
for t in targets {
self.disconnect(&t).await;
}
self.tunnels.lock().remove(id);
}
/// Creates a database on the server of data source `id` by running `statement` on the data
/// source's own database, after closing the IDE's connections to `template`, the database
/// the server copies (PostgreSQL and SQL Server refuse to copy one that has sessions).
@@ -1865,6 +1767,83 @@ mod tests {
DbManager::new(dir.join("project"), data.join("db-passwords.json"), data.join("db-history.json"), ssh)
}
#[tokio::test]
async fn external_tunnel_approval_binds_the_command_destination_and_local_scope() {
let tmp = tempfile::tempdir().unwrap();
#[cfg(windows)]
let name = "forward.exe";
#[cfg(not(windows))]
let name = "forward";
let program = tmp.path().join(name);
std::fs::write(&program, b"fixture version 1").unwrap();
let app = tmp.path().join("app");
let desktop = |root: &Path| manager(root).with_global_sources(app.clone()).with_local_external_tunnels(true);
let db = desktop(tmp.path());
let other = desktop(&tmp.path().join("other"));
let mut source = DataSource {
id: "pg".into(),
name: "Example PostgreSQL".into(),
driver: DbDriver::Postgres,
host: "db.example".into(),
external_tunnel: Some(DbExternalTunnel {
executable: program.to_str().unwrap().into(),
arguments: vec!["--listen={localPort}".into(), "{host}:{port}".into()],
}),
..Default::default()
};
assert!(db.check_external_approval(&source).await.is_err());
db.approve_external_tunnel(&source).await.unwrap();
db.save_sources(vec![source.clone()]).await.unwrap();
db.check_external_approval(&db.source("pg").unwrap()).await.unwrap();
db.check_external_approval(&source).await.unwrap();
assert!(other.check_external_approval(&source).await.is_err());
for changed in [
DataSource { host: "other.example".into(), ..source.clone() },
DataSource { user: "other".into(), ..source.clone() },
DataSource { ssl: DbSslMode::Require, ..source.clone() },
] {
assert!(db.check_external_approval(&changed).await.is_err());
}
let mut changed = source.clone();
changed.external_tunnel.as_mut().unwrap().arguments.push("--changed".into());
assert!(db.check_external_approval(&changed).await.is_err());
source.global = true;
assert!(db.check_external_approval(&source).await.is_err());
db.approve_external_tunnel(&source).await.unwrap();
db.save_sources(vec![source.clone()]).await.unwrap();
db.check_external_approval(&db.source("pg").unwrap()).await.unwrap();
other.check_external_approval(&source).await.unwrap();
std::fs::write(&program, b"fixture version 2").unwrap();
assert!(db.check_external_approval(&source).await.is_err());
}
#[tokio::test]
async fn external_tunnel_rejects_incompatible_modes_and_implicit_test() {
let tmp = tempfile::tempdir().unwrap();
let source = DataSource {
id: "pg".into(),
driver: DbDriver::Postgres,
external_tunnel: Some(DbExternalTunnel {
executable: std::env::current_exe().unwrap().to_str().unwrap().into(),
arguments: vec!["{localPort}".into()],
}),
..Default::default()
};
let remote = manager(tmp.path()).with_global_sources(tmp.path().join("app"));
assert!(remote.test_external_tunnel(&source, None).await.is_err());
let db = remote.with_local_external_tunnels(true);
assert!(db.test(&source, None, None).await.is_err());
for bad in [
DataSource { ssl: DbSslMode::VerifyFull, ..source.clone() },
DataSource { url_only: true, ..source.clone() },
DataSource { plugin_owner: Some("sample".into()), ..source.clone() },
DataSource { driver: DbDriver::Jdbc, ..source.clone() },
DataSource { ssh: Some(DbSsh { enabled: true, ..Default::default() }), ..source.clone() },
] {
assert!(db.approve_external_tunnel(&bad).await.is_err());
}
}
#[tokio::test]
async fn saved_passwords_stay_off_disk() {
let tmp = tempfile::tempdir().unwrap();
+11
View File
@@ -0,0 +1,11 @@
use ide_core::{IdeError, IdeResult};
use std::path::Path;
pub(super) fn persist_local(path: &Path, data: &[u8]) -> IdeResult<()> {
let dir = path.parent().expect("registry paths have a parent");
std::fs::create_dir_all(dir)?;
let mut tmp = tempfile::NamedTempFile::new_in(dir)?;
std::io::Write::write_all(&mut tmp, data)?;
tmp.persist(path).map_err(|e| IdeError::from(e.error))?;
Ok(())
}
+251
View File
@@ -0,0 +1,251 @@
//! A connection target owns its pool and keeps its data source's forwarding route alive.
//! Concurrent opens of sibling databases share a helper, but unrelated sources never wait on it.
use super::*;
use external_tunnel::ExternalTunnel;
use std::sync::Weak;
use tokio::sync::OnceCell;
#[derive(Clone, Copy, PartialEq, Eq)]
pub(super) enum RouteUse {
Connect,
Test,
ReviewedExternalTest,
}
pub(super) enum Route {
Ssh(Tunnel),
External(ExternalTunnel),
}
impl Route {
fn port(&self) -> u16 {
match self {
Self::Ssh(t) => t.port(),
Self::External(t) => t.port(),
}
}
fn is_closed(&self) -> bool {
match self {
Self::Ssh(t) => t.is_closed(),
Self::External(t) => t.is_closed(),
}
}
}
type RouteSlot = Arc<OnceCell<Route>>;
// The file watcher may observe a source edit after a new caller already read it.
pub(super) struct CachedRoute {
host: String,
port: u16,
ssh: Option<DbSsh>,
helper: Option<DbExternalTunnel>,
slot: Weak<OnceCell<Route>>,
}
impl CachedRoute {
fn matches(&self, source: &DataSource) -> bool {
let (host, port) = tunnel_target(source);
self.host == host && self.port == port && self.ssh == source.ssh && self.helper == source.external_tunnel
}
}
pub(super) type Routes = Mutex<HashMap<String, CachedRoute>>;
#[derive(Clone)]
pub(super) struct Connection {
pub(super) pool: Arc<Pool>,
route: Option<RouteSlot>,
}
impl Connection {
pub(super) fn target(&self, source: &DataSource) -> DataSource {
routed_target(source, self.route.as_ref())
}
fn is_closed(&self) -> bool {
self.pool.is_closed() || self.route.as_ref().and_then(|s| s.get()).is_some_and(Route::is_closed)
}
}
#[derive(Default)]
pub(super) struct ConnectionSlot {
pub(super) value: OnceCell<Connection>,
pub(super) cancel: CancellationToken,
}
fn routed_target(source: &DataSource, slot: Option<&RouteSlot>) -> DataSource {
match slot.and_then(|s| s.get()) {
Some(route) => DataSource { host: "127.0.0.1".into(), port: Some(route.port()), ..source.clone() },
None => source.clone(),
}
}
impl DbManager {
pub(super) async fn endpoint(
&self,
source: &DataSource,
ssh_secret: Option<String>,
purpose: RouteUse,
) -> IdeResult<(DataSource, Option<RouteSlot>)> {
let external = source.external_tunnel.as_ref();
let ssh = source.ssh.as_ref().filter(|ssh| ssh.enabled && tunneled(source.driver));
if external.is_none() && ssh.is_none() {
return Ok((source.clone(), None));
}
if external.is_some() {
match purpose {
RouteUse::Connect => self.check_external_approval(source).await?,
RouteUse::ReviewedExternalTest => {
self.external_config(source)?;
}
RouteUse::Test => {
return Err(IdeError::invalid("Review the external tunnel in the local Test Connection dialog"));
}
}
}
let slot = if purpose == RouteUse::Connect {
let mut routes = self.routes.lock();
if let Some(slot) = routes.get(&source.id).filter(|r| r.matches(source)).and_then(|r| r.slot.upgrade())
&& !slot.get().is_some_and(Route::is_closed)
{
slot
} else {
routes.retain(|_, r| r.slot.strong_count() > 0);
let slot = Arc::new(OnceCell::new());
let (host, port) = tunnel_target(source);
routes.insert(
source.id.clone(),
CachedRoute {
host: host.to_owned(),
port,
ssh: source.ssh.clone(),
helper: source.external_tunnel.clone(),
slot: Arc::downgrade(&slot),
},
);
slot
}
} else {
Arc::new(OnceCell::new())
};
slot.get_or_try_init(|| async {
if let Some(config) = external {
ExternalTunnel::open(config, tunnel_target(source)).await.map(Route::External)
} else {
let ssh = ssh.expect("enabled SSH transport");
let session = self.ssh_session(source, ssh, ssh_secret).await?;
let (host, port) = tunnel_target(source);
Tunnel::open(session, host, port).await.map(Route::Ssh)
}
})
.await?;
Ok((routed_target(source, Some(&slot)), Some(slot)))
}
pub(super) fn connection_error(&self, error: IdeError, source: &DataSource) -> IdeError {
if source.external_tunnel.is_some() && error.kind == ErrorKind::Io {
return IdeError::new(error.kind, format!("{} through the external database tunnel", error.message));
}
let via = source.ssh.as_ref().filter(|s| s.enabled && tunneled(source.driver)).map(|ssh| self.ssh_label(ssh));
through_tunnel(error, source, via.as_deref())
}
pub fn is_connected(&self, id: &str) -> bool {
self.pools.lock().get(id).and_then(|slot| slot.value.get()).is_some_and(|c| !c.is_closed())
}
pub fn connected(&self) -> Vec<String> {
self.pools
.lock()
.iter()
.filter(|(_, s)| s.value.get().is_some_and(|c| !c.is_closed()))
.map(|(id, _)| id.clone())
.collect()
}
pub async fn pool(&self, id: &str) -> IdeResult<Arc<Pool>> {
Ok(self.connection(id).await?.pool)
}
pub(super) async fn connection(&self, id: &str) -> IdeResult<Connection> {
let (slot, stale) = {
let mut pools = self.pools.lock();
let stale = if pools.get(id).and_then(|s| s.value.get()).is_some_and(Connection::is_closed) {
pools.remove(id)
} else {
None
};
(pools.entry(id.into()).or_default().clone(), stale)
};
if let Some(stale) = stale {
self.close_target(id, stale).await;
}
let result = tokio::select! {
biased;
_ = slot.cancel.cancelled() => Err(IdeError::cancelled()),
result = slot.value.get_or_try_init(|| self.open_connection(id)) => result.cloned(),
};
if result.is_err() {
let mut pools = self.pools.lock();
if Arc::strong_count(&slot) == 2 && pools.get(id).is_some_and(|s| Arc::ptr_eq(s, &slot)) {
pools.remove(id);
}
}
result
}
async fn open_connection(&self, id: &str) -> IdeResult<Connection> {
let (source_id, database) = split_target(id);
let mut source = self.source(source_id)?;
let password = self.password(&source).await;
// The approval belongs to the configured source, including its login database.
// Sibling database selection changes only the driver's target after routing.
let (mut target, route) = self.endpoint(&source, None, RouteUse::Connect).await?;
target.select_database(database);
source.select_database(database);
self.restore_sso(&source).await;
let result = self.open_pool(&target, password.as_deref(), false).await;
self.keep_sso(&source).await;
let pool = Arc::new(result.map_err(|e| self.connection_error(e, &source))?);
if let Some(secs) = source.options.keep_alive_secs.filter(|s| *s > 0) {
keep_alive(&pool, Duration::from_secs(secs.into()));
}
Ok(Connection { pool, route })
}
async fn close_target(&self, id: &str, slot: Arc<ConnectionSlot>) {
slot.cancel.cancel();
// A held transaction or result cursor keeps the pool from closing.
let session = self.sessions.lock().get(id).cloned();
if let Some(s) = session {
end_session(&s).await;
}
self.cursors.release_target(id);
if let Some(c) = slot.value.get() {
c.pool.close().await;
}
}
pub async fn disconnect(&self, id: &str) {
let slot = self.pools.lock().remove(id);
if let Some(slot) = slot {
self.close_target(id, slot).await;
}
}
pub async fn disconnect_source(&self, id: &str) {
let closing: Vec<_> = {
let mut pools = self.pools.lock();
let mut routes = self.routes.lock();
routes.remove(id);
pools.extract_if(|key, _| split_target(key).0 == id).collect()
};
for (_, slot) in &closing {
slot.cancel.cancel();
}
for (target, slot) in closing {
self.close_target(&target, slot).await;
}
}
}
+21
View File
@@ -296,6 +296,14 @@ pub struct DbSsh {
pub save_secret: bool,
}
/// A foreground program that forwards an IDE-assigned loopback port to the database.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct DbExternalTunnel {
pub executable: String,
pub arguments: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase", default)]
pub struct DataSource {
@@ -318,6 +326,8 @@ pub struct DataSource {
pub read_only: bool,
/// SSH tunnel settings (`None`: never configured; kept but unused when not `enabled`).
pub ssh: Option<DbSsh>,
#[serde(skip_serializing_if = "Option::is_none")]
pub external_tunnel: Option<DbExternalTunnel>,
/// Wire-compatible product preset (`cockroachdb`, `tidb`…; empty: the driver itself).
pub vendor: String,
pub color: Option<DbColor>,
@@ -361,6 +371,7 @@ impl Default for DataSource {
save_password: false,
read_only: false,
ssh: None,
external_tunnel: None,
vendor: String::new(),
color: None,
comment: String::new(),
@@ -501,6 +512,16 @@ pub fn parse_url(raw: &str) -> IdeResult<ParsedUrl> {
}
impl DataSource {
pub(crate) fn select_database(&mut self, database: Option<&str>) {
if let Some(db) = database {
// The configured schema belongs to the configured database.
if self.driver == DbDriver::Snowflake && !self.database.eq_ignore_ascii_case(db) {
self.options.default_schema.clear();
}
self.database = db.to_owned();
}
}
pub(crate) fn same_except_visibility(&self, other: &Self) -> bool {
if self == other {
return true;
+103
View File
@@ -0,0 +1,103 @@
//! Only an explicit desktop action can trust a helper. The project file is portable;
//! the authorization belongs to this machine and to the reviewed destination.
use crate::{DataSource, DbDriver, DbExternalTunnel, DbManager, DbSslMode, local_settings::persist_local};
use ide_core::{IdeError, IdeResult};
use std::path::{Path, PathBuf};
impl DbManager {
pub fn with_local_external_tunnels(mut self, enabled: bool) -> Self {
self.local_external_tunnels = enabled;
self
}
pub(super) fn external_config<'a>(&self, source: &'a DataSource) -> IdeResult<&'a DbExternalTunnel> {
if !self.local_external_tunnels {
return Err(IdeError::invalid("External database tunnels require a local desktop project"));
}
if source.driver != DbDriver::Postgres || source.plugin_owner.is_some() || source.url_only {
return Err(IdeError::invalid(
"Use a user-managed PostgreSQL source with host and port for an external tunnel",
));
}
if source.ssh.as_ref().is_some_and(|ssh| ssh.enabled) {
return Err(IdeError::invalid("Choose either SSH or an external tunnel"));
}
if source.ssl == DbSslMode::VerifyFull {
return Err(IdeError::invalid(
"Verify Full needs the remote TLS hostname, which this tunnel transport cannot supply",
));
}
let config =
source.external_tunnel.as_ref().ok_or_else(|| IdeError::invalid("Choose an external tunnel helper"))?;
crate::external_tunnel::ExternalTunnel::validate(config, crate::tunnel_target(source))?;
Ok(config)
}
fn external_approval(&self, source: &DataSource) -> IdeResult<(PathBuf, String)> {
let config = self.external_config(source)?;
let dir = &self.global.as_ref().ok_or_else(|| IdeError::invalid("Local database settings unavailable"))?.0;
let key = serde_json::to_vec(&((!source.global).then_some(&self.root), &source.id))
.map_err(|e| IdeError::internal(e.to_string()))?;
let settings = serde_json::to_vec(&(
config,
crate::tunnel_target(source),
&source.user,
&source.database,
&source.ssl,
&source.ssl_ca_file,
&source.ssl_cert_file,
&source.ssl_key_file,
source.read_only,
&source.properties,
&source.options,
))
.map_err(|e| IdeError::internal(e.to_string()))?;
Ok((
dir.join("database-tunnel-approvals").join(blake3::hash(&key).to_hex().as_str()),
blake3::hash(&settings).to_string(),
))
}
/// Called only after the local connection dialog shows the executable, arguments and destination.
pub async fn approve_external_tunnel(&self, source: &DataSource) -> IdeResult<()> {
let (path, settings) = self.external_approval(source)?;
let program = self.external_config(source)?.executable.clone();
tokio::task::spawn_blocking(move || {
let identity = executable_identity(Path::new(&program))?;
persist_local(&path, format!("{settings}\n{identity}").as_bytes())
})
.await
.map_err(|e| IdeError::internal(e.to_string()))?
}
pub(super) async fn check_external_approval(&self, source: &DataSource) -> IdeResult<()> {
let (path, settings) = self.external_approval(source)?;
let program = self.external_config(source)?.executable.clone();
tokio::task::spawn_blocking(move || {
let review = || {
IdeError::invalid("Review the external tunnel in SSH/SSL and save the data source before connecting")
};
let approval = std::fs::read_to_string(path).map_err(|_| review())?;
let (saved, identity) = approval.split_once('\n').ok_or_else(review)?;
// Avoid touching a program named by an unapproved project file.
if saved != settings || identity != executable_identity(Path::new(&program))? {
return Err(review());
}
Ok(())
})
.await
.map_err(|e| IdeError::internal(e.to_string()))?
}
}
fn executable_identity(program: &Path) -> IdeResult<String> {
let path = std::fs::canonicalize(program)?;
if !path.is_file() {
return Err(IdeError::invalid("The external tunnel helper must be an executable file"));
}
let mut hash = blake3::Hasher::new();
hash.update(path.as_os_str().as_encoded_bytes());
hash.update(&[0]);
hash.update_reader(std::fs::File::open(path)?)?;
Ok(hash.finalize().to_string())
}
+174
View File
@@ -44,6 +44,33 @@ async fn create_schemas(db: &DbManager) {
}
}
#[tokio::test]
async fn postgres_read_only_is_checked_before_and_after_startup_sql() -> IdeResult<()> {
use ide_db::{DbProperty, Pool};
let Some((host, port, user, password)) = server() else { return Ok(()) };
let mut source =
DataSource { driver: DbDriver::Postgres, host, port: Some(port), user, read_only: true, ..Default::default() };
let pool = Pool::connect(&source, Some(&password), None).await?;
assert_eq!(pool.rows("SHOW transaction_read_only", 1).await?, [[Some("on".into())]]);
pool.close().await;
// Exercise the same server response as a pooler that ignored the startup option.
source.properties.push(DbProperty { name: "default_transaction_read_only".into(), value: "off".into() });
source.options.startup_script = "SELECT 1/0".into();
let err = Pool::connect(&source, Some(&password), None).await.err().expect("writable connection");
assert!(err.message.contains("did not enable the requested default_transaction_read_only"), "{}", err.message);
source.properties.clear();
source.options.startup_script = "SET SESSION CHARACTERISTICS AS TRANSACTION READ WRITE".into();
let err = Pool::connect(&source, Some(&password), None).await.err().expect("startup script disabled read-only");
assert!(err.message.contains("did not enable the requested default_transaction_read_only"), "{}", err.message);
source.options.startup_script = "BEGIN READ WRITE".into();
let err = Pool::connect(&source, Some(&password), None).await.err().expect("writable startup transaction");
assert!(err.message.contains("writable transaction"), "{}", err.message);
source.options.startup_script = "BEGIN READ ONLY".into();
Pool::connect(&source, Some(&password), None).await?.close().await;
Ok(())
}
#[tokio::test]
async fn active_schema_context_drives_the_executing_connection() -> IdeResult<()> {
let tmp = tempfile::tempdir().unwrap();
@@ -398,3 +425,150 @@ async fn cancelling_a_later_page_stops_its_statement_on_the_server() -> IdeResul
assert_eq!(running, 0, "the cancelled statement still runs on the server");
Ok(())
}
// The same test executable serves as a foreground TCP forwarder for the managed-route test.
#[test]
fn postgres_tunnel_fixture() {
use std::io::{Write, copy};
use std::net::{Ipv4Addr, Shutdown, TcpListener, TcpStream};
let flag = |prefix: &str| std::env::args().find_map(|s| s.strip_prefix(prefix).map(String::from));
let Some(port) = flag("listen=") else { return };
if let Some(file) = flag("waiting=") {
std::fs::write(file, port.as_bytes()).unwrap();
std::thread::sleep(std::time::Duration::from_secs(60));
return;
}
let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, port.parse::<u16>().unwrap())).unwrap();
let log = flag("start-log=").unwrap();
let mut file = std::fs::OpenOptions::new().append(true).create(true).open(log).unwrap();
writeln!(file, "{port}").unwrap();
let destination = flag("forward=").unwrap();
for stream in listener.incoming() {
let mut client = stream.unwrap();
let dest = destination.clone();
std::thread::spawn(move || {
let mut remote = TcpStream::connect(dest).unwrap();
let mut input = client.try_clone().unwrap();
let mut output = remote.try_clone().unwrap();
std::thread::spawn(move || {
let _ = copy(&mut input, &mut output);
let _ = output.shutdown(Shutdown::Write);
});
let _ = copy(&mut remote, &mut client);
let _ = client.shutdown(Shutdown::Write);
});
}
}
#[tokio::test]
async fn managed_tunnel_shares_the_forwarder_and_closes_it_after_the_last_target() -> IdeResult<()> {
let Some((host, port, user, password)) = server() else { return Ok(()) };
let tmp = tempfile::tempdir()?;
let root = tmp.path();
let log = root.join("starts");
let ssh = std::sync::Arc::new(ide_ssh::SshManager::new(root.join("ssh-secrets")));
let db = DbManager::new(root.into(), root.join("passwords.json"), root.join("history.json"), ssh)
.with_global_sources(root.join("app"))
.with_local_external_tunnels(true);
let source = DataSource {
id: "tunnel".into(),
name: "Tunnel fixture".into(),
driver: DbDriver::Postgres,
host,
port: Some(port),
user,
database: "postgres".into(),
read_only: true,
external_tunnel: Some(ide_db::DbExternalTunnel {
executable: std::env::current_exe()?.to_string_lossy().into_owned(),
arguments: vec![
"--exact".into(),
"postgres_tunnel_fixture".into(),
"--skip".into(),
"listen={localPort}".into(),
"--skip".into(),
"forward={host}:{port}".into(),
"--skip".into(),
format!("start-log={}", log.display()),
],
}),
..Default::default()
};
db.save_sources(vec![source.clone()]).await?;
db.set_password("tunnel", Some(password), false).await?;
assert!(db.pool("tunnel").await.is_err());
assert!(!log.exists());
assert!(db.test_external_tunnel(&source, None).await?.contains("PostgreSQL"));
assert!(db.pool("tunnel").await.is_err(), "Test must not persist launch approval");
db.approve_external_tunnel(&source).await?;
let (a, b) = tokio::try_join!(db.pool("tunnel"), db.pool("tunnel:postgres"))?;
assert_eq!(std::fs::read_to_string(&log)?.lines().count(), 2, "one test helper and one pooled helper");
assert!(db.is_connected("tunnel") && db.is_connected("tunnel:postgres"));
drop((a, b));
db.disconnect("tunnel").await;
let result = db.execute("tunnel:postgres", "SELECT 1", 1, &CancellationToken::new()).await?;
assert_eq!(result.rows, vec![vec![Some("1".to_owned())]]);
db.disconnect_source("tunnel").await;
let ports: Vec<u16> = std::fs::read_to_string(log)?.lines().map(|p| p.parse().unwrap()).collect();
tokio::time::timeout(std::time::Duration::from_secs(5), async {
for port in ports {
while tokio::net::TcpStream::connect(("127.0.0.1", port)).await.is_ok() {
tokio::time::sleep(std::time::Duration::from_millis(20)).await;
}
}
})
.await
.expect("both helpers must stop");
Ok(())
}
#[tokio::test]
async fn external_startup_does_not_block_another_source_and_disconnect_cancels_it() -> IdeResult<()> {
let tmp = tempfile::tempdir()?;
let dir = tmp.path();
let ssh = std::sync::Arc::new(ide_ssh::SshManager::new(dir.join("ssh-secrets")));
let db = DbManager::new(dir.into(), dir.join("passwords.json"), dir.join("history.json"), ssh)
.with_global_sources(dir.join("app"))
.with_local_external_tunnels(true);
let waiting = dir.join("starting");
let pending = DataSource {
id: "pending".into(),
name: "Starting helper".into(),
driver: DbDriver::Postgres,
host: "db.example".into(),
external_tunnel: Some(ide_db::DbExternalTunnel {
executable: std::env::current_exe()?.to_string_lossy().into_owned(),
arguments: vec![
"--exact".into(),
"postgres_tunnel_fixture".into(),
"--skip".into(),
"listen={localPort}".into(),
"--skip".into(),
format!("waiting={}", waiting.display()),
],
}),
..Default::default()
};
let file = dir.join("local.db");
std::fs::File::create(&file)?;
let sqlite =
DataSource { id: "local".into(), name: "SQLite fixture".into(), file: Some(file.into()), ..Default::default() };
db.approve_external_tunnel(&pending).await?;
db.save_sources(vec![pending, sqlite]).await?;
let connect = db.pool("pending");
let edit = async {
while !waiting.exists() {
tokio::time::sleep(std::time::Duration::from_millis(20)).await;
}
db.pool("local").await?;
assert!(db.is_connected("local"));
db.disconnect_source("pending").await;
Ok::<_, ide_core::IdeError>(())
};
let (result, edit) = tokio::time::timeout(std::time::Duration::from_secs(8), async { tokio::join!(connect, edit) })
.await
.expect("the pending PostgreSQL helper must not block SQLite or disconnect");
edit?;
assert!(matches!(result, Err(error) if error.kind == ide_core::error::ErrorKind::Cancelled));
Ok(())
}
+1
View File
@@ -68,6 +68,7 @@ specta.workspace = true
specta-typescript.workspace = true
tokio = { workspace = true, features = ["io-std"] }
tracing.workspace = true
url = "2"
tracing-subscriber.workspace = true
parking_lot.workspace = true
dunce.workspace = true
+10
View File
@@ -82,6 +82,7 @@ impl HostConfig {
}
pub struct Host {
local_database_tunnels: bool,
pub(crate) mcp_executable: Arc<RwLock<Option<PathBuf>>>,
pub mcp: mcp::McpService,
plugin_host: RwLock<std::sync::Weak<plugins::PluginHost>>,
@@ -106,6 +107,7 @@ pub struct Host {
syntax: Arc<OnceLock<Arc<Syntax>>>,
pub global_settings: SettingsStore,
pub dependency_versions: Arc<ide_workspace::dependencies::VersionCache>,
pub pypi_names: Arc<ide_workspace::dependencies::pypi::NameCache>,
pub terminals: TerminalManager,
pub processes: ProcessManager,
/// Debug sessions (adapters run on this machine, next to the project).
@@ -165,6 +167,12 @@ impl Host {
windows
}
/// Enables user-approved database helper processes on the local desktop.
pub fn with_local_database_tunnels(mut self) -> Self {
self.local_database_tunnels = true;
self
}
pub fn new(config: HostConfig) -> Self {
let HostConfig {
config_dir,
@@ -185,6 +193,7 @@ impl Host {
ssh.set_configs(global_settings.effective().ssh.configs);
let host = Self {
plugin_host: RwLock::default(),
local_database_tunnels: false,
mcp_executable: Arc::default(),
mcp: Default::default(),
diagnostics,
@@ -207,6 +216,7 @@ impl Host {
dependency_versions: Arc::new(ide_workspace::dependencies::VersionCache::new(
data_dir.join("cache/dependency-versions"),
)),
pypi_names: Arc::new(ide_workspace::dependencies::pypi::NameCache::new(data_dir.join("cache"))),
// Sessions, runs and terminals report to the window that started them (`window_sink`).
terminals: TerminalManager::new(),
processes: ProcessManager::new(),
+1
View File
@@ -870,6 +870,7 @@ async fn occurrences(
max_matches: 0,
context,
include_excluded: false,
skip_large_files: false,
};
let host = call.host();
let request = crate::mcp::tool::request_id();
+1
View File
@@ -650,6 +650,7 @@ async fn text_search(call: Call, is_regex: bool) -> IdeResult<Output> {
max_matches,
context: Default::default(),
include_excluded: call.flag("includeExcluded", false)?,
skip_large_files: false,
};
if is_regex && let Err(e) = ide_search::match_ranges("", &query) {
return Err(IdeError::invalid(format!("Invalid regex pattern: {pattern} ({})", e.message)));
+25 -43
View File
@@ -1,6 +1,6 @@
//! Agents tool window: coding agent tasks of the project (over ACP). In a remote
//! window they run on the host, next to the project they work on.
use super::Channel;
use super::{Channel, blocking, blocking_value};
use crate::Host;
use crate::agent_secrets::{AgentSecrets, Kept};
use ide_agent::registry::{AgentRegistry, RegistryPaths};
@@ -63,9 +63,7 @@ pub async fn agent_providers(host: &Host, window: &str) -> IdeResult<Vec<AgentPr
pub async fn agent_hermes_profiles(host: &Host, window: &str) -> IdeResult<Vec<ide_agent::hermes::HermesProfile>> {
host.require_trust(window)?;
let root = ide_agent::hermes::root(dirs::home_dir().as_deref());
tokio::task::spawn_blocking(move || root.map(|r| ide_agent::hermes::labeled_profiles(&r)).unwrap_or_default())
.await
.map_err(join_err)
blocking_value(move || root.map(|r| ide_agent::hermes::labeled_profiles(&r)).unwrap_or_default()).await
}
/// Refreshes the model catalog; force bypasses freshness, not the cooldown.
@@ -126,20 +124,15 @@ pub(crate) fn registry_paths(host: &Host) -> RegistryPaths {
RegistryPaths::new(&host.config_dir, &host.local_data_dir)
}
fn join_err(e: impl std::fmt::Display) -> IdeError {
IdeError::internal(e.to_string())
}
/// Agents of the ACP Registry this machine can run, with what is installed; the list
/// saved earlier when the registry is unreachable. Cancel with `cancel_request(request)`.
#[command(trust = always)]
pub async fn agent_registry_list(host: &Host, request: RequestId) -> IdeResult<AgentRegistry> {
let paths = registry_paths(host);
let cancel = host.begin_request(request);
let result =
tokio::task::spawn_blocking(move || ide_agent::registry::list(&paths, &cancel)).await.map_err(join_err);
let result = blocking(move || ide_agent::registry::list(&paths, &cancel)).await;
host.end_request(request);
let mut registry = result??;
let mut registry = result?;
let installing = installing();
for agent in &mut registry.agents {
agent.installing = installing.contains(&agent.id);
@@ -204,7 +197,7 @@ pub async fn agent_registry_install(
});
}
};
let result = tokio::task::spawn_blocking(move || {
let result = blocking(move || {
let _installing = installing;
let _cancel = ide_core::task::on_cancel(task, {
let cancel = cancel.clone();
@@ -223,10 +216,9 @@ pub async fn agent_registry_install(
report(None, Some(1.0), true);
result
})
.await
.map_err(join_err);
.await;
host.end_request(request);
result??;
result?;
for project in host.projects() {
project.agents.reload_providers();
}
@@ -237,7 +229,7 @@ pub async fn agent_registry_install(
#[command(trust = always)]
pub async fn agent_registry_remove(host: &Host, id: String) -> IdeResult<()> {
let paths = registry_paths(host);
tokio::task::spawn_blocking(move || ide_agent::registry::remove(&paths, &id)).await.map_err(join_err)??;
blocking(move || ide_agent::registry::remove(&paths, &id)).await?;
for project in host.projects() {
project.agents.reload_providers();
}
@@ -273,7 +265,7 @@ pub async fn agent_entries(
pub async fn agent_external_sessions(host: &Host, window: &str) -> IdeResult<Vec<ExternalSession>> {
// Reads transcripts from disk on the blocking pool.
let agents = host.project(window)?.agents.clone();
tokio::task::spawn_blocking(move || agents.external_sessions()).await.map_err(join_err)
blocking_value(move || agents.external_sessions()).await
}
/// Imports an external session as a task: its first turn loads and replays it.
@@ -286,7 +278,7 @@ pub async fn agent_import_session(
) -> IdeResult<AgentTask> {
host.require_trust(window)?;
let agents = host.project(window)?.agents.clone();
tokio::task::spawn_blocking(move || agents.import_session(&provider, &session_id)).await.map_err(join_err)?
blocking(move || agents.import_session(&provider, &session_id)).await
}
#[command(trust = trusted)]
@@ -408,14 +400,13 @@ async fn cli_update(
let project = host.project(window)?;
let installing = offer.as_ref().map(|_| Installing::begin(&provider)).transpose()?;
let cancel = host.begin_project_request(window, request);
let result = tokio::task::spawn_blocking(move || {
let result = blocking(move || {
let _installing = installing;
project.agents.cli_update(&provider, offer.as_ref(), &cancel)
})
.await
.map_err(join_err);
.await;
host.end_request(request);
result?
result
}
/// What the agent reports about itself when it starts (no session: no MCP servers, hooks
@@ -818,11 +809,7 @@ pub fn agent_mcp_import(host: &Host, window: &str) -> IdeResult<Vec<McpServer>>
pub async fn agent_mcp_discover_sources(host: &Host, window: &str) -> IdeResult<Vec<McpExternalSource>> {
let project_root = host.project(window).ok().filter(|p| !p.light).map(|p| p.root.clone());
let home = dirs::home_dir();
tokio::task::spawn_blocking(move || {
ide_agent::mcp::discover_external_sources(home.as_deref(), project_root.as_deref())
})
.await
.map_err(|e| IdeError::internal(e.to_string()))
blocking_value(move || ide_agent::mcp::discover_external_sources(home.as_deref(), project_root.as_deref())).await
}
/// Imports selected servers from discovered external MCP configuration files into User or Workspace scope.
@@ -1061,7 +1048,7 @@ pub async fn agent_skills_list(host: &Host, window: &str) -> IdeResult<Vec<Agent
let project = host.project(window).ok().filter(|p| !p.light);
let policy = host_skills_policy(host, project.as_deref());
let home = dirs::home_dir();
tokio::task::spawn_blocking(move || {
blocking(move || {
Ok(ide_agent::skills::resolve(
ide_agent::skills::discover_skills_with_plugins(
&policy.workspace_roots,
@@ -1075,7 +1062,6 @@ pub async fn agent_skills_list(host: &Host, window: &str) -> IdeResult<Vec<Agent
))
})
.await
.map_err(|e| IdeError::internal(e.to_string()))?
}
/// Sets how `name` may run in `scope`, in the settings file of that scope, and returns the
@@ -1139,14 +1125,13 @@ pub async fn agent_skills_browse(
) -> IdeResult<RemoteSkillBrowseResult> {
let cancel = host.begin_request(request);
let search_path = ide_core::tool_path::search_path();
let res = tokio::task::spawn_blocking(move || {
let res = blocking(move || {
let fetcher = ide_agent::skill_installer::GitHubHttpFetcher::new(&search_path)?;
ide_agent::skill_installer::browse_skills(&fetcher, &source, &cancel)
})
.await
.map_err(join_err);
.await;
host.end_request(request);
res?
res
}
/// Fetches one skill's `SKILL.md`, file list, and static security scan warnings before installation.
@@ -1164,7 +1149,7 @@ pub async fn agent_skills_preview(
let ws_root = host.project(window).ok().filter(|p| !p.light).map(|p| p.root.clone());
let home = dirs::home_dir();
let search_path = ide_core::tool_path::search_path();
let res = tokio::task::spawn_blocking(move || {
let res = blocking(move || {
let fetcher = ide_agent::skill_installer::GitHubHttpFetcher::new(&search_path)?;
ide_agent::skill_installer::preview_skill(
&fetcher,
@@ -1175,10 +1160,9 @@ pub async fn agent_skills_preview(
&cancel,
)
})
.await
.map_err(join_err);
.await;
host.end_request(request);
res?
res
}
/// Installs the selected skill subtree into `~/.agents/skills` (User) or `<workspace>/.agents/skills` (Workspace).
@@ -1199,7 +1183,7 @@ pub async fn agent_skills_install(
let search_path = ide_core::tool_path::search_path();
let install_home = home.clone();
let install_ws = ws_root.clone();
let res = tokio::task::spawn_blocking(move || {
let res = blocking(move || {
let fetcher = ide_agent::skill_installer::GitHubHttpFetcher::new(&search_path)?;
ide_agent::skill_installer::install_skill(
&fetcher,
@@ -1209,10 +1193,9 @@ pub async fn agent_skills_install(
&cancel,
)
})
.await
.map_err(join_err);
.await;
host.end_request(request);
res??;
res?;
let event = IdeEvent::SettingsChanged { key: "agents.skills".into() };
for p in host.projects() {
@@ -1221,7 +1204,7 @@ pub async fn agent_skills_install(
}
let policy = host_skills_policy(host, project.as_deref());
tokio::task::spawn_blocking(move || {
blocking(move || {
Ok(ide_agent::skills::resolve(
ide_agent::skills::discover_skills_with_plugins(
&policy.workspace_roots,
@@ -1235,7 +1218,6 @@ pub async fn agent_skills_install(
))
})
.await
.map_err(join_err)?
}
/// The user's and the workspace's skill policies (`[agents.skills.<name>]`).
+1 -1
View File
@@ -8,7 +8,7 @@ use crate::Project;
use crate::ops::Channel;
use ide_command::command;
use super::doc::blocking;
use super::blocking;
use ide_analysis::{
DuplicateOptions, DuplicatesReport, SourceFile, StructuralFile, StructuralQuery, StructuralSummary,
};
+129 -49
View File
@@ -3,6 +3,7 @@
pub(super) mod workspace;
use super::dependencies::{MavenCentralArtifacts, MavenCentralGroups, MavenCentralVersions};
use super::{blocking, blocking_value};
use crate::ops::Channel;
use crate::{Host, Project};
use ide_command::command;
@@ -22,10 +23,6 @@ use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, OnceLock};
use std::time::{Duration, Instant};
fn join_err(e: tokio::task::JoinError) -> IdeError {
IdeError::internal(e.to_string())
}
/// POM gutters in several editors refresh together. A very short cache lets those
/// requests share one reactor scan without serving a stale module list after edits settle.
const MAVEN_MODULE_CACHE_TTL: Duration = Duration::from_millis(250);
@@ -200,7 +197,7 @@ pub async fn build_model(host: &Host, window: &str) -> IdeResult<BuildModel> {
host.require_trust(window)?;
let project = host.project(window)?;
let config = host.config_dir.clone();
tokio::task::spawn_blocking(move || workspace::load_project(&project, &config)).await.map_err(join_err)?
blocking(move || workspace::load_project(&project, &config)).await
}
fn linked_gradle_paths(
@@ -253,7 +250,7 @@ fn linked_gradle_paths(
async fn set_gradle_projects(host: &Host, window: &str, paths: Vec<String>, link: bool) -> IdeResult<BuildModel> {
host.require_trust(window)?;
let project = host.project(window)?;
tokio::task::spawn_blocking(move || {
blocking(move || {
if ide_workspace::workspace::Workspace::load(&project.root)?.is_some() {
return Err(IdeError::invalid("Open a workspace member as a project to link Gradle builds"));
}
@@ -269,7 +266,6 @@ async fn set_gradle_projects(host: &Host, window: &str, paths: Vec<String>, link
Ok::<BuildModel, IdeError>(load(&project.root, &project.build_cache_dir(), &settings))
})
.await
.map_err(join_err)?
}
#[command(trust = trusted)]
@@ -335,7 +331,7 @@ pub async fn build_sync(
let bridge_profiles = profiles.clone();
let p = project.clone();
let config = host.config_dir.clone();
let result = tokio::task::spawn_blocking(move || {
let result = blocking(move || {
let scopes = workspace::scopes(&p, &config)?;
let selected: Vec<_> =
scopes.iter().filter(|scope| workspace::selected(scope, &p.root, tool, build_dir.as_deref())).collect();
@@ -416,10 +412,9 @@ pub async fn build_sync(
};
Ok::<_, IdeError>((model, profiles_changed || offline_changed, updates, snapshots))
})
.await
.map_err(join_err);
.await;
let result = async {
let (mut model, reconfigure, updates, snapshots) = result??;
let (mut model, reconfigure, updates, snapshots) = result?;
if completion_token.is_cancelled() {
return Err(IdeError::cancelled());
}
@@ -445,7 +440,7 @@ pub async fn build_sync(
// JDT LS resolves the binary jars while importing Maven projects.
update_java_projects(&lsp, &updates, reconfigure, Some(&completion_token)).await;
let cancel = completion_token.clone();
let (updated, refreshed) = tokio::task::spawn_blocking(move || {
let (updated, refreshed) = blocking_value(move || {
let mut refreshed = Vec::new();
if let Some(maven) = &model.maven {
for batch in snapshots {
@@ -464,8 +459,7 @@ pub async fn build_sync(
}
(model, refreshed)
})
.await
.map_err(join_err)?;
.await?;
model = updated;
tokio::spawn(async move {
refresh_library_archives(&lsp, &documents, &updates, refreshed).await;
@@ -584,12 +578,11 @@ pub async fn gradle_published_catalog(
coordinates: String,
) -> IdeResult<Option<ide_core::IpcPath>> {
let project = host.project(window)?;
tokio::task::spawn_blocking(move || {
blocking_value(move || {
ide_sdk::libraries::published_version_catalog(&project.root, &project.settings.effective(), &coordinates)
.map(Into::into)
})
.await
.map_err(join_err)
}
/// The resolved dependency tree of a Gradle project for one configuration (Dependency Analyzer).
@@ -608,7 +601,7 @@ pub async fn gradle_dependencies(
let project = host.project(window)?;
let config = host.config_dir.clone();
let token = host.begin_project_request(window, request);
let result = tokio::task::spawn_blocking(move || {
let result = blocking(move || {
let scopes = workspace::scopes(&project, &config)?;
let scope = scopes
.iter()
@@ -636,10 +629,9 @@ pub async fn gradle_dependencies(
}
Ok(report.dependencies)
})
.await
.map_err(join_err);
.await;
host.end_request(request);
result?
result
}
/// What the Dependency Analyzer has of the builds of `project` at `root` (the project, or one
@@ -686,12 +678,11 @@ pub async fn maven_dependency_declaration(
) -> IdeResult<Location> {
let project = host.project(window)?;
let config = host.config_dir.clone();
tokio::task::spawn_blocking(move || {
blocking(move || {
let (path, _, range) = declaring_pom(&project, &config, &pom, &dependency)?;
Ok(Location::file(path, range))
})
.await
.map_err(join_err)?
}
/// The go-to-declaration target at `pos` of a Maven POM: the definition of the
@@ -705,7 +696,7 @@ pub async fn maven_goto_declaration(host: &Host, window: &str, pom: String, pos:
// without a managed version the target is the artifact's own POM (a project module's, or the
// local repository's). `None` when nothing resolvable is under the caret.
let project = host.project(window)?;
tokio::task::spawn_blocking(move || {
blocking(move || {
let given = Path::new(&pom);
let path = if given.is_absolute() { given.to_path_buf() } else { project.root.join(given) };
let text = project.text_of(&path)?;
@@ -716,7 +707,6 @@ pub async fn maven_goto_declaration(host: &Host, window: &str, pom: String, pos:
Ok(ide_build::maven::goto_declaration_with(&text, &path, pos, options, modules))
})
.await
.map_err(join_err)?
}
/// Gutter targets of the unversioned dependencies and plugins in a Maven POM:
@@ -731,7 +721,7 @@ pub async fn maven_managed_declarations(
) -> IdeResult<Vec<PomManagedDeclaration>> {
let project = host.project(window)?;
let cancel = host.begin_project_read_request(window, request);
let result = tokio::task::spawn_blocking(move || {
let result = blocking(move || {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
@@ -753,10 +743,7 @@ pub async fn maven_managed_declarations(
})
.await;
host.end_request(request);
match result {
Ok(result) => result,
Err(error) => Err(join_err(error)),
}
result
}
/// How long completion waits for Maven Central before answering from the local repository.
@@ -855,7 +842,7 @@ pub async fn maven_exclude_dependency(
) -> IdeResult<Location> {
let project = host.project(window)?;
let config = host.config_dir.clone();
tokio::task::spawn_blocking(move || {
blocking(move || {
let (path, text, range) = declaring_pom(&project, &config, &pom, &dependency)?;
match ide_build::pom_edit::add_exclusion(&text, &dependency, &exclusion) {
Some(Exclusion::Edit(edit)) => {
@@ -871,7 +858,6 @@ pub async fn maven_exclude_dependency(
Ok(Location::file(path, range))
})
.await
.map_err(join_err)?
}
/// Build / Rebuild / Build Artifacts of a Java project without a build tool, from its
@@ -989,7 +975,7 @@ pub async fn build_run(
let config_dir = host.config_dir.clone();
let token = host.begin_project_request(window, request);
let launch_project = project.clone();
let result = tokio::task::spawn_blocking(move || {
let result = blocking(move || {
// Fast path (#2476): an unchanged single-project Maven build skips
// Maven entirely. Previous diagnostics stay: nothing changed, so they
// are still accurate.
@@ -1111,10 +1097,9 @@ pub async fn build_run(
}
Ok::<_, IdeError>(result)
})
.await
.map_err(join_err);
.await;
host.end_request(request);
let outcome = result??;
let outcome = result?;
// Maven generated sources (protobuf, gRPC) stay invisible to jdtls until the
// folders the build wrote are attached. An up-to-date build skips Maven and
// still needs this: the classes can already be on disk.
@@ -1124,11 +1109,39 @@ pub async fn build_run(
Ok(outcome)
}
/// Build › Compile File: compiles one Java source of a linked Maven module with
/// `javac`, streaming the console and messages on `on_event`; cancellable with
/// `cancel_request(request)`. Diagnostics of `clear` (the files of the previous
/// build) are cleared first; the new messages are published as `build`
/// diagnostics.
fn plan_compile_file(
root: &Path,
cache: &Path,
settings: &Settings,
detected: &[ide_workspace::roots::SourceFolder],
file: &Path,
cancel: &CancellationToken,
on_progress: &dyn Fn(String),
) -> IdeResult<compile::BuildPlan> {
if file.extension().is_none_or(|ext| !ext.eq_ignore_ascii_case("java")) {
return Err(IdeError::invalid("only Java sources can be compiled as a single file"));
}
if !file.is_file() {
return Err(IdeError::not_found("no Java source found for single-file compilation"));
}
let name = file.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
let model = with_profiles(load(root, cache, settings), cache);
if compile::single_file_target(root, &model, file).is_ok() {
on_progress(format!("Resolving classpath for {name}…"));
return compile::compile_file_plan_cancellable(root, &model, file, cancel);
}
if compile::has_gradle_file_target(root, &model, file) {
on_progress(format!("Resolving classpath for {name}…"));
return compile::gradle_compile_file_plan(root, &model, file, cache, cancel);
}
let (ps, roots, jdk) = structure_inputs(root, settings, detected);
compile::structure_compile_file_plan(root, &ps, &roots, jdk.as_ref(), &settings.languages.java.language_level, file)
}
/// Build › Recompile: compiles one Java source file with `javac`, streaming the
/// console and messages on `on_event`; cancellable with `cancel_request(request)`.
/// Diagnostics of `clear` (the files of the previous build) are cleared first;
/// the new messages are published as `build` diagnostics.
#[command(trust = trusted)]
pub async fn build_compile_file(
host: &Host,
@@ -1140,10 +1153,21 @@ pub async fn build_compile_file(
) -> IdeResult<BuildResult> {
host.require_trust(window)?;
let project = host.project(window)?;
let (root, cache, sink) = (project.root.clone(), project.build_cache_dir(), project.sink.clone());
let settings = project.settings.effective();
let file = ide_core::project_roots::resolve(&project.root, &file);
let scope = {
let (project, file) = (project.clone(), file.clone());
blocking(move || workspace::scope_for(&project, &file)).await?
};
let scope_root = scope.root.clone();
let detected = if scope.root == project.root {
project.detected_roots.read().clone()
} else {
let root = scope.root.clone();
blocking_value(move || ide_workspace::roots::detect(&root)).await?
};
let sink = project.sink.clone();
let token = host.begin_project_request(window, request);
let result = tokio::task::spawn_blocking(move || {
let result = blocking(move || {
for path in clear {
sink.emit(IdeEvent::Diagnostics {
path: path.into(),
@@ -1151,8 +1175,11 @@ pub async fn build_compile_file(
items: Vec::new(),
});
}
let plan = compile::compile_file_plan(&root, &with_profiles(load(&root, &cache, &settings), &cache), &file)?;
let result = compile::run(&root, &plan, &token, &|e| {
let plan =
plan_compile_file(&scope.root, &scope.cache, &scope.settings, &detected, &file, &token, &|message| {
let _ = on_event.send(BuildEvent::Progress { message, fraction: None });
})?;
let result = compile::run(&scope.root, &plan, &token, &|e| {
let _ = on_event.send(e);
})?;
for (path, items) in compile::diagnostics(&result.messages) {
@@ -1160,12 +1187,11 @@ pub async fn build_compile_file(
}
Ok::<_, IdeError>(result)
})
.await
.map_err(join_err);
.await;
host.end_request(request);
let outcome = result??;
let outcome = result?;
if outcome.system == ide_build::compile::BuildSystem::Maven {
project.lsp.sync_maven_generated_sources(&project.root).await;
project.lsp.sync_maven_generated_sources(&scope_root).await;
}
Ok(outcome)
}
@@ -1390,6 +1416,60 @@ mod build_tool_settings_tests {
assert_eq!(model.env["JAVA_HOME"], root.join("jdk21").to_string_lossy());
assert_eq!(model.env["GRADLE_USER_HOME"], root.join("user-home").to_string_lossy());
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn single_file_plan_falls_back_to_project_structure_and_resolves_workspace_scope() {
let tmp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(tmp.path()).unwrap();
let plain = base.join("plain");
let java_file = plain.join("src/Main.java");
std::fs::create_dir_all(java_file.parent().unwrap()).unwrap();
std::fs::write(&java_file, "class Main {}").unwrap();
let detected = ide_workspace::roots::detect(&plain);
let plan = plan_compile_file(
&plain,
&base.join("cache"),
&Settings::default(),
&detected,
&java_file,
&ide_core::CancellationToken::new(),
&|_| {},
)
.unwrap();
assert_eq!(plan.system, compile::BuildSystem::Javac);
assert_eq!(plan.title, "Compile Main.java");
let txt = plain.join("notes.txt");
std::fs::write(&txt, "hi").unwrap();
assert!(
plan_compile_file(
&plain,
&base.join("cache"),
&Settings::default(),
&detected,
&txt,
&ide_core::CancellationToken::new(),
&|_| {},
)
.is_err()
);
let host =
Host::new(crate::HostConfig { local_data_dir: base.join("local"), ..crate::HostConfig::for_test(&base) });
let member_a = base.join("member-a");
let member_b = base.join("member-b");
for m in [&member_a, &member_b] {
std::fs::create_dir_all(m.join("src")).unwrap();
std::fs::write(m.join("src/App.java"), "class App {}").unwrap();
}
let ws = base.join("ws");
std::fs::create_dir_all(&ws).unwrap();
ide_workspace::workspace::Workspace::save(&ws, "WS", vec![member_a.clone(), member_b.clone()], true).unwrap();
let project = host.open_project("win", &ws).unwrap();
let scope = workspace::scope_for(&project, &member_b.join("src/App.java")).unwrap();
assert_eq!(scope.root, member_b);
host.close_project("win");
}
}
#[cfg(test)]
+1 -1
View File
@@ -2,7 +2,7 @@
use crate::Host;
use ide_command::command;
use crate::ops::doc::blocking;
use crate::ops::blocking;
use ide_core::IdeResult;
use ide_vfs::{ByteRange, FileProbe};
use std::path::PathBuf;
+2 -5
View File
@@ -2,17 +2,14 @@
use crate::Host;
use ide_command::command;
use ide_core::{IdeError, IdeResult, IpcPath};
use super::blocking;
use ide_core::{IdeResult, IpcPath};
use ide_coverage::{CoveragePrepared, CoverageReportSpec, CoverageSuite};
use ide_run::RunConfig;
/// Output directories kept per kind (older runs' data is deleted).
pub const KEEP_RUNS: usize = 10;
pub async fn blocking<T: Send + 'static>(f: impl FnOnce() -> IdeResult<T> + Send + 'static) -> IdeResult<T> {
tokio::task::spawn_blocking(f).await.map_err(|e| IdeError::internal(e.to_string()))?
}
/// How to run `config` with coverage: the command to launch and where its report will be,
/// or which tool is missing.
#[command(trust = trusted)]
+8 -3
View File
@@ -188,10 +188,15 @@ pub async fn db_finish_transaction(host: &Host, window: &str, id: String, commit
}
#[command(trust = trusted)]
pub async fn db_disconnect(host: &Host, window: &str, id: String) -> IdeResult<()> {
// Closes the connection of data source `id`.
pub async fn db_disconnect(host: &Host, window: &str, id: String, whole_source: Option<bool>) -> IdeResult<()> {
// A source-level Deactivate includes databases still opening in the background.
let db = host.project(window)?.db.clone();
db.disconnect(&id).await;
let (source, database) = ide_db::split_target(&id);
if whole_source == Some(true) && database.is_none() {
db.disconnect_source(source).await;
} else {
db.disconnect(&id).await;
}
Ok(())
}
+8
View File
@@ -671,6 +671,13 @@ pub async fn debug_jvm_memory_classes(
host.debugger.jvm_memory_classes(session).await
}
/// A `Thread.print -l` of the debuggee JVM, or why it cannot be taken.
#[command(trust = trusted)]
pub async fn debug_jvm_thread_dump(host: &Host, window: &str, session: DebugSessionId) -> IdeResult<JvmThreadsResult> {
host.require_trust(window)?;
host.debugger.jvm_thread_dump(session).await
}
/// Up to `limit` live instances of the class in the stopped JVM.
#[command(trust = trusted)]
pub async fn debug_jvm_memory_instances(
@@ -867,6 +874,7 @@ ide_command::domain!(
debug_jvm_memory_fields,
debug_jvm_memory_instances,
debug_jvm_memory_referrers,
debug_jvm_thread_dump,
debug_listen_for_jvm,
debug_pause,
debug_redefine_classes,
+26 -1
View File
@@ -330,6 +330,31 @@ pub async fn pypi_package(
result
}
/// PyPI project names containing `query`, best match first, 51 at most (50 are shown). Answers from a cached copy of
/// PyPI's name list, which the first search downloads and a search a day later refreshes.
#[command(trust = outside_restricted)]
pub async fn pypi_search(host: &Host, window: &str, query: String, request: RequestId) -> IdeResult<Vec<String>> {
let names = host.pypi_names.clone();
let cancel = host.begin_project_read_request(window, request);
let result = host
.blocking(move || {
let fetch: pypi::Fetch = std::sync::Arc::new(|cancel: &CancellationToken| {
let search_path = std::env::var_os("PATH").unwrap_or_default();
ide_tools::Http::new(&search_path)?
.https_only()
.accept(pypi::SIMPLE_INDEX_ACCEPT)
.compressed()
.get_text_limited(pypi::SIMPLE_INDEX_URL, Some(256 * 1024 * 1024), cancel)
});
let index = names.index(&cancel, fetch)?;
// One more than shown, so the UI can tell the list was cut.
index.search(&query, 51, &cancel)
})
.await;
host.end_request(request);
result
}
#[cfg(test)]
mod tests {
use super::*;
@@ -456,4 +481,4 @@ mod tests {
}
}
ide_command::domain!(dependencies: dependency_versions, python_requirements, pypi_package);
ide_command::domain!(dependencies: dependency_versions, python_requirements, pypi_package, pypi_search);
+20
View File
@@ -214,6 +214,25 @@ pub async fn deploy_test_connection(
host.remote.test_connection_with(&connection, &path, password).await
}
#[command(trust = trusted)]
pub async fn remote_upload_into(
window: &str,
host: &Host,
connection: FsConnection,
paths: Vec<IpcPath>,
target: String,
replace: bool,
request: RequestId,
) -> IdeResult<TransferReport> {
let project = host.project(window)?;
let token = host.begin_request(request);
let (mut report, done) = progress(project.sink.clone(), "Uploading", token.clone());
let result = host.remote.upload_into(&connection, &local(paths), &target, replace, &token, &mut report).await;
done();
host.end_request(request);
result
}
ide_command::domain!(
deploy:
deploy_compare,
@@ -227,6 +246,7 @@ ide_command::domain!(
deploy_upload,
remote_delete,
remote_download_into,
remote_upload_into,
remote_list,
remote_mkdir,
remote_of,
+1
View File
@@ -1,3 +1,4 @@
use super::blocking;
use crate::Host;
use ide_command::command;
use ide_core::{ChangeSet, DocId, IdeResult};
+2 -7
View File
@@ -1,17 +1,12 @@
use crate::Host;
use crate::ops::blocking;
use ide_command::command;
use ide_core::{DocId, IdeError, IdeResult, OutlineItem, Range, TextEdit};
use ide_core::{DocId, IdeResult, OutlineItem, Range, TextEdit};
use ide_language::{FoldRange, SyntaxHighlights};
use ide_text::LineEnding;
use ide_workspace::{DocumentEncoding, DocumentInfo, DocumentLanguage, HistoryEntry};
use std::path::PathBuf;
/// Runs blocking work (disk I/O, parsing, large copies) on the blocking pool,
/// keeping it off the main thread and the async runtime's workers.
pub async fn blocking<T: Send + 'static>(f: impl FnOnce() -> IdeResult<T> + Send + 'static) -> IdeResult<T> {
tokio::task::spawn_blocking(f).await.map_err(|e| IdeError::internal(e.to_string()))?
}
/// Opens a read-only virtual document (see `lsp_virtual_document`) as an
/// editor buffer, so syntax features and language-server requests work in it.
#[command(trust = always)]
+1 -1
View File
@@ -6,7 +6,7 @@ use ide_core::IdeResult;
use ide_workspace::DirectoryHistory;
use std::path::PathBuf;
use super::doc::blocking;
use super::blocking;
/// Show History on a folder: snapshots of the files under it (deleted ones included) and labels.
#[command(trust = always)]
+21 -1
View File
@@ -1,4 +1,4 @@
use super::doc::blocking;
use super::blocking;
use crate::Host;
use crate::plugins::{ProviderKind, editor_providers_for as editor_providers};
use ide_command::command;
@@ -595,6 +595,25 @@ pub async fn plugin_line_markers(
.collect())
}
/// Where other files import the document's file (Find Usages on a file, a Vue component's
/// usages). Cancel with `cancel_request(request)`.
#[command(trust = trusted)]
pub async fn lsp_file_references(
host: &Host,
window: &str,
request: RequestId,
doc: DocId,
) -> IdeResult<Vec<Location>> {
let lsp = host.project(window)?.lsp.clone();
let cancel = host.begin_request(request);
let result = tokio::select! {
result = lsp.file_references(doc, cancel.clone()) => result,
_ = cancel.cancelled() => Err(ide_core::IdeError::cancelled()),
};
host.end_request(request);
result
}
/// Implementations of the symbols at `positions`, one list per position (the
/// editor's "is implemented / overridden" gutter markers). Cancel with
/// `cancel_request(request)`.
@@ -3197,6 +3216,7 @@ ide_command::domain!(
lsp_hierarchy_refactor,
lsp_hover,
lsp_implementation_locations,
lsp_file_references,
lsp_implementations,
lsp_inlay_hints,
lsp_inline_completion,
+1 -1
View File
@@ -4,7 +4,7 @@
//! poms the nearest pom declares itself are followed from there; a parent outside
//! that walk that no pom declares is not.
use super::doc::blocking;
use super::blocking;
use crate::Host;
use ide_build::maven;
use ide_core::{DocId, Location, Pos};
+103 -2
View File
@@ -39,6 +39,7 @@ pub mod ssh;
pub mod stream_trace;
pub mod syntax;
pub mod term;
pub mod thread_dump;
pub mod tools;
pub mod vcs;
pub mod web;
@@ -118,15 +119,115 @@ ide_command::domains!(
stream_trace: crate::ops::stream_trace,
syntax: crate::ops::syntax,
term: crate::ops::term,
thread_dump: crate::ops::thread_dump,
tools: crate::ops::tools,
vcs: crate::ops::vcs,
vcs_commands: crate::ops::vcs::commands,
web: crate::ops::web,
);
/// A blocking task that panicked or was cancelled, as the error a command returns.
pub(crate) fn join_error(e: tokio::task::JoinError) -> IdeError {
IdeError::internal(e.to_string())
}
/// Runs blocking work (disk I/O, parsing, large copies) on the ambient runtime's blocking
/// pool, keeping it off the main thread and the async runtime's workers.
pub async fn blocking<T: Send + 'static>(f: impl FnOnce() -> IdeResult<T> + Send + 'static) -> IdeResult<T> {
tokio::task::spawn_blocking(f).await.map_err(join_error)?
}
/// [`blocking`] for work that cannot fail: only a panic or cancellation is an error.
pub(crate) async fn blocking_value<T: Send + 'static>(f: impl FnOnce() -> T + Send + 'static) -> IdeResult<T> {
tokio::task::spawn_blocking(f).await.map_err(join_error)
}
impl Host {
/// Runs blocking work (disk I/O, parsing, large copies) on the blocking pool.
/// [`blocking`] on this host's runtime instead of the ambient one.
pub async fn blocking<T: Send + 'static>(&self, f: impl FnOnce() -> IdeResult<T> + Send + 'static) -> IdeResult<T> {
self.runtime.spawn_blocking(f).await.map_err(|e| IdeError::internal(e.to_string()))?
self.runtime.spawn_blocking(f).await.map_err(join_error)?
}
}
#[cfg(test)]
mod blocking_tests {
use super::{blocking, blocking_value};
use crate::{Host, HostConfig};
use ide_core::error::ErrorKind;
use ide_core::{IdeError, IdeResult};
use std::sync::Arc;
fn runtime(name: &str) -> tokio::runtime::Runtime {
tokio::runtime::Builder::new_multi_thread().worker_threads(1).thread_name(name).enable_all().build().unwrap()
}
fn thread_name() -> String {
std::thread::current().name().unwrap_or_default().to_owned()
}
fn assert_panic(error: &IdeError) {
assert_eq!(error.kind, ErrorKind::Internal);
assert!(error.data.is_none());
// tokio's JoinError text: `task <id> panicked with message "boom"` (the id varies).
assert!(error.message.starts_with("task "), "{}", error.message);
assert!(error.message.ends_with(" panicked with message \"boom\""), "{}", error.message);
}
fn host_on(handle: tokio::runtime::Handle, base: &std::path::Path) -> Host {
Host::new(HostConfig {
config_dir: base.join("config"),
data_dir: base.join("data"),
local_data_dir: base.join("local"),
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: Arc::default(),
sink_for: Box::new(|_| Arc::new(|_| {})),
owner: |w| w,
runtime: handle,
project_environment: false,
})
}
#[test]
fn blocking_returns_the_value_and_passes_the_closure_error_through() {
runtime("ambient").block_on(async {
assert_eq!(blocking(|| Ok(7)).await.unwrap(), 7);
let error = blocking::<()>(|| Err(IdeError::invalid("nope"))).await.unwrap_err();
assert_eq!((error.kind, error.message.as_str()), (ErrorKind::InvalidInput, "nope"));
});
}
#[test]
fn blocking_maps_a_panic_to_an_internal_error() {
runtime("ambient").block_on(async {
assert_panic(&blocking::<()>(|| panic!("boom")).await.unwrap_err());
});
}
#[test]
fn blocking_runs_on_the_ambient_runtime() {
let name = runtime("ambient").block_on(async { blocking(|| Ok(thread_name())).await.unwrap() });
assert_eq!(name, "ambient");
}
#[test]
fn blocking_value_returns_the_value_and_maps_a_panic() {
runtime("ambient").block_on(async {
assert_eq!(blocking_value(thread_name).await.unwrap(), "ambient");
assert_panic(&blocking_value::<()>(|| panic!("boom")).await.unwrap_err());
});
}
#[test]
fn host_blocking_runs_on_the_hosts_runtime_not_the_ambient_one() {
let (ambient, hosts) = (runtime("ambient"), runtime("hosts"));
let temp = tempfile::tempdir().unwrap();
let host = host_on(hosts.handle().clone(), temp.path());
ambient.block_on(async {
assert_eq!(host.blocking(|| Ok(thread_name())).await.unwrap(), "hosts");
assert_eq!(host.blocking(|| IdeResult::Ok(7)).await.unwrap(), 7);
let error = host.blocking::<()>(|| Err(IdeError::invalid("nope"))).await.unwrap_err();
assert_eq!((error.kind, error.message.as_str()), (ErrorKind::InvalidInput, "nope"));
assert_panic(&host.blocking::<()>(|| panic!("boom")).await.unwrap_err());
});
}
}
+1 -1
View File
@@ -1,4 +1,4 @@
use super::doc::blocking;
use super::blocking;
use super::python_stubs::{
PythonStubLinks, counterpart_candidates, match_declarations, module_name, site_packages, stub_path,
};
+1 -1
View File
@@ -12,7 +12,7 @@ use ide_workspace::{FileMove, UndoOutcome};
use parking_lot::Mutex;
use std::path::{Path, PathBuf};
use super::doc::blocking;
use super::blocking;
fn pairs(moves: &[FileMove]) -> Vec<(PathBuf, PathBuf)> {
moves.iter().map(|m| (m.from.to_path_buf(), m.to.to_path_buf())).collect()
+4 -4
View File
@@ -13,7 +13,7 @@ use std::time::Duration;
pub async fn run_configs(host: &Arc<Host>, window: &str) -> IdeResult<Vec<RunConfig>> {
// Detection reads build files (and Spring Boot sources): off the command thread.
let (host, window) = (host.clone(), window.to_owned());
super::doc::blocking(move || configs(&host, &window)).await
super::blocking(move || configs(&host, &window)).await
}
#[command(trust = trusted)]
@@ -25,7 +25,7 @@ pub async fn run_save_configs(
) -> IdeResult<()> {
let (host, window) = (host.clone(), window.to_owned());
let removed = removed_detected_ids.unwrap_or_default();
super::doc::blocking(move || save_configs(&host, &window, &configs, &removed)).await
super::blocking(move || save_configs(&host, &window, &configs, &removed)).await
}
/// Detected configs followed by user-defined ones (user ids win on conflict).
@@ -263,7 +263,7 @@ fn settings_only(
#[command(trust = trusted)]
pub async fn run_without_derived(host: &Arc<Host>, window: &str, configs: Vec<RunConfig>) -> IdeResult<Vec<RunConfig>> {
let (host, window) = (host.clone(), window.to_owned());
super::doc::blocking(move || without_derived(&host, &window, configs)).await
super::blocking(move || without_derived(&host, &window, configs)).await
}
/// Without what settings derived (toolchain commands, Maven options, `JAVA_HOME`…), so they
@@ -287,7 +287,7 @@ fn without_derived(host: &Host, window: &str, configs: Vec<RunConfig>) -> IdeRes
#[command(trust = trusted)]
pub async fn run_apply_settings(host: &Arc<Host>, window: &str, configs: Vec<RunConfig>) -> IdeResult<Vec<RunConfig>> {
let (host, window) = (host.clone(), window.to_owned());
super::doc::blocking(move || apply_settings(&host, &window, configs)).await
super::blocking(move || apply_settings(&host, &window, configs)).await
}
/// Today's settings applied, as [`configs`] lists the others.
+17 -7
View File
@@ -100,20 +100,20 @@ pub async fn run_application_publish(
#[command(trust = trusted)]
pub async fn run_templates(host: &Host, window: &str) -> IdeResult<Vec<RunConfig>> {
let root = host.project(window)?.root.clone();
crate::ops::doc::blocking(move || ide_run::load_templates(&root)).await
crate::ops::blocking(move || ide_run::load_templates(&root)).await
}
#[command(trust = trusted)]
pub async fn run_save_templates(host: &Host, window: &str, templates: Vec<RunConfig>) -> IdeResult<()> {
let root = host.project(window)?.root.clone();
crate::ops::doc::blocking(move || ide_run::save_templates(&root, &templates)).await
crate::ops::blocking(move || ide_run::save_templates(&root, &templates)).await
}
/// Project files run configurations can be imported from (`.vscode/launch.json`).
#[command(trust = trusted)]
pub async fn run_import_sources(host: &Host, window: &str) -> IdeResult<Vec<RunImportSource>> {
let root = host.project(window)?.root.clone();
crate::ops::doc::blocking(move || Ok(ide_run::import::available(&root))).await
crate::ops::blocking(move || Ok(ide_run::import::available(&root))).await
}
/// Configurations read from `source`, not saved; names already in `existing` are skipped.
@@ -127,7 +127,7 @@ pub async fn run_import_configs(
// `existing`: the configurations being edited.
host.require_trust(window)?;
let root = host.project(window)?.root.clone();
crate::ops::doc::blocking(move || ide_run::import_configs(&root, source, &existing)).await
crate::ops::blocking(move || ide_run::import_configs(&root, source, &existing)).await
}
/// The environment runs inherit when "Include system environment variables" is on.
@@ -141,7 +141,7 @@ pub fn run_system_env() -> std::collections::BTreeMap<String, String> {
pub async fn run_env_files(files: Vec<std::path::PathBuf>) -> IdeResult<std::collections::BTreeMap<String, String>> {
// In order (later files win): the same files a run loads, over the system environment
// debug adapters inherit.
crate::ops::doc::blocking(move || {
crate::ops::blocking(move || {
ide_run::envfile::load(&files, &ide_run::system_env())
.map_err(|e| IdeError::not_found(format!("cannot read .env file: {e}")))
})
@@ -317,7 +317,9 @@ pub async fn run_tomcat_build(host: &Host, window: &str, config: RunConfig) -> I
.filter(|s| !s.is_empty())
.or_else(|| artifacts.first().map(|a| &a.id))
.ok_or_else(|| IdeError::invalid("Choose a WAR artifact"))?;
// One deployment of the config (`ide_run::tomcat::deployment_configs`); its build records go to its own directory.
let base = ide_run::tomcat::effective_base_dir(&project.root, &project.cache_dir, &config)?;
let base = ide_run::tomcat::state_dir(&base, &config);
if let Some(name) = id.strip_prefix(PROJECT_ARTIFACT) {
let settings = project.settings.effective();
let detected = project.detected_roots.read().clone();
@@ -340,7 +342,10 @@ pub async fn run_tomcat_build(host: &Host, window: &str, config: RunConfig) -> I
let mut plan = ide_build::web::build(&project.root, &model, id, &base)?;
plan.env.extend(config.env.clone());
let mut build = RunConfig {
id: format!("tomcat-build:{}", config.id),
id: match config.extras.params.get("deploymentIndex") {
Some(i) => format!("tomcat-build:{}:{i}", config.id),
None => format!("tomcat-build:{}", config.id),
},
name: format!("Build {}", config.name),
kind: if id.starts_with("maven:") { "maven" } else { "gradle" }.into(),
command: plan.command.clone(),
@@ -405,7 +410,12 @@ pub async fn run_tomcat_sync(
let class_paths: Vec<_> =
class_paths.iter().filter_map(|p| dunce::canonicalize(project.root.join(p)).ok()).collect();
let base = ide_run::tomcat::effective_base_dir(&project.root, &project.cache_dir, &config)?;
ide_run::tomcat::sync_outputs(&base, &module, &class_paths, resources_only)
ide_run::tomcat::sync_outputs(
&ide_run::tomcat::state_dir(&base, &config),
&module,
&class_paths,
resources_only,
)
})
.await
.map_err(|e| IdeError::internal(e.to_string()))?
+10 -16
View File
@@ -1,17 +1,14 @@
//! File › New Project (`ide-scaffold`). Its commands run in Restricted Mode: New Project writes
//! only where the user chose and runs no code of an open project.
use super::{blocking, blocking_value};
use crate::Host;
use crate::ops::Channel;
use ide_command::command;
use ide_core::{IdeError, IdeResult, IpcPath, RequestId};
use ide_core::{IdeResult, IpcPath, RequestId};
use ide_scaffold::{CreateRequest, Field, GeneratorInfo, Requirement, ScaffoldEvent, Values};
use std::path::PathBuf;
fn join_err(e: impl std::fmt::Display) -> IdeError {
IdeError::internal(e.to_string())
}
/// The project generators File › New Project offers, in list order.
#[command(trust = always)]
pub fn scaffold_catalog() -> Vec<GeneratorInfo> {
@@ -29,30 +26,28 @@ pub async fn scaffold_options(
) -> IdeResult<Vec<Field>> {
// Spring Initializr's Boot versions and dependencies…; empty for other generators.
let cancel = host.begin_request(request);
let result = tokio::task::spawn_blocking(move || ide_scaffold::options(&generator, &values, &cancel))
.await
.map_err(join_err);
let result = blocking(move || ide_scaffold::options(&generator, &values, &cancel)).await;
host.end_request(request);
result?
result
}
/// The programs a generator needs for `values`, and whether they are installed.
#[command(trust = always)]
pub async fn scaffold_requirements(generator: String, values: Values) -> IdeResult<Vec<Requirement>> {
tokio::task::spawn_blocking(move || ide_scaffold::requirements(&generator, &values)).await.map_err(join_err)?
blocking(move || ide_scaffold::requirements(&generator, &values)).await
}
/// Whether a project named `name` cannot be created in `location`: something other than an
/// empty folder is already there.
#[command(trust = always)]
pub async fn scaffold_target_taken(location: PathBuf, name: String) -> IdeResult<bool> {
tokio::task::spawn_blocking(move || ide_scaffold::target_taken(&location.join(name.trim()))).await.map_err(join_err)
blocking_value(move || ide_scaffold::target_taken(&location.join(name.trim()))).await
}
/// The first of `base`, `base1`, `base2`, … that names nothing in `location` yet.
#[command(trust = always)]
pub async fn scaffold_free_name(location: PathBuf, base: String) -> IdeResult<String> {
tokio::task::spawn_blocking(move || ide_scaffold::free_name(&location, &base)).await.map_err(join_err)
blocking_value(move || ide_scaffold::free_name(&location, &base)).await
}
/// Creates a project, streaming progress through `on_event`, and returns its directory,
@@ -66,15 +61,14 @@ pub async fn scaffold_create(
) -> IdeResult<IpcPath> {
// Trusted because the user just created it; a failed or cancelled run leaves no files behind.
let cancel = host.begin_request(request);
let result = tokio::task::spawn_blocking(move || {
let result = blocking(move || {
ide_scaffold::create(&req, &cancel, &|e| {
let _ = on_event.send(e);
})
})
.await
.map_err(join_err);
.await;
host.end_request(request);
let dir = result??;
let dir = result?;
host.set_project_trust(&dir, true, false).await?;
Ok(dir.into())
}
+27 -55
View File
@@ -1,4 +1,5 @@
//! Interpreters / toolchains (`ide-sdk`): discovery, Python virtualenvs and packages.
use super::{blocking, blocking_value, join_error};
use crate::Host;
use crate::ops::Channel;
use ide_command::command;
@@ -13,10 +14,6 @@ use std::sync::atomic::{AtomicUsize, Ordering};
pub mod container_python;
pub use container_python::{ContainerPython, sdk_container_python, sdk_container_python_refresh};
fn join_err(e: impl std::fmt::Display) -> IdeError {
IdeError::internal(e.to_string())
}
/// Executables found for "run this file", and where single files are compiled to.
#[derive(Clone, Debug, serde::Serialize, specta::Type)]
#[serde(rename_all = "camelCase")]
@@ -48,7 +45,7 @@ pub async fn sdk_detect(host: &Host, window: &str, kind: SdkKind) -> IdeResult<V
(Some(p), SdkKind::Python) => ide_sdk::apply::python_interpreter(&p.root, &p.settings.effective()),
_ => None,
};
tokio::task::spawn_blocking(move || {
blocking_value(move || {
let mut sdks = ide_sdk::detect(kind, root.as_deref());
if let Some(path) = current
&& !sdks.iter().any(|s| *s.path == *path)
@@ -59,7 +56,6 @@ pub async fn sdk_detect(host: &Host, window: &str, kind: SdkKind) -> IdeResult<V
sdks
})
.await
.map_err(join_err)
}
/// The Python interpreters of the recently opened projects, each with its project.
@@ -78,7 +74,7 @@ pub async fn sdk_python_project_interpreters(host: &Host, window: &str) -> IdeRe
.filter(|root| current.as_deref() != Some(root.as_path()))
.filter(|root| host.trust.window_trusted(root).unwrap_or(false))
.collect();
tokio::task::spawn_blocking(move || {
blocking_value(move || {
// Each project resolves its configured interpreter, else its own virtualenv. The
// probes run `python`, so keep them off the async runtime and bound how many run at
// once: the recent list can hold ~30 projects, and each probe starts a process.
@@ -107,7 +103,6 @@ pub async fn sdk_python_project_interpreters(host: &Host, window: &str) -> IdeRe
found.into_iter().map(|(_, interpreter)| interpreter).collect()
})
.await
.map_err(join_err)
}
/// An existing Python executable or virtualenv folder as an SDK; `None` if Python cannot run.
@@ -115,9 +110,7 @@ pub async fn sdk_python_project_interpreters(host: &Host, window: &str) -> IdeRe
pub async fn sdk_python_interpreter(host: &Host, window: &str, path: PathBuf) -> IdeResult<Option<Sdk>> {
host.require_trust_if_project(window)?;
let root = host.project(window).ok().map(|p| p.root.clone());
tokio::task::spawn_blocking(move || Ok(ide_sdk::python_interpreter_sdk(&path, root.as_deref())))
.await
.map_err(join_err)?
blocking(move || Ok(ide_sdk::python_interpreter_sdk(&path, root.as_deref()))).await
}
/// `sys.path` of the interpreter `python`, for All Interpreters › Show Paths.
@@ -130,7 +123,7 @@ pub async fn sdk_python_sys_path(
) -> IdeResult<Vec<ide_core::IpcPath>> {
host.require_trust_if_project(window)?;
let cancel = host.begin_project_request(window, request);
let result = tokio::task::spawn_blocking(move || {
let result = blocking(move || {
let paths = ide_sdk::libraries::python_sys_path(&python, &cancel);
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
@@ -143,10 +136,9 @@ pub async fn sdk_python_sys_path(
})?;
Ok(paths.iter().map(|p| p.as_path().into()).collect())
})
.await
.map_err(join_err);
.await;
host.end_request(request);
result?
result
}
/// For each folder added to an interpreter's paths, why it stays off the import path
@@ -158,9 +150,7 @@ pub async fn sdk_python_user_path_problems(
paths: Vec<String>,
) -> IdeResult<Vec<Option<ide_sdk::apply::UserPathProblem>>> {
host.require_trust_if_project(window)?;
tokio::task::spawn_blocking(move || paths.iter().map(|p| ide_sdk::apply::user_path(p).err()).collect())
.await
.map_err(join_err)
blocking_value(move || paths.iter().map(|p| ide_sdk::apply::user_path(p).err()).collect()).await
}
/// The interpreter of the workspace member `near` belongs to, else the project's.
@@ -201,9 +191,7 @@ pub async fn sdk_python_effective(
let project = host.project(window)?;
let config_dir = host.config_dir.clone();
// Loading a member's settings needs more stack than a sync command's main thread has left.
tokio::task::spawn_blocking(move || Ok(effective_python(&config_dir, &project, near.as_deref()).map(Into::into)))
.await
.map_err(join_err)?
blocking(move || Ok(effective_python(&config_dir, &project, near.as_deref()).map(Into::into))).await
}
/// The PHP interpreter chosen in Settings › Languages & Frameworks › PHP; `None`: the `php` on `PATH`.
@@ -226,7 +214,7 @@ pub async fn sdk_php_xdebug(
) -> IdeResult<ide_sdk::php::PhpXdebug> {
host.require_trust(window)?;
let cwd = cwd.or_else(|| host.project(window).ok().map(|p| p.root.clone()));
tokio::task::spawn_blocking(move || ide_sdk::php::xdebug(&php, cwd.as_deref())).await.map_err(join_err)?
blocking(move || ide_sdk::php::xdebug(&php, cwd.as_deref())).await
}
/// The PHP language level of the project `path` belongs to (a workspace member, by path, as
@@ -249,7 +237,7 @@ pub async fn sdk_php_language_level(host: &Host, window: &str, path: PathBuf) ->
let project = host.project(window)?;
let (project_root, project_settings) = (project.root.clone(), project.settings.effective());
let config_dir = host.config_dir.clone();
tokio::task::spawn_blocking(move || {
blocking_value(move || {
let member = ide_workspace::workspace::Workspace::load(&project_root).ok().flatten().and_then(|w| {
w.projects.into_iter().filter(|p| path.starts_with(p)).max_by_key(|p| p.components().count())
});
@@ -264,7 +252,6 @@ pub async fn sdk_php_language_level(host: &Host, window: &str, path: PathBuf) ->
}
})
.await
.map_err(join_err)
}
/// The Composer project `path` belongs to, when its dependencies need `composer install`.
@@ -288,12 +275,11 @@ pub async fn sdk_php_composer_install(
return Ok(None);
}
let root = project.root.clone();
tokio::task::spawn_blocking(move || {
blocking_value(move || {
ide_sdk::php::composer_install(&path, &root)
.map(|(root, reason)| ComposerInstallState { root: ide_core::IpcPath::from(root), reason })
})
.await
.map_err(join_err)
}
/// SDK / library source folders shown under "External Libraries" in the Project view,
@@ -354,7 +340,7 @@ pub async fn sdk_project_libraries(
return Err(IdeError::cancelled());
}
let groups =
ide_sdk::libraries::merge_groups([libraries.map_err(join_err)?, dependencies.map_err(join_err)?].concat());
ide_sdk::libraries::merge_groups([libraries.map_err(join_error)?, dependencies.map_err(join_error)?].concat());
if host.project(window).is_ok_and(|current| std::sync::Arc::ptr_eq(&current, &project)) {
host.mcp_reports
.set_libraries(window, groups.iter().flat_map(|g| g.roots.iter().map(|r| r.path.0.clone())).collect());
@@ -371,12 +357,11 @@ pub async fn sdk_locate_tools(
near: Option<PathBuf>,
) -> IdeResult<LocatedTools> {
host.require_trust(window)?;
tokio::task::spawn_blocking(move || LocatedTools {
blocking_value(move || LocatedTools {
tools: ide_sdk::locate::locate_tools(&names, near.as_deref()),
compile_dir: ide_sdk::locate::compile_dir().into(),
})
.await
.map_err(join_err)
}
/// The environments the window's project defines for Hatch, `default` first (hatch must be on PATH).
@@ -385,10 +370,9 @@ pub async fn sdk_python_hatch_envs(host: &Host, window: &str, request: RequestId
host.require_trust_if_project(window)?;
let root = host.project(window)?.root.clone();
let cancel = host.begin_project_request(window, request);
let result =
tokio::task::spawn_blocking(move || ide_sdk::python::hatch_envs(&root, &cancel)).await.map_err(join_err);
let result = blocking(move || ide_sdk::python::hatch_envs(&root, &cancel)).await;
host.end_request(request);
result?
result
}
/// Creates a Python environment and streams its output through `on_output`.
@@ -407,15 +391,14 @@ pub async fn sdk_python_create_venv(
) -> IdeResult<Sdk> {
host.require_trust_if_project(window)?;
let cancel = host.begin_project_request(window, request);
let result = tokio::task::spawn_blocking(move || {
let result = blocking(move || {
ide_sdk::python::create_venv(tool, &base, &location, install_packages, &cancel, &|line| {
let _ = on_output.send(line);
})
})
.await
.map_err(join_err);
.await;
host.end_request(request);
result?
result
}
#[command(trust = outside_restricted)]
@@ -428,11 +411,9 @@ pub async fn sdk_python_packages(
) -> IdeResult<Vec<PythonPackage>> {
host.require_trust_if_project(window)?;
let cancel = host.begin_project_request(window, request);
let result = tokio::task::spawn_blocking(move || ide_sdk::python::list_packages(&python, outdated, &cancel))
.await
.map_err(join_err);
let result = blocking(move || ide_sdk::python::list_packages(&python, outdated, &cancel)).await;
host.end_request(request);
result?
result
}
/// A package index other than PyPI that installing from `python` uses; `None` for PyPI.
@@ -446,13 +427,9 @@ pub async fn sdk_python_package_index(
host.require_trust_if_project(window)?;
let project_root = host.project(window).ok().map(|p| p.root.clone());
let cancel = host.begin_project_request(window, request);
let result = tokio::task::spawn_blocking(move || {
ide_sdk::python::configured_index(&python, project_root.as_deref(), &cancel)
})
.await
.map_err(join_err);
let result = blocking(move || ide_sdk::python::configured_index(&python, project_root.as_deref(), &cancel)).await;
host.end_request(request);
result?
result
}
/// Installs (`uninstall = false`) or removes a package; output streams through `on_output`.
@@ -471,7 +448,7 @@ pub async fn sdk_python_pip(
host.require_trust_if_project(window)?;
let project_root = host.project(window).ok().map(|p| p.root.clone());
let cancel = host.begin_project_request(window, request);
let result = tokio::task::spawn_blocking(move || {
let result = blocking(move || {
let send = |line: String| {
let _ = on_output.send(line);
};
@@ -481,21 +458,16 @@ pub async fn sdk_python_pip(
ide_sdk::python::install_package(&python, &requirement, upgrade, project_root.as_deref(), &cancel, &send)
}
})
.await
.map_err(join_err);
.await;
host.end_request(request);
result?
result
}
/// The JDK whose home is `path`, as the SDK list shows it; `None` when it is no JDK home.
#[command(trust = trusted)]
pub async fn sdk_jdk_at(path: String) -> IdeResult<Option<Sdk>> {
// A macOS bundle too (Add JDK from Disk…).
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)
blocking_value(move || ide_sdk::java::jdk_at(std::path::Path::new(&path)).map(|j| ide_sdk::jdk_sdk(&j))).await
}
#[cfg(all(test, unix))]
+1 -1
View File
@@ -111,7 +111,7 @@ pub(crate) fn search_project(
};
let literals = |path: &Path, text: &str| literals_of(project, syntax, path, text);
let defaults = project.documents.file_defaults();
let fallback = |path: &Path| defaults.fallback_for(path).map(str::to_owned);
let fallback = |path: &Path| defaults.fallback_for(path).map(|f| f.encoding.to_owned());
let mut total = SearchSummary::default();
for dir in std::iter::once(root).filter(|_| include_root).chain(&content_roots) {
let mut remaining = query.clone();
+1 -1
View File
@@ -3,7 +3,7 @@ use crate::Host;
use crate::Project;
use ide_command::command;
use super::doc::blocking;
use super::blocking;
use ide_core::settings::SpellingSettings;
use ide_core::{DocId, IdeError, IdeResult, RequestId};
use ide_language::SpellingKind;
+1 -1
View File
@@ -10,7 +10,7 @@ use crate::Host;
use crate::Project;
use ide_command::command;
use super::doc::blocking;
use super::blocking;
use ide_core::{CancellationToken, DocId, IdeError, IdeResult, LanguageId, Pos, Range, RequestId};
use ide_syntax::{
ExpressionAt, FileIdentifiers, IdentifierOccurrence, Locals, NodeAt, Snapshot, StructuralRanges, StructureResult,
+109
View File
@@ -0,0 +1,109 @@
use crate::Host;
use ide_command::command;
use ide_core::{IdeResult, RunId};
use ide_dap::{JvmMemoryUnavailable, JvmThreadsResult, JvmThreadsUnavailable};
use ide_jvm_attach::{ProcEntry, is_hotspot, process_table, select_run_jvm};
use std::sync::Arc;
/// A `Thread.print -l` of the JVM a run started: the deepest HotSpot JVM of the run's process
/// tree, else the one carrying `token` (the run's marker property).
#[command(trust = trusted)]
pub async fn run_jvm_thread_dump(
host: &Arc<Host>,
window: &str,
id: RunId,
token: Option<String>,
) -> IdeResult<JvmThreadsResult> {
host.require_trust(window)?;
let remote = host.remote.runs.contains(id);
let root = if remote { None } else { host.processes.pid(id) };
let selected = host.blocking(move || Ok(run_jvm(remote, root, token.as_deref(), process_table, is_hotspot)));
let pid = match selected.await? {
Ok(pid) => pid,
Err(refused) => return Ok(refused),
};
// A debugger attached to this run or JVM (Debug of a build tool's run, Attach to Process)
// may hold it suspended, which only its session knows.
if let Some(dump) = host.debugger.debugged_jvm_thread_dump(id, pid).await {
return dump;
}
// The attach handshake blocks for seconds.
host.blocking(move || Ok(ide_dap::run_jvm_thread_dump(pid))).await
}
fn unavailable(reason: JvmThreadsUnavailable) -> JvmThreadsResult {
JvmThreadsResult::Unavailable { reason }
}
fn jvm(reason: JvmMemoryUnavailable) -> JvmThreadsResult {
unavailable(JvmThreadsUnavailable::Jvm { reason })
}
/// The run's JVM, or why none can be dumped. `root` is the run's process while it runs; the
/// process table is read only once the cheaper reasons to refuse are ruled out.
fn run_jvm(
remote: bool,
root: Option<u32>,
token: Option<&str>,
table: impl FnOnce() -> Vec<ProcEntry>,
is_hotspot: impl Fn(u32) -> bool,
) -> Result<u32, JvmThreadsResult> {
if remote {
return Err(unavailable(JvmThreadsUnavailable::RemoteRun));
}
let Some(root) = root else { return Err(jvm(JvmMemoryUnavailable::ProgramExited)) };
if !cfg!(unix) {
return Err(jvm(JvmMemoryUnavailable::UnsupportedPlatform));
}
select_run_jvm(&table(), root, token, is_hotspot).ok_or_else(|| jvm(JvmMemoryUnavailable::NoJvmProcess))
}
ide_command::domain!(thread_dump: run_jvm_thread_dump);
#[cfg(test)]
mod tests {
use super::*;
fn never_called<T>() -> T {
panic!("not reached")
}
#[cfg(unix)]
fn proc(pid: u32, ppid: u32, command: &str) -> ProcEntry {
ProcEntry { pid, ppid, command: command.into() }
}
#[test]
fn remote_run_is_refused() {
let result = run_jvm(true, Some(10), None, never_called, |_| never_called());
assert_eq!(result, Err(unavailable(JvmThreadsUnavailable::RemoteRun)));
}
#[test]
fn exited_run_reports_program_exited() {
let result = run_jvm(false, None, None, never_called, |_| never_called());
assert_eq!(result, Err(jvm(JvmMemoryUnavailable::ProgramExited)));
}
#[cfg(unix)]
#[test]
fn no_jvm_in_tree() {
let table = || vec![proc(10, 1, "sh -c run"), proc(11, 10, "sleep 100")];
let result = run_jvm(false, Some(10), None, table, |_| false);
assert_eq!(result, Err(jvm(JvmMemoryUnavailable::NoJvmProcess)));
}
#[cfg(unix)]
#[test]
fn finds_the_jvm_below_the_run() {
let table = || vec![proc(10, 1, "sh -c run"), proc(11, 10, "java -jar app.jar")];
assert_eq!(run_jvm(false, Some(10), None, table, |pid| pid == 11), Ok(11));
}
#[cfg(not(unix))]
#[test]
fn unsupported_without_reading_the_process_table() {
let result = run_jvm(false, Some(10), None, never_called, |_| never_called());
assert_eq!(result, Err(jvm(JvmMemoryUnavailable::UnsupportedPlatform)));
}
}
+14 -19
View File
@@ -1,4 +1,5 @@
//! Language server / debug adapter installer and JDK downloads (`ide-tools`).
use super::{blocking, blocking_value};
use crate::Host;
use crate::ops::Channel;
use ide_command::command;
@@ -51,10 +52,6 @@ fn languages(host: &Host, window: &str) -> Vec<ide_language::LanguageConfig> {
langs
}
fn join_err(e: impl std::fmt::Display) -> IdeError {
IdeError::internal(e.to_string())
}
fn reconfigure_servers(host: &Host) {
for project in host.projects() {
let lsp = project.lsp.clone();
@@ -67,7 +64,7 @@ fn reconfigure_servers(host: &Host) {
pub async fn tools_list(host: &Host, window: &str) -> IdeResult<Vec<ToolInfo>> {
let tools = tools(host, window)?;
let langs = languages(host, window);
tokio::task::spawn_blocking(move || tools.list(&langs)).await.map_err(join_err)
blocking_value(move || tools.list(&langs)).await
}
/// Installs (or reinstalls) a tool into `<app-data>/tools`, streaming output through
@@ -83,15 +80,14 @@ pub async fn tools_install(
let tools = tools(host, window)?;
let langs = languages(host, window);
let cancel = host.begin_request(request);
let result = tokio::task::spawn_blocking(move || {
let result = blocking(move || {
tools.install(&name, &langs, &cancel, &|e| {
let _ = on_event.send(e);
})
})
.await
.map_err(join_err);
.await;
host.end_request(request);
let info = result??;
let info = result?;
// Language servers whose launch depends on installed tools (jdtls loads the
// java-debug bundle) pick the change up.
reconfigure_servers(host);
@@ -104,9 +100,9 @@ pub async fn tools_install(
pub async fn tools_updates(host: &Host, window: &str, request: RequestId) -> IdeResult<Vec<ToolUpdate>> {
let tools = tools(host, window)?;
let cancel = host.begin_request(request);
let result = tokio::task::spawn_blocking(move || tools.updates(&cancel)).await.map_err(join_err);
let result = blocking(move || tools.updates(&cancel)).await;
host.end_request(request);
result?
result
}
/// Removes a tool the IDE installed.
@@ -114,7 +110,7 @@ pub async fn tools_updates(host: &Host, window: &str, request: RequestId) -> Ide
pub async fn tools_uninstall(host: &Host, window: &str, name: String) -> IdeResult<ToolInfo> {
let tools = tools(host, window)?;
let langs = languages(host, window);
let info = tokio::task::spawn_blocking(move || tools.uninstall(&name, &langs)).await.map_err(join_err)??;
let info = blocking(move || tools.uninstall(&name, &langs)).await?;
reconfigure_servers(host);
Ok(info)
}
@@ -130,9 +126,9 @@ pub fn jdk_download_vendors() -> Vec<JdkVendor> {
pub async fn jdk_download_releases(host: &Host, vendor: String, request: RequestId) -> IdeResult<JdkReleases> {
let tools = Tools::new(&host.local_data_dir);
let cancel = host.begin_request(request);
let result = tokio::task::spawn_blocking(move || tools.jdk_releases(&vendor, &cancel)).await.map_err(join_err);
let result = blocking(move || tools.jdk_releases(&vendor, &cancel)).await;
host.end_request(request);
result?
result
}
/// Where Download JDK puts JDKs unless told otherwise.
@@ -157,7 +153,7 @@ pub async fn jdk_download(
let tools = Tools::new(&host.local_data_dir);
let location = location.filter(|p| !p.as_os_str().is_empty());
let cancel = host.begin_request(request);
let result = tokio::task::spawn_blocking(move || {
let result = blocking(move || {
let jdk = tools.download_jdk(&vendor, version, location.as_deref(), &cancel, &|e| {
let _ = on_event.send(e);
})?;
@@ -171,10 +167,9 @@ pub async fn jdk_download(
.ok_or_else(|| IdeError::internal(format!("{} is not a JDK home", home.display())))?;
IdeResult::Ok(ide_sdk::jdk_sdk(&jdk))
})
.await
.map_err(join_err);
.await;
host.end_request(request);
let sdk = result??;
let sdk = result?;
reconfigure_servers(host);
Ok(sdk)
}
@@ -193,7 +188,7 @@ pub async fn jdtls_required_java(host: &Host, window: &str) -> IdeResult<Option<
};
ide_sdk::apply::server_launch_overrides(&mut cfg, &settings);
ide_sdk::apply::server_protocol_overrides(&mut cfg, &settings);
tokio::task::spawn_blocking(move || ide_sdk::java::jdtls_required_java(&cfg)).await.map_err(join_err)
blocking_value(move || ide_sdk::java::jdtls_required_java(&cfg)).await
}
ide_command::domain!(
+1 -4
View File
@@ -3,6 +3,7 @@ use super::*;
use crate::Host;
use crate::Project;
use crate::ops::Channel;
use crate::ops::blocking;
use ide_command::command;
use ide_core::error::PushDivergence;
use ide_core::ipc_path::IpcPath;
@@ -413,10 +414,6 @@ fn per_backend(
per_repo(project, paths, recorded, |r, paths| f(r as &dyn Backend, paths))
}
async fn blocking<T: Send + 'static>(f: impl FnOnce() -> IdeResult<T> + Send + 'static) -> IdeResult<T> {
tokio::task::spawn_blocking(f).await.map_err(|e| ide_core::IdeError::internal(e.to_string()))?
}
fn with_shelf_batch<T>(project: &Project, batch: Option<String>, operation: impl FnOnce() -> T) -> T {
let Some(batch) = batch.and_then(|id| uuid::Uuid::parse_str(&id).ok()) else { return operation() };
let repos = project.repos();
+2
View File
@@ -3516,6 +3516,7 @@ impl PluginWorkspace for HostWorkspace {
max_matches: limit.min(10_000).saturating_add(1),
context: Default::default(),
include_excluded: false,
skip_large_files: false,
};
query.exclude.extend(project.search_excludes());
let files = Mutex::new(Vec::new());
@@ -5009,6 +5010,7 @@ mod workbench_tests {
style: style.into(),
hover: None,
after: Some("after".into()),
markdown_hover: None,
};
api.decorations(Some(&path), "set", vec![item("highlight"), item("unknown")]).unwrap();
assert_eq!(api.shared.decoration_sets()["test"][0].items.len(), 1);
+2 -5
View File
@@ -5,18 +5,15 @@ use super::{
PluginInfo, PluginStatusItem, WorkbenchEvent,
};
use crate::Host;
use crate::ops::blocking;
use ide_command::command;
use ide_core::{IdeError, IdeResult, RequestId};
use ide_core::{IdeResult, RequestId};
use ide_plugin::Invocation;
use ide_workspace::settings::SettingsScope;
use std::collections::BTreeMap;
use std::path::PathBuf;
use std::sync::Arc;
async fn blocking<T: Send + 'static>(f: impl FnOnce() -> IdeResult<T> + Send + 'static) -> IdeResult<T> {
tokio::task::spawn_blocking(f).await.map_err(|e| IdeError::internal(e.to_string()))?
}
/// Runs a plugin command in the context of this window's project and focused editor.
#[allow(clippy::too_many_arguments)]
#[command(trust = trusted)]
+1 -4
View File
@@ -1,4 +1,5 @@
use super::PluginHost;
use crate::ops::blocking;
use ide_command::command;
use ide_core::{IdeError, IdeResult};
use ide_plugin::Invocation;
@@ -200,10 +201,6 @@ pub async fn plugin_navigation_markers(
.await
}
async fn blocking<T: Send + 'static>(f: impl FnOnce() -> IdeResult<T> + Send + 'static) -> IdeResult<T> {
tokio::task::spawn_blocking(f).await.map_err(|e| IdeError::internal(e.to_string()))?
}
ide_command::domain!(
plugins_index_ops:
plugin_endpoints,
+179 -20
View File
@@ -11,6 +11,7 @@ use super::{PackageFile, PluginEvent, PluginHost, PluginSource, PluginStatus, Pl
use ide_core::{IdeError, IdeResult};
use ide_extension::package::{self, Index, IndexEntry, PackageSignature, PluginIcon, SIGNATURE_FILE};
use ide_extension::{MANIFEST_FILE, Manifest};
use ide_tools::mirror;
use semver::Version;
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
@@ -237,6 +238,11 @@ impl PluginHost {
*self.default_market_url.write() = url.filter(|u| !u.trim().is_empty());
}
/// Where plugin packages are fetched from first (Tools › Download sources).
pub fn set_downloads(&self, downloads: ide_core::settings::ToolDownloadSettings) {
*self.downloads.write() = downloads;
}
pub fn set_market_url(&self, url: Option<String>) {
self.state.lock().market_url = url.filter(|u| !u.trim().is_empty());
self.save_state();
@@ -355,40 +361,111 @@ impl PluginHost {
entry.id, entry.version
)));
}
let bytes = read_url(&download, MAX_PACKAGE).map_err(IdeError::unavailable)?;
let candidates = mirror::candidates(&download, &self.downloads.read());
let downloads = self.plugins_dir.join(DOWNLOADS);
std::fs::create_dir_all(&downloads)?;
let archive = downloads.join(format!("{}-{}.{}", entry.id, entry.version, package::PACKAGE_EXTENSION));
std::fs::write(&archive, bytes)?;
let dir = self.unpack_package(&archive);
let _ = std::fs::remove_file(&archive);
let dir = dir?;
let manifest = Manifest::load(&dir).map_err(IdeError::invalid)?;
let files = self.package_files_in(&dir)?;
let digest = package::package_digest(&dir, &files)?;
if (manifest.id.as_str(), manifest.version.as_str(), digest.as_str())
!= (&entry.id, &entry.version, &entry.digest)
{
let _ = std::fs::remove_dir_all(&dir);
return Err(IdeError::invalid("the download does not match the marketplace's entry"));
let picked = try_sources(&candidates, |index, candidate| {
// Bytes a failed source left behind must not be unpacked as the next one's.
if index > 0 {
let _ = std::fs::remove_file(&archive);
}
// Which source a package comes from is the first thing to look at when an install
// is slow or fails (a mirror is one of several candidates), so it goes in the log.
tracing::info!(
"plugins: {} {} from {} ({}){}",
entry.id,
entry.version,
candidate.url,
candidate.describe(),
if candidates.len() > 1 {
format!(", source {} of {}", index + 1, candidates.len())
} else {
String::new()
}
);
let fetched = self.fetch_market_package(&candidate.url, &entry, &archive);
if let Err(e) = &fetched {
tracing::warn!("plugins: {} from {} failed: {}", entry.id, candidate.url, e.message);
}
fetched
});
match picked {
Ok((dir, index)) => {
tracing::info!(
"plugins: {} {} installed from {}",
entry.id,
entry.version,
candidates[index].describe()
);
Ok(dir)
}
Err(e) => Err(e),
}
if self.verified_publisher(&dir).is_none() {
}
/// Fetches the package of `entry` from `url`, checks it against the index (its digest, then
/// the publisher's signature) and only then hands it over, unpacked. A failure here is that
/// source's failure.
///
/// The index has no hash of the archive itself, only [`package_digest`] of the unpacked
/// contents, so the bytes have to be unpacked before they can be checked. The unpacked
/// files of a source that does **not** check are therefore kept out of reach until they
/// pass: they go to a staging folder of this attempt, and every exit but the verified one
/// removes it, so nothing a mirror served is ever left where the install page reads from.
fn fetch_market_package(&self, url: &str, entry: &IndexEntry, archive: &Path) -> IdeResult<PathBuf> {
let bytes = read_url(url, MAX_PACKAGE).map_err(IdeError::unavailable)?;
std::fs::write(archive, bytes)?;
let unpacked = self.unpack_package(archive);
// The archive is needed only until it is unpacked; a failed source leaves none behind.
let _ = std::fs::remove_file(archive);
let dir = unpacked?;
self.verify_market_package(&dir, entry).inspect_err(|_| {
let _ = std::fs::remove_dir_all(&dir);
return Err(IdeError::invalid("the marketplace package is not signed by a trusted publisher"));
}
})?;
Ok(dir)
}
/// Whether the unpacked package in `dir` is the one `entry` names: same id, version and
/// digest, and signed by a publisher the index trusts.
fn verify_market_package(&self, dir: &Path, entry: &IndexEntry) -> IdeResult<()> {
let manifest = Manifest::load(dir).map_err(IdeError::invalid)?;
let files = self.package_files_in(dir)?;
let digest = package::package_digest(dir, &files)?;
if (manifest.id.as_str(), manifest.version.as_str(), digest.as_str())
!= (&entry.id, &entry.version, &entry.digest)
{
return Err(IdeError::invalid("the download does not match the marketplace's entry"));
}
if self.verified_publisher(dir).is_none() {
return Err(IdeError::invalid("the marketplace package is not signed by a trusted publisher"));
}
Ok(())
}
/// Unpacks a package file (`.oiplugin`, or a `.zip` of a package) next to the downloads; returns the folder.
///
/// A package that fails to unpack leaves nothing: the folder is removed, so a half-written
/// zip is never mistaken for a package (a mirror's bytes reach here before they are checked).
pub fn unpack_package(&self, archive: &Path) -> IdeResult<PathBuf> {
let stem = archive.file_stem().and_then(|s| s.to_str()).unwrap_or("package");
let dir = self.plugins_dir.join(DOWNLOADS).join(format!("{stem}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let unpacked = package::unpack(archive, &dir).map_err(IdeError::invalid)?;
let unpacked = match package::unpack(archive, &dir) {
Ok(unpacked) => unpacked,
Err(e) => {
let _ = std::fs::remove_dir_all(&dir);
return Err(IdeError::invalid(e));
}
};
// Kept with the files: install checks it and keeps it with the installed copy.
if let Some(sig) = unpacked.signature {
let json = serde_json::to_string_pretty(&sig).map_err(|e| IdeError::internal(e.to_string()))?;
std::fs::write(dir.join(SIGNATURE_FILE), json)?;
let json = serde_json::to_string_pretty(&sig).map_err(|e| IdeError::internal(e.to_string()));
let written = json.and_then(|json| std::fs::write(dir.join(SIGNATURE_FILE), json).map_err(IdeError::from));
if let Err(e) = written {
let _ = std::fs::remove_dir_all(&dir);
return Err(e);
}
}
Ok(dir)
}
@@ -540,6 +617,31 @@ pub(super) fn read_signature(dir: &Path) -> Option<PackageSignature> {
serde_json::from_str(&text).ok()
}
/// The first `candidate` whose `attempt` succeeds, with its index.
///
/// A mirror is a third party: when one fails, that failure is its own and the official host
/// below still gets its turn. The official host is the last candidate, so its failure is the
/// download's: returned as it is when nothing came before it, else with the mirrors' reasons.
fn try_sources<T>(
candidates: &[mirror::Candidate],
mut attempt: impl FnMut(usize, &mirror::Candidate) -> IdeResult<T>,
) -> IdeResult<(T, usize)> {
let mut failures: Vec<String> = Vec::new();
for (index, candidate) in candidates.iter().enumerate() {
match attempt(index, candidate) {
Ok(value) => return Ok((value, index)),
// A mirror's failure is its own: the next source still gets a turn.
Err(e) if candidate.mirror.is_some() => failures.push(format!("{}: {}", candidate.describe(), e.message)),
Err(e) if failures.is_empty() => return Err(e),
Err(e) => {
failures.push(format!("{}: {}", candidate.describe(), e.message));
return Err(IdeError::unavailable(format!("could not download ({})", failures.join("; "))));
}
}
}
Err(IdeError::unavailable(format!("could not download ({})", failures.join("; "))))
}
/// Keeps the signature of a package with its installed copy.
pub(super) fn copy_signature(src: &Path, installed: &Path) {
if src.join(SIGNATURE_FILE).is_file() {
@@ -588,6 +690,60 @@ mod tests {
assert!(reachable_from("/srv/market/index.json", "/srv/market/a.oiplugin"));
}
#[test]
fn a_mirror_that_serves_a_bad_package_leaves_the_official_host_its_turn() {
// Two sources: the mirror, then the official host. The mirror answers with bytes that
// do not verify — which is exactly the failure `fetch_market_package` reports for a
// tampered package — and the official host must still be asked.
let candidates = mirror::candidates(
"https://github.com/acme/hello/releases/download/v1/acme.hello-1.0.0.oiplugin",
&ide_core::settings::ToolDownloadSettings { github_mirror: "https://gh-proxy.com/".into() },
);
let asked: std::cell::RefCell<Vec<usize>> = std::cell::RefCell::new(Vec::new());
let picked = try_sources(&candidates, |index, candidate| {
asked.borrow_mut().push(index);
match candidate.mirror.is_some() {
true => Err(IdeError::invalid("the download does not match the marketplace's entry")),
false => Ok("the official copy"),
}
});
let (copy, index) = picked.unwrap();
assert_eq!((copy, index), ("the official copy", 1));
assert_eq!(*asked.borrow(), [0, 1], "the mirror was tried first, then the official host");
// Both failing: the official host's error is the download's, with the mirror's folded in.
let err = try_sources(&candidates, |index, candidate| -> IdeResult<&str> {
match candidate.mirror.is_some() {
true => Err(IdeError::invalid("the download does not match the marketplace's entry")),
false => Err(IdeError::unavailable(format!("nothing at {index}"))),
}
})
.unwrap_err();
assert!(err.message.contains("https://gh-proxy.com/"), "{}", err.message);
assert!(err.message.contains("nothing at 1"), "{}", err.message);
}
#[test]
fn a_download_goes_to_the_mirror_first_and_the_official_host_last() {
let url = "https://github.com/acme/hello/releases/download/v1/acme.hello-1.0.0.oiplugin";
let through = mirror::candidates(
url,
&ide_core::settings::ToolDownloadSettings { github_mirror: "https://gh-proxy.com/".into() },
);
assert_eq!(through.len(), 2);
assert_eq!(through[0].url, format!("https://gh-proxy.com/{url}"));
assert!(through[0].mirror.is_some());
assert_eq!((through[1].url.as_str(), through[1].mirror.is_none()), (url, true));
// A local index's own package is not on GitHub: no prefix may carry it.
let local = mirror::candidates(
"/srv/market/a.oiplugin",
&ide_core::settings::ToolDownloadSettings { github_mirror: "https://gh-proxy.com/".into() },
);
assert_eq!(local.len(), 1);
assert_eq!(local[0].url, "/srv/market/a.oiplugin");
}
#[test]
fn a_failed_read_says_why() {
// A port nothing listens on: refused.
@@ -595,7 +751,10 @@ mod tests {
let url = format!("http://127.0.0.1:{port}/a.oiplugin");
let err = read_url(&url, 1 << 20).unwrap_err();
assert_eq!(err.matches(&url).count(), 1, "{err}");
assert!(err.to_lowercase().contains("refused"), "{err}");
// The cause follows the URL. Its wording is the OS's, and localised: assert that it is
// there rather than spelling out any one language's phrase for a refused connection.
let cause = err.strip_prefix(&url).unwrap_or_default().trim_start_matches([':', ' ']);
assert!(cause.len() > 1, "the failure says nothing beyond the URL: {err}");
}
#[test]
+3
View File
@@ -429,6 +429,8 @@ pub struct PluginHost {
announced_updates: Mutex<Vec<String>>,
/// The marketplace used while the user has set none (the app's official one).
default_market_url: RwLock<Option<String>>,
/// Tools › Download sources: where plugin packages are fetched from first.
downloads: RwLock<ide_core::settings::ToolDownloadSettings>,
/// Updates not confirmed yet (the new version hasn't started once): what
/// to roll back to.
updates: Mutex<HashMap<String, PendingUpdate>>,
@@ -499,6 +501,7 @@ impl PluginHost {
official_keys: RwLock::new(official_keys),
announced_updates: Mutex::default(),
default_market_url: RwLock::new(None),
downloads: RwLock::new(Default::default()),
updates: Mutex::default(),
project_policy: RwLock::new(Arc::new(|_| false)),
engine: PluginEngine::new().map_err(IdeError::internal)?,
+1 -4
View File
@@ -20,6 +20,7 @@
use super::{Consent, HostWorkspace, PluginEvent, PluginHost, PluginSource, SecretStore};
use crate::catalogue::TrustClass;
use crate::ops::blocking;
use crate::rpc::{Dispatcher, PeerHandle};
use base64::Engine as _;
use ide_core::{IdeError, IdeResult};
@@ -451,10 +452,6 @@ impl RemotePlugins {
}
}
async fn blocking<T: Send + 'static>(f: impl FnOnce() -> IdeResult<T> + Send + 'static) -> IdeResult<T> {
tokio::task::spawn_blocking(f).await.map_err(|e| IdeError::internal(e.to_string()))?
}
fn spawn_supervision(host: Weak<PluginHost>) -> IdeResult<()> {
std::thread::Builder::new().name("remote-plugins".into()).spawn(move || {
for n in 1u32.. {
+188 -3
View File
@@ -36,6 +36,7 @@
//! priority = "default" # or "option": only through Open With
//! layout = "tab" # or "split" / "preview": beside the text editor
//! web = "web/index.html" # a web page from the package instead of rendered content
//! frames = ["https://example.com"] # API 1.16: origins the page may embed; each needs `net:<host>`
//!
//! [[contributes.editorPanels]]
//! id = "minimap"
@@ -641,6 +642,65 @@ struct ViewDecl {
/// A web page of the package (`web/index.html`) instead of content the code renders.
#[serde(default, skip_serializing_if = "Option::is_none")]
web: Option<String>,
/// Origins the web page may embed in `<iframe>`s (API 1.16).
#[serde(default, skip_serializing_if = "Vec::is_empty")]
frames: Vec<String>,
}
/// Most origins one web page may declare in `frames`.
const MAX_FRAMES: usize = 16;
/// Checks a web page's `frames` and returns them as origins (`https://host[:port]`).
/// Each is HTTPS, or HTTP to a loopback host, and must be covered by a `net:` or
/// `net.http:` capability of the manifest, so the install page lists it; the page
/// gets only the ones the user granted.
fn frame_origins(pkg: &Package, frames: &[String], web: bool, what: &str) -> Result<Vec<String>, String> {
if frames.is_empty() {
return Ok(Vec::new());
}
pkg.manifest.needs_api(&format!("{what}: `frames`"), 16)?;
if !web {
return Err(format!("{what}: `frames` is for a web page (`web`)"));
}
if frames.len() > MAX_FRAMES {
return Err(format!("{what}: at most {MAX_FRAMES} `frames`"));
}
let mut origins = Vec::new();
for frame in frames {
let origin = frame_origin(frame).map_err(|e| format!("{what}: frames: {frame:?}: {e}"))?;
let cap = ide_plugin::net_capability(&origin).map_err(|e| format!("{what}: frames: {frame:?}: {e}"))?;
if !pkg.manifest.capabilities.all().any(|c| c.covers(&cap)) {
return Err(format!("{what}: frames: {frame:?} needs the `{cap}` capability (required or optional)"));
}
if !origins.contains(&origin) {
origins.push(origin);
}
}
Ok(origins)
}
/// `https://host[:port]` (or `http://` to a loopback host) with nothing after it.
fn frame_origin(frame: &str) -> Result<String, String> {
let url = url::Url::parse(frame).map_err(|e| format!("not a URL ({e})"))?;
let loopback = matches!(
url.host(),
Some(url::Host::Domain("localhost")) | Some(url::Host::Ipv4(std::net::Ipv4Addr::LOCALHOST))
) || url.host() == Some(url::Host::Ipv6(std::net::Ipv6Addr::LOCALHOST));
match url.scheme() {
"https" => {}
"http" if loopback => {}
_ => return Err("an origin is https://, or http:// to localhost".into()),
}
if url.host_str().is_none_or(|h| h.contains('*')) {
return Err("name one exact host".into());
}
if !url.username().is_empty() || url.password().is_some() {
return Err("no user name or password".into());
}
if url.path() != "/" || url.query().is_some() || url.fragment().is_some() {
return Err("an origin only: no path, query or fragment".into());
}
Ok(url.origin().ascii_serialization())
}
/// The files of a `web` entry, or a check that the code renders the view.
@@ -655,7 +715,7 @@ fn web_or_code(pkg: &Package, web: Option<&str>, what: &str) -> Result<Vec<PathB
}
pub(super) fn view(pkg: &Package, decl: toml::Value) -> Result<UiDecl, String> {
let d: ViewDecl = decode(VIEWS, decl)?;
let mut d: ViewDecl = decode(VIEWS, decl)?;
validate_item_id(&d.id, "view id")?;
title(VIEWS, &d.title)?;
if let Some(group) = &d.group {
@@ -668,6 +728,7 @@ pub(super) fn view(pkg: &Package, decl: toml::Value) -> Result<UiDecl, String> {
}
let files = web_or_code(pkg, d.web.as_deref(), &format!("view {:?}", d.id))?;
d.frames = frame_origins(pkg, &d.frames, d.web.is_some(), &format!("view {:?}", d.id))?;
if !["left", "right", "bottom", SERVICES_LOCATION].contains(&d.location.as_str()) {
return Err(format!("view {:?}: `location` is left, right, bottom or services", d.id));
}
@@ -734,6 +795,11 @@ struct CustomEditorDecl {
layout: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
web: Option<String>,
/// Origins the web page may embed (API 1.16).
#[serde(default, skip_serializing_if = "Vec::is_empty")]
frames: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
binary: Option<bool>,
}
fn default_priority() -> String {
@@ -758,11 +824,12 @@ fn file_patterns(patterns: &[String], what: &str) -> Result<(), String> {
}
pub(super) fn custom_editor(pkg: &Package, decl: toml::Value) -> Result<UiDecl, String> {
let d: CustomEditorDecl = decode(CUSTOM_EDITORS, decl)?;
let mut d: CustomEditorDecl = decode(CUSTOM_EDITORS, decl)?;
validate_item_id(&d.id, "custom editor id")?;
title(CUSTOM_EDITORS, &d.title)?;
let what = format!("custom editor {:?}", d.id);
let files = web_or_code(pkg, d.web.as_deref(), &what)?;
d.frames = frame_origins(pkg, &d.frames, d.web.is_some(), &what)?;
file_patterns(&d.patterns, &what)?;
if d.priority != "default" && d.priority != "option" {
return Err(format!("{what}: `priority` is default or option"));
@@ -770,6 +837,12 @@ pub(super) fn custom_editor(pkg: &Package, decl: toml::Value) -> Result<UiDecl,
if !["tab", "split", "preview"].contains(&d.layout.as_str()) {
return Err(format!("{what}: `layout` is tab, split or preview"));
}
if let Some(binary) = d.binary {
pkg.manifest.needs_api("contributes.customEditors.binary", 16)?;
if binary && (d.web.is_none() || d.layout != "tab") {
return Err(format!("{what}: `binary` requires a web editor with `layout = \"tab\"`"));
}
}
let mut out = UiDecl::new(d.id.clone(), d.title.clone(), json(&d)?);
out.files = files;
Ok(out)
@@ -783,6 +856,9 @@ struct EditorPanelDecl {
width: u32,
#[serde(default, skip_serializing_if = "Option::is_none")]
when: Option<String>,
/// Origins the page may embed (API 1.16).
#[serde(default, skip_serializing_if = "Vec::is_empty")]
frames: Vec<String>,
}
const EDITOR_PANEL_WIDTH: std::ops::RangeInclusive<u32> = 40..=400;
@@ -791,7 +867,7 @@ const EDITOR_PANEL_WIDTH: std::ops::RangeInclusive<u32> = 40..=400;
/// editor group, beside its text editor. It sees each file the group shows, so it
/// needs `editor.read`.
pub(super) fn editor_panel(pkg: &Package, decl: toml::Value) -> Result<UiDecl, String> {
let d: EditorPanelDecl = decode(EDITOR_PANELS, decl)?;
let mut d: EditorPanelDecl = decode(EDITOR_PANELS, decl)?;
pkg.manifest.needs_api(&format!("contributes.{EDITOR_PANELS}"), 9)?;
validate_item_id(&d.id, "editor panel id")?;
let what = format!("editor panel {:?}", d.id);
@@ -805,6 +881,7 @@ pub(super) fn editor_panel(pkg: &Package, decl: toml::Value) -> Result<UiDecl, S
return Err(format!("{what}: needs the `editor.read` capability (the page sees the files editors show)"));
}
let files = super::web::web_files(pkg, &d.web, &what)?;
d.frames = frame_origins(pkg, &d.frames, true, &what)?;
let mut out = UiDecl::new(d.id.clone(), d.id.clone(), json(&d)?);
out.files = files;
Ok(out)
@@ -1333,6 +1410,114 @@ mod tests {
assert!(check(&optional).is_ok());
}
#[test]
fn binary_custom_editor_requires_api_1_16() {
let dir = tempfile::tempdir().unwrap();
std::fs::create_dir(dir.path().join("web")).unwrap();
std::fs::write(dir.path().join("web/view.html"), "").unwrap();
let check = |engine: &str, binary: &str| {
let source = format!(
r#"id = "p"
name = "P"
version = "1.0.0"
engines.openidea = "{engine}"
[[contributes.customEditors]]
id = "data"
title = "Data"
patterns = ["*.bin"]
web = "web/view.html"
{binary}
"#
);
let manifest = ide_extension::Manifest::parse(&source)?;
let decl = manifest.declarations(CUSTOM_EDITORS).into_iter().next().unwrap();
custom_editor(&Package::new(manifest, dir.path().to_path_buf()), decl)
};
for value in [true, false] {
let field = format!("binary = {value}");
assert_eq!(check("^1.16", &field).unwrap().json["binary"], value);
assert_eq!(
check("^1.15", &field).unwrap_err(),
r#"contributes.customEditors.binary is new in plugin API 1.16: set engines.openidea to "^1.16""#
);
}
assert!(check("^1.15", "").unwrap().json.get("binary").is_none());
}
#[test]
fn web_pages_declare_frames_their_net_capabilities_cover() {
let dir = tempfile::tempdir().unwrap();
std::fs::create_dir(dir.path().join("web")).unwrap();
std::fs::write(dir.path().join("web/index.html"), "<iframe></iframe>").unwrap();
let header = "id = \"p\"\nname = \"P\"\nversion = \"1.0.0\"\nengines.openidea = \"^1.16\"\nwasm = \"p.wasm\"\n\
[capabilities]\nrequired = [\"editor.read\", \"net:example.com\", \"net:*.games.test\", \"net:localhost\"]\n";
let check = |point: &str, body: &str, header: &str| {
let manifest = ide_extension::Manifest::parse(&format!("{header}[[contributes.{point}]]\n{body}"))?;
let decl = manifest.declarations(point).into_iter().next().unwrap();
let pkg = Package::new(manifest, dir.path().to_path_buf());
match point {
VIEWS => view(&pkg, decl),
CUSTOM_EDITORS => custom_editor(&pkg, decl),
_ => editor_panel(&pkg, decl),
}
};
let view_with =
|frames: &str| format!("id = \"v\"\ntitle = \"V\"\nweb = \"web/index.html\"\nframes = {frames}\n");
let ok = check(
VIEWS,
&view_with(r#"["https://EXAMPLE.com/", "https://a.games.test:8443", "http://localhost:5173"]"#),
header,
)
.unwrap();
assert_eq!(
ok.json["frames"],
serde_json::json!(["https://example.com", "https://a.games.test:8443", "http://localhost:5173"])
);
assert!(
check(VIEWS, "id = \"v\"\ntitle = \"V\"\nweb = \"web/index.html\"\n", header)
.unwrap()
.json
.get("frames")
.is_none()
);
let editor = "id = \"e\"\ntitle = \"E\"\npatterns = [\"*.x\"]\nweb = \"web/index.html\"\nframes = [\"https://example.com\"]\n";
assert_eq!(
check(CUSTOM_EDITORS, editor, header).unwrap().json["frames"],
serde_json::json!(["https://example.com"])
);
let panel = "id = \"m\"\nweb = \"web/index.html\"\nwidth = 110\nframes = [\"https://example.com\"]\n";
assert_eq!(
check(EDITOR_PANELS, panel, header).unwrap().json["frames"],
serde_json::json!(["https://example.com"])
);
for (frames, error) in [
(r#"["https://other.com"]"#, "`net:other.com` capability"),
(r#"["https://games.test"]"#, "`net:games.test` capability"),
(r#"["http://example.com"]"#, "https://, or http:// to localhost"),
(r#"["ftp://example.com"]"#, "https://, or http:// to localhost"),
(r#"["https://example.com/room"]"#, "no path"),
(r#"["https://example.com?x"]"#, "no path"),
(r#"["https://example.com/#x"]"#, "no path"),
(r#"["https://*.games.test"]"#, "one exact host"),
(r#"["https://[email protected]"]"#, "user name"),
(r#"["example.com"]"#, "not a URL"),
(r#"["data:text/html,x"]"#, "https://"),
] {
let err = check(VIEWS, &view_with(frames), header).unwrap_err();
assert!(err.contains(error), "{frames} → {err}");
}
let many = format!("[{}]", vec!["\"https://example.com\""; 17].join(", "));
assert!(check(VIEWS, &view_with(&many), header).unwrap_err().contains("at most 16"));
let older = header.replace("^1.16", "^1.15");
assert!(check(VIEWS, &view_with(r#"["https://example.com"]"#), &older).unwrap_err().contains("1.16"));
let code_view = "id = \"v\"\ntitle = \"V\"\nframes = [\"https://example.com\"]\n";
assert!(check(VIEWS, code_view, header).unwrap_err().contains("for a web page"));
// `net:ask` is not a listed host: the install page would not show the origin.
let ask = header.replace("\"net:example.com\"", "\"net:ask\"");
assert!(check(VIEWS, &view_with(r#"["https://example.com"]"#), &ask).unwrap_err().contains("capability"));
}
fn package_with_catalogs(files: &[(&str, &str)]) -> (tempfile::TempDir, Package) {
let dir = tempfile::tempdir().unwrap();
std::fs::create_dir(dir.path().join(LOCALES_DIR)).unwrap();
+1 -4
View File
@@ -4,6 +4,7 @@
//! the desktop for local projects, `openidea-server` for remote ones.
use super::{PluginEditor, PluginHost, PluginOutputLine};
use crate::ops::blocking;
use ide_command::command;
use ide_core::{DocId, IdeError, IdeResult};
use ide_plugin::{EditorContext, Invocation, ServiceTab, View, ViewEvent, Viewport};
@@ -35,10 +36,6 @@ pub fn view_invocation(
})
}
async fn blocking<T: Send + 'static>(f: impl FnOnce() -> IdeResult<T> + Send + 'static) -> IdeResult<T> {
tokio::task::spawn_blocking(f).await.map_err(|e| IdeError::internal(e.to_string()))?
}
/// Content of a plugin view (`doc`: the document of a custom editor; `editor`: for
/// a tool window, the window's active editor, as commands get it).
#[allow(clippy::too_many_arguments)]
+38 -1
View File
@@ -121,6 +121,10 @@ pub(super) struct WebPtySession {
pub struct WebFile {
pub bytes: Vec<u8>,
pub mime: &'static str,
/// The origins a page may embed: `None` when no web page whose directory holds
/// the file declares `frames` (API 1.16), else the declared origins the user has
/// granted (`net:` / `net.http:`), possibly none.
pub frames: Option<Vec<String>>,
}
impl PluginHost {
@@ -324,6 +328,32 @@ impl PluginHost {
})
}
/// `frames` of the web pages whose directory holds `rel`, kept to those `granted`.
fn web_frames(&self, plugin: &str, rel: &str, granted: &[ide_extension::Capability]) -> Option<Vec<String>> {
let declared: Vec<String> = super::ui_points::WEB_POINTS
.iter()
.flat_map(|point| self.ui.items(point, Some(plugin)))
.filter(|item| {
let dir = item.decl.get("web").and_then(|w| w.as_str()).and_then(|e| e.rsplit_once('/'));
dir.is_some_and(|(dir, _)| rel.starts_with(&format!("{dir}/")))
})
.filter_map(|item| item.decl.get("frames").and_then(|f| f.as_array()).cloned())
.flatten()
.filter_map(|f| f.as_str().map(str::to_owned))
.collect();
if declared.is_empty() {
return None;
}
let mut allowed = Vec::new();
for origin in declared {
let ok = ide_plugin::net_capability(&origin).is_ok_and(|cap| granted.iter().any(|g| g.covers(&cap)));
if ok && !allowed.contains(&origin) {
allowed.push(origin);
}
}
Some(allowed)
}
/// The web roots `plugin` declares (entry directories, package-relative, `/`-terminated).
fn web_dirs(&self, plugin: &str) -> Vec<String> {
super::ui_points::WEB_POINTS
@@ -376,7 +406,14 @@ impl PluginHost {
return Err(IdeError::not_found(format!("{rel}: not part of a web view")));
}
let bytes = plugin.pkg.read_bytes(rel_path).map_err(IdeError::not_found)?;
Ok(WebFile { bytes, mime: mime(rel) })
let mime = mime(rel);
let frames = if mime.starts_with("text/html") {
let granted = plugin.meta.lock().granted.clone();
self.web_frames(plugin_id, rel, &granted)
} else {
None
};
Ok(WebFile { bytes, mime, frames })
}
}
+4 -5
View File
@@ -753,7 +753,8 @@ impl Host {
self.data_dir.join("db-history.json"),
self.ssh.clone(),
)
.with_global_sources(self.data_dir.clone()),
.with_global_sources(self.data_dir.clone())
.with_local_external_tunnels(self.local_database_tunnels),
);
let http_history = Arc::new(ide_http::History::new(self.data_dir.join("http-history").join(project_key)));
let agents = Arc::new(ide_agent::AgentManager::new(
@@ -1498,17 +1499,15 @@ impl Project {
return encoding_rs::Encoding::for_label(info.encoding.as_bytes())
.ok_or_else(|| ide_core::IdeError::invalid("unknown document encoding"));
}
let defaults = self.documents.file_defaults();
let fallback = defaults.fallback_for(path);
// The working file only when it is a regular file: a path that is a directory there
// (a committed symlink to a folder, a file replaced by a folder) has only its blob.
if path.is_file() {
let loaded = ide_vfs::load_text_with_fallback(path, fallback)?;
let loaded = self.documents.load_file(path)?;
return encoding_rs::Encoding::for_label(loaded.encoding.as_bytes())
.ok_or_else(|| ide_core::IdeError::invalid("unknown file encoding"));
}
let bytes = self.with_log_repo_of(path, |r| r.file_bytes_at(path, rev))?.unwrap_or_default();
Ok(ide_vfs::detect_encoding(&bytes, fallback))
Ok(self.documents.detect_encoding(path, &bytes))
}
/// Current text of `path`: the open buffer when available, else the file on disk.
+13 -1
View File
@@ -26,13 +26,14 @@ async fn invoke(peer: &Peer, window: &str, cmd: &str, args: Value) -> Result<Val
const NO_SESSION: i64 = 4242;
fn calls() -> [(&'static str, Value); 4] {
fn calls() -> [(&'static str, Value); 5] {
let object = json!({"generation": 1, "id": 7});
[
("debug_jvm_memory_classes", json!({"session": NO_SESSION})),
("debug_jvm_memory_instances", json!({"session": NO_SESSION, "className": "java.lang.String", "limit": 10})),
("debug_jvm_memory_fields", json!({"session": NO_SESSION, "object": object})),
("debug_jvm_memory_referrers", json!({"session": NO_SESSION, "object": object, "limit": 10})),
("debug_jvm_thread_dump", json!({"session": NO_SESSION})),
]
}
@@ -80,3 +81,14 @@ async fn class_table_is_refused_in_restricted_mode() {
let error = ide_host::ops::debug::debug_jvm_memory_classes(&host, "main", session).await.unwrap_err();
assert!(error.message.contains("Restricted Mode"), "{error:?}");
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn thread_dumps_are_refused_in_restricted_mode() {
let (host, _tmp) = host(false);
let session = ide_core::DebugSessionId(NO_SESSION as u32);
let error = ide_host::ops::debug::debug_jvm_thread_dump(&host, "main", session).await.unwrap_err();
assert!(error.message.contains("Restricted Mode"), "{error:?}");
let error =
ide_host::ops::thread_dump::run_jvm_thread_dump(&host, "main", ide_core::RunId(1), None).await.unwrap_err();
assert!(error.message.contains("Restricted Mode"), "{error:?}");
}
+167
View File
@@ -209,6 +209,11 @@ fn write_index(
path.to_string_lossy().into_owned()
}
/// The download sources setting with `mirror` as the GitHub proxy prefix (Tools › Download sources).
fn download_sources(mirror: &str) -> ide_core::settings::ToolDownloadSettings {
ide_core::settings::ToolDownloadSettings { github_mirror: mirror.into() }
}
/// Security audit lead 5: an index entry's id and version name the download file,
/// so an entry whose id or version would place it outside the downloads folder
/// is not offered, and nothing is written for it.
@@ -439,6 +444,168 @@ fn serve(body: String) -> String {
})
}
/// A loopback HTTP server that logs every request path it is asked for and answers with
/// `bytes` (a package file); the base URL to put in front of the GitHub one.
fn serve_bytes(bytes: Vec<u8>, paths: Arc<Mutex<Vec<String>>>) -> String {
use std::io::{BufRead, BufReader, Write};
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let base = format!("http://127.0.0.1:{}", listener.local_addr().unwrap().port());
std::thread::spawn(move || {
for mut stream in listener.incoming().flatten() {
let mut reader = BufReader::new(stream.try_clone().unwrap());
let mut line = String::new();
if reader.read_line(&mut line).unwrap_or(0) > 0 {
paths.lock().push(line.trim().to_owned());
}
while reader.read_line(&mut line).unwrap_or(0) > 0 && line != "\r\n" {
line.clear();
}
let _ = write!(
stream,
"HTTP/1.1 200 OK\r\nContent-Type: application/octet-stream\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
bytes.len()
);
let _ = stream.write_all(&bytes);
}
});
base
}
/// A configured mirror is tried before the official host, and its bytes must still pass the
/// index's digest and the publisher's signature: a mirror only ever carries the download
/// (Tools › Download sources), never the trust root.
#[test]
fn a_mirror_prefix_carries_plugin_packages_and_only_bytes_that_check() {
let f = fixture();
let market = f.work.join("market");
std::fs::create_dir_all(&market).unwrap();
let key = PublisherKey::from_seed([3; 32]);
let (package, mut entry) = signed_hello(&market, "1.0.0", &key, &f.host);
// The download is a GitHub one, which is the only kind a prefix may carry.
entry.download = format!(
"https://github.com/acme/openidea-hello/releases/download/v1.0.0/{}",
package.file_name().unwrap().to_string_lossy()
);
let url = write_index(&market, &key, vec![entry.clone()], vec![], false);
f.host.set_market_url(Some(url));
f.host.refresh_market().unwrap();
// The mirror answers with the real package.
let paths: Arc<Mutex<Vec<String>>> = Arc::default();
let base = serve_bytes(std::fs::read(&package).unwrap(), paths.clone());
f.host.set_downloads(download_sources(&base));
let dir = f.host.download_market_plugin("acme.hello").unwrap();
assert_eq!(f.host.preview_install(&dir).unwrap().version, "1.0.0");
let asked = paths.lock().clone();
assert_eq!(asked.len(), 1, "{asked:?}");
assert!(
asked[0].contains(entry.download.trim_start_matches("https://")),
"the official URL is appended to the prefix unchanged: {asked:?}"
);
// No mirror: the official URL is what is asked for, exactly as before.
f.host.set_downloads(download_sources(""));
assert_eq!(
ide_tools::mirror::candidates(&entry.download, &download_sources("")),
vec![ide_tools::mirror::Candidate { url: entry.download.clone(), mirror: None }]
);
// A download that is not on GitHub is not one a prefix may carry: it stays official.
let mut local = entry.clone();
local.download = package.to_string_lossy().into_owned();
assert_eq!(
ide_tools::mirror::candidates(&local.download, &download_sources(&base)),
vec![ide_tools::mirror::Candidate { url: local.download.clone(), mirror: None }]
);
}
/// A mirror serving a tampered package is a source that fails its checks — and the unpacked
/// bytes it served must not be left behind where the install page reads from.
///
/// The index has no hash of the archive itself (only `package_digest` of the unpacked
/// contents), so the bytes have to be unpacked before they can be checked; the test therefore
/// watches the staging folders, not the archive.
#[test]
fn a_tampered_package_from_a_mirror_is_refused_and_leaves_nothing_behind() {
let f = fixture();
let market = f.work.join("market");
std::fs::create_dir_all(&market).unwrap();
let key = PublisherKey::from_seed([3; 32]);
let (package, mut entry) = signed_hello(&market, "1.0.0", &key, &f.host);
entry.download = format!(
"https://github.com/acme/openidea-hello/releases/download/v1.0.0/{}",
package.file_name().unwrap().to_string_lossy()
);
let url = write_index(&market, &key, vec![entry.clone()], vec![], false);
f.host.set_market_url(Some(url));
f.host.refresh_market().unwrap();
// A package whose manifest was changed after signing: its digest disagrees with the index,
// and it carries no signature at all.
let tampered = {
let dir = f.work.join("tampered-src");
std::fs::create_dir_all(&dir).unwrap();
let unpacked = f.host.unpack_package(&package).unwrap();
copy_dir(&unpacked, &dir.join("pkg"));
let manifest = std::fs::read_to_string(dir.join("pkg/plugin.toml")).unwrap();
std::fs::write(dir.join("pkg/plugin.toml"), manifest.replace("Sample plugin", "Totally safe plugin")).unwrap();
let files = f.host.package_files_of(&dir.join("pkg")).unwrap();
let out = dir.join("tampered.oiplugin");
package::pack(&dir.join("pkg"), &files, &out, None).unwrap();
out
};
let mirror_paths: Arc<Mutex<Vec<String>>> = Arc::default();
let mirror = serve_bytes(std::fs::read(&tampered).unwrap(), mirror_paths.clone());
let downloads = f.plugins_dir.join(".downloads");
// Browsing the package above went through `unpack_package`, which stages a folder of its
// own: clear what that left so the baseline is this attempt's alone.
for dir in staging_dirs(&downloads) {
let _ = std::fs::remove_dir_all(downloads.join(dir));
}
let staging_before = staging_dirs(&downloads);
assert!(staging_before.is_empty(), "{staging_before:?}");
// The mirror answers with the tampered package, and it is the only source configured: the
// download must fail rather than install what the mirror served.
f.host.set_downloads(download_sources(&mirror));
let err = f.host.download_market_plugin("acme.hello").unwrap_err();
assert!(err.message.contains("could not download"), "{}", err.message);
assert!(err.message.contains("does not match the marketplace's entry"), "{}", err.message);
assert_eq!(mirror_paths.lock().len(), 1, "the mirror was asked once");
// Nothing the mirror served stays where the install page reads from, and the staging folder
// of the refused attempt is gone.
assert_eq!(staging_dirs(&downloads), staging_before, "a refused package left its staging folder");
let leftovers: Vec<PathBuf> = std::fs::read_dir(&downloads)
.unwrap()
.flatten()
.map(|e| e.path())
.filter(|p| p.to_string_lossy().contains("acme.hello"))
.collect();
assert!(leftovers.is_empty(), "a refused package left files behind: {leftovers:?}");
// The official host, serving the real package, still installs.
let official_paths: Arc<Mutex<Vec<String>>> = Arc::default();
let official = serve_bytes(std::fs::read(&package).unwrap(), official_paths.clone());
f.host.set_downloads(download_sources(&official));
let dir = f.host.download_market_plugin("acme.hello").unwrap();
assert_eq!(f.host.preview_install(&dir).unwrap().version, "1.0.0");
assert_eq!(official_paths.lock().len(), 1);
}
/// The staging folders under `<plugins>/.downloads`: one per unpacked package, `<stem>-<pid>`.
fn staging_dirs(downloads: &Path) -> Vec<String> {
let Ok(entries) = std::fs::read_dir(downloads) else { return Vec::new() };
let mut names: Vec<String> = entries
.flatten()
.filter(|e| e.file_type().map(|t| t.is_dir()).unwrap_or(false))
.map(|e| e.file_name().to_string_lossy().into_owned())
.collect();
names.sort();
names
}
/// An index is read up to the size an index may have, whatever its server says or sends:
/// the marketplace is read again every day, with nobody asking.
#[test]
+182
View File
@@ -124,6 +124,7 @@ impl PluginWorkspace for TestWorkspace {
max_matches: limit,
context: Default::default(),
include_excluded: false,
skip_large_files: false,
};
let files = Mutex::new(Vec::new());
let summary = ide_search::search(root, &query, &|_| None, cancel, &|file| files.lock().push(file))
@@ -3526,6 +3527,77 @@ fn views_open_project_files_at_a_line() {
assert!(opened.is_none());
}
#[test]
fn views_open_locations_use_invoking_root_and_reject_symlink_escapes() {
let f = fixture(Limits::default());
f.install(&sample("jobs"));
let other = f._tmp.path().join("project-b");
std::fs::create_dir_all(&other).unwrap();
let other = dunce::canonicalize(other).unwrap();
for root in [&f.project, &other] {
std::fs::write(root.join("jobs.log"), "build\ndeploy\nfailed\n").unwrap();
}
let press = |client: &str, root: Option<&Path>| {
f.take_events();
let inv = Invocation {
client: Some(client.into()),
workspace_root: root.map(Path::to_path_buf),
..Default::default()
};
let result = f.host.view_event("jobs", "jobs", ide_plugin::ViewEvent::Button { id: "log".into() }, inv);
let opened = f
.take_events()
.into_iter()
.filter_map(|(client, event)| match event {
PluginEvent::OpenLocation { plugin_id, path, line, column } => {
Some((client, plugin_id, path.0, line, column))
}
_ => None,
})
.collect::<Vec<_>>();
(result, opened)
};
for (client, root) in [("window-a", &f.project), ("window-b", &other), ("window-a", &f.project)] {
let (result, opened) = press(client, Some(root));
result.unwrap();
assert_eq!(opened, vec![(Some(client.into()), "jobs".into(), root.join("jobs.log"), 2, 4)]);
}
let link = f.project.join("jobs.log");
std::fs::remove_file(&link).unwrap();
let (result, opened) = press("window-a", Some(&f.project));
let error = result.unwrap_err();
assert_eq!(error.kind, ErrorKind::InvalidInput);
assert!(error.message.contains("no such file"), "{error:?}");
assert!(opened.is_empty());
let (result, opened) = press("window-a", None);
let error = result.unwrap_err();
assert_eq!(error.kind, ErrorKind::InvalidInput);
assert!(error.message.contains("no project is open"), "{error:?}");
assert!(opened.is_empty());
#[cfg(unix)]
{
use std::os::unix::fs::symlink;
symlink(other.join("jobs.log"), &link).unwrap();
let (result, opened) = press("window-a", Some(&f.project));
let error = result.unwrap_err();
assert_eq!(error.kind, ErrorKind::InvalidInput);
assert!(error.message.contains("outside the project root"), "{error:?}");
assert!(opened.is_empty());
std::fs::remove_file(&link).unwrap();
let target = f.project.join("构建 日志 [ ] # %.log");
std::fs::write(&target, "build\ndeploy\nfailed\n").unwrap();
symlink(target.file_name().unwrap(), &link).unwrap();
let (result, opened) = press("window-a", Some(&f.project));
result.unwrap();
assert_eq!(opened, vec![(Some("window-a".into()), "jobs".into(), target, 2, 4)]);
}
}
#[test]
fn commands_see_the_paths_they_were_run_on() {
let f = fixture(Limits::default());
@@ -3902,6 +3974,68 @@ path = "templates/new.draw"
assert!(f.host.web_page("web-demo", "draw").is_err());
}
#[test]
fn web_pages_embed_only_declared_and_granted_frames() {
let f = fixture(Limits::default());
let tmp = tempfile::tempdir().unwrap();
let pkg = tmp.path().join("frame-demo");
for (path, text) in [
("hall/index.html", "<iframe src=\"https://play.games.test:8443/room\"></iframe>"),
("hall/rules.html", "<p>rules</p>"),
("hall/app.js", "console.log(1)"),
("panel/index.html", "<p>panel</p>"),
] {
std::fs::create_dir_all(pkg.join(path).parent().unwrap()).unwrap();
std::fs::write(pkg.join(path), text).unwrap();
}
std::fs::write(
pkg.join("plugin.toml"),
r#"id = "frame-demo"
name = "Frame Demo"
version = "1.0.0"
engines.openidea = "^1.16"
[capabilities]
optional = ["net:example.com", "net:*.games.test"]
[[contributes.views]]
id = "hall"
title = "Hall"
web = "hall/index.html"
frames = ["https://example.com/", "https://play.games.test:8443", "https://example.com"]
[[contributes.views]]
id = "panel"
title = "Panel"
web = "panel/index.html"
"#,
)
.unwrap();
let info = f.install(&pkg);
assert_eq!(info.status, PluginStatus::Static, "{:?}", info.error);
assert_eq!(
f.host.ui_items("views").iter().find(|v| v.decl["id"] == "hall").unwrap().decl["frames"],
serde_json::json!(["https://example.com", "https://play.games.test:8443"])
);
let page = f.host.web_page("frame-demo", "hall").unwrap();
let rev = page.path.strip_prefix("frame-demo/").unwrap().split_once('/').unwrap().0.to_owned();
let frames = |path: &str| f.host.web_file("frame-demo", &format!("{rev}/{path}")).unwrap().frames;
let both = Some(vec!["https://example.com".to_owned(), "https://play.games.test:8443".to_owned()]);
// Every page in the declaring view's directory, not its other files nor another view's pages.
assert_eq!(frames("hall/index.html"), both);
assert_eq!(frames("hall/rules.html"), both);
assert_eq!(frames("hall/app.js"), None);
assert_eq!(frames("panel/index.html"), None);
// Only what the user granted: declining a host takes it out of the policy.
f.host.set_capability("frame-demo", "net:example.com", false).unwrap();
assert_eq!(frames("hall/index.html"), Some(vec!["https://play.games.test:8443".to_owned()]));
f.host.set_capability("frame-demo", "net:*.games.test", false).unwrap();
assert_eq!(frames("hall/index.html"), Some(Vec::new()));
f.host.set_capability("frame-demo", "net:example.com", true).unwrap();
assert_eq!(frames("hall/index.html"), Some(vec!["https://example.com".to_owned()]));
}
#[test]
fn file_icons_without_patterns_require_api_1_8_and_project_assets() {
let f = fixture(Limits::default());
@@ -5286,6 +5420,34 @@ fn project_notifications_go_to_a_window_of_that_project_only() {
assert_eq!(f.status("jobs"), PluginStatus::Active);
}
#[test]
fn file_prompts_return_the_path_from_the_calling_window_without_a_capability() {
use ide_plugin::{PluginFileFilter, Prompt};
let f = fixture(Limits::default());
f.install(&sample("jobs"));
f.host.set_capability("jobs", "project.read", false).unwrap();
for name in [None, Some("result.parquet")] {
let (result, prompt) = run_and_answer(&f, "pick-file", name, Some(&["C:/data/chosen.parquet"]), Duration::ZERO);
assert_eq!(result.unwrap().as_deref(), Some("C:/data/chosen.parquet"));
assert_eq!(
prompt,
Prompt::PickFile {
title: "Data file".into(),
save: name.is_some(),
name: name.map(str::to_owned),
filters: vec![PluginFileFilter { name: "Parquet".into(), extensions: vec!["parquet".into()] }],
}
);
}
// A suggested name is only a file name, never a directory to start in.
let (_, prompt) =
run_and_answer(&f, "pick-file", Some("/etc/out.parquet"), Some(&["C:/data/x.parquet"]), Duration::ZERO);
assert!(matches!(&prompt, Prompt::PickFile { name: Some(n), .. } if n == "out.parquet"), "{prompt:?}");
assert_eq!(run_and_answer(&f, "pick-file", None, None, Duration::ZERO).0.unwrap(), None);
assert!(run_and_answer(&f, "pick-file", None, Some(&["relative"]), Duration::ZERO).0.is_err());
assert!(f.host.run_command("jobs", "pick-file", None, Invocation::default()).is_err());
}
#[test]
fn directory_prompts_and_project_requests_use_the_calling_window_without_a_capability() {
use ide_plugin::Prompt;
@@ -6794,6 +6956,26 @@ fn api14_stage3_terminal_calls_are_denied_without_process_grants() {
assert!(f.run("execution", "terminal", None).unwrap_err().contains("not granted"));
}
/// API 1.15: a plugin pushes line-end labels whose hover is Markdown, and clears them.
#[test]
fn markdown_decorations_publish_a_hover_card_and_clear() {
let f = fixture(Limits::default());
f.install(&sample("decorations"));
f.run("decorations", "publish", Some("src/notes.txt")).unwrap();
let sets = f.host.decoration_sets();
let set = &sets["decorations"][0];
assert_eq!((set.set_id.as_str(), set.tree), ("example", false));
assert_eq!(set.items.len(), 1);
assert_eq!(set.items[0].style, "highlight");
assert_eq!(set.items[0].after.as_deref(), Some(" + model-x"));
assert_eq!(
set.items[0].markdown_hover.as_deref(),
Some("**model-x** generated this line\n\n- prompt: add a greeting")
);
f.run("decorations", "clear", None).unwrap();
assert!(f.host.decoration_sets()["decorations"].is_empty());
}
// ─── Project window groups ────────────────────────────────────────────────────
// A group's container root holds only `.openidea` metadata; the files live in
// the member projects. The plugin surface reaches them like the editor and the
+2
View File
@@ -40,6 +40,7 @@ async fn find(host: &Host, paths: Vec<PathBuf>, pattern: &str) -> Vec<ide_search
max_matches: 0,
context: Default::default(),
include_excluded: false,
skip_large_files: false,
},
ide_host::ops::Channel::new(move |event| {
if let search::SearchEvent::File { file } = event {
@@ -161,6 +162,7 @@ async fn properties_search_git_and_document_coordinates_agree() {
max_matches: 0,
context: Default::default(),
include_excluded: false,
skip_large_files: false,
};
search::replace_in_files(
&host,
+68 -13
View File
@@ -1,16 +1,20 @@
mod common;
use ide_core::{ChangeSet, TextChange};
use ide_host::{Host, ops::vcs};
use std::{path::Path, process::Command, time::Duration};
use ide_host::{Host, Project, ops::vcs};
use std::{
path::{Path, PathBuf},
process::Command,
sync::Arc,
time::Duration,
};
fn git(root: &Path, args: &[&str]) {
let out = Command::new("git").current_dir(root).args(args).output().unwrap();
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn gbk_document_gutter_diff_stage_and_rollback_share_encoding() {
fn repo() -> (tempfile::TempDir, PathBuf, PathBuf) {
let temp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(temp.path()).unwrap();
let root = base.join("project");
@@ -20,6 +24,25 @@ async fn gbk_document_gutter_diff_stage_and_rollback_share_encoding() {
git(&root, &["config", "user.email", "[email protected]"]);
git(&root, &["config", "commit.gpgsign", "false"]);
git(&root, &["config", "core.autocrlf", "false"]);
(temp, base, root)
}
async fn open(base: &Path, root: &Path) -> (Host, Arc<Project>) {
let host = Host::new(common::host_config(base));
host.trust.decide(root, true, false).unwrap();
let project = host.open_project("main", root).unwrap();
for _ in 0..500 {
if !project.repos().is_empty() {
break;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
(host, project)
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn gbk_document_gutter_diff_stage_and_rollback_share_encoding() {
let (_temp, base, root) = repo();
let path = root.join("Example.java");
let old = "// 中文注释\nclass Example {\n // 保持不变\n int value = 1;\n}\n";
let original = ide_vfs::encode(old, "gbk", false).unwrap();
@@ -27,15 +50,7 @@ async fn gbk_document_gutter_diff_stage_and_rollback_share_encoding() {
std::fs::write(root.join("Utf8.java"), old).unwrap();
git(&root, &["add", "."]);
git(&root, &["commit", "-m", "GBK Java"]);
let host = Host::new(common::host_config(&base));
host.trust.decide(&root, true, false).unwrap();
let project = host.open_project("main", &root).unwrap();
for _ in 0..500 {
if !project.repos().is_empty() {
break;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
let (host, project) = open(&base, &root).await;
let mut defaults = project.documents.file_defaults();
defaults.project_fallback = "gbk".into();
project.documents.set_file_defaults(defaults);
@@ -139,3 +154,43 @@ async fn a_directory_symlink_revision_is_its_target() {
assert_eq!(vcs::vcs_file_mode(&host, "main", link, Some("HEAD".into())).await.unwrap().as_deref(), Some("120000"));
host.close_project("main");
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn ascii_properties_keep_utf8_for_vcs_by_default() {
let (_temp, base, root) = repo();
let path = root.join("messages.properties");
std::fs::write(&path, b"greeting=Hello\n").unwrap();
git(&root, &["add", "."]);
git(&root, &["commit", "-m", "properties"]);
let (host, project) = open(&base, &root).await;
assert_eq!(project.vcs_encoding(&path, None).unwrap().charset, encoding_rs::UTF_8, "working file");
std::fs::remove_file(&path).unwrap();
assert_eq!(project.vcs_encoding(&path, Some("HEAD")).unwrap().charset, encoding_rs::UTF_8, "revision");
host.close_project("main");
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn vcs_labels_ascii_files_like_the_editor() {
let (_temp, base, root) = repo();
std::fs::write(root.join(".editorconfig"), "root = true\n[Utf8.java]\ncharset = utf-8\n").unwrap();
let latin = root.join("Latin.java");
let utf8 = root.join("Utf8.java");
std::fs::write(&latin, b"class Latin {}\n").unwrap();
std::fs::write(&utf8, b"class Utf8 {}\n").unwrap();
git(&root, &["add", "."]);
git(&root, &["commit", "-m", "ascii"]);
let (host, project) = open(&base, &root).await;
let mut defaults = project.documents.file_defaults();
defaults.project_fallback = "iso-8859-15".into();
project.documents.set_file_defaults(defaults);
let charset = |path: &Path, rev| project.vcs_encoding(path, rev).unwrap().charset;
assert_eq!(charset(&latin, None), encoding_rs::ISO_8859_15, "working file, project encoding");
assert_eq!(charset(&utf8, None), encoding_rs::UTF_8, "working file, .editorconfig charset");
std::fs::remove_file(&latin).unwrap();
std::fs::remove_file(&utf8).unwrap();
assert_eq!(charset(&latin, Some("HEAD")), encoding_rs::ISO_8859_15, "revision, project encoding");
assert_eq!(charset(&utf8, Some("HEAD")), encoding_rs::UTF_8, "revision, .editorconfig charset");
host.close_project("main");
}
+7
View File
@@ -112,6 +112,7 @@ mod tests {
#[test]
fn scan_matches_port_not_first_listener() {
let _serial = crate::test_serial::hold();
let dir = tempfile::tempdir().unwrap();
let _a = fake_jvm(dir.path(), ".java_pid111", Some(5005));
let _b = fake_jvm(dir.path(), ".java_pid222", Some(6006));
@@ -120,6 +121,7 @@ mod tests {
#[test]
fn scan_returns_none_when_no_port_matches() {
let _serial = crate::test_serial::hold();
let dir = tempfile::tempdir().unwrap();
let _a = fake_jvm(dir.path(), ".java_pid111", Some(5005));
assert_eq!(find_in(dir.path(), 6006, SECOND, 2 * SECOND, ALL), None);
@@ -127,6 +129,7 @@ mod tests {
#[test]
fn scan_skips_silent_listener_within_budget() {
let _serial = crate::test_serial::hold();
let dir = tempfile::tempdir().unwrap();
let _silent = fake_jvm(dir.path(), ".java_pid111", None);
let _b = fake_jvm(dir.path(), ".java_pid222", Some(6006));
@@ -137,6 +140,7 @@ mod tests {
#[test]
fn scan_gives_up_at_the_budget_even_if_a_query_could_run_longer() {
let _serial = crate::test_serial::hold();
let dir = tempfile::tempdir().unwrap();
let _silent = fake_jvm(dir.path(), ".java_pid111", None);
let started = Instant::now();
@@ -146,6 +150,7 @@ mod tests {
#[test]
fn scan_ignores_non_matching_names() {
let _serial = crate::test_serial::hold();
let dir = tempfile::tempdir().unwrap();
let _a = fake_jvm(dir.path(), ".java_pidabc", Some(6006));
let _b = fake_jvm(dir.path(), ".java_pid", Some(6006));
@@ -156,6 +161,7 @@ mod tests {
#[test]
fn scan_applies_the_socket_trust_checks() {
let _serial = crate::test_serial::hold();
let dir = tempfile::tempdir().unwrap();
let _a = fake_jvm(dir.path(), ".java_pid111", Some(6006));
fs::set_permissions(dir.path().join(".java_pid111"), fs::Permissions::from_mode(0o666)).unwrap();
@@ -170,6 +176,7 @@ mod tests {
#[test]
fn scan_never_asks_a_jvm_the_caller_rejects() {
let _serial = crate::test_serial::hold();
let dir = tempfile::tempdir().unwrap();
let _a = fake_jvm(dir.path(), ".java_pid111", Some(6006));
let offered = std::sync::Mutex::new(Vec::new());
+70 -12
View File
@@ -35,16 +35,7 @@ fn version_from(text: &str) -> Option<JavaVersion> {
pub fn java_version_of(pid: u32) -> Option<JavaVersion> {
#[cfg(any(target_os = "linux", target_os = "macos"))]
{
let exe = std::fs::canonicalize(exe_path(pid)?).ok()?;
// `<jdk>/bin/java`, or `<jdk>/jre/bin/java` on JDK 8.
let home = exe.parent()?.parent()?;
// Only climb out of `jre/`, so a JDK without its own `release` cannot pick up an
// unrelated file in a shared parent such as `/usr/lib/jvm`.
let outer = if home.file_name().is_some_and(|n| n == "jre") { home.parent() } else { None };
[Some(home), outer].into_iter().flatten().find_map(|dir| {
let contents = std::fs::read_to_string(dir.join("release")).ok()?;
parse_release(&contents)
})
version_of_exe(&exe_path(pid)?)
}
#[cfg(not(any(target_os = "linux", target_os = "macos")))]
{
@@ -53,13 +44,41 @@ pub fn java_version_of(pid: u32) -> Option<JavaVersion> {
}
}
#[cfg(any(target_os = "linux", target_os = "macos", test))]
fn version_of_exe(exe: &std::path::Path) -> Option<JavaVersion> {
releases_of(exe).iter().find_map(|release| parse_release(release))
}
/// The `release` files of the JDK whose `java` executable is `exe`, nearest first.
#[cfg(any(target_os = "linux", target_os = "macos", test))]
fn releases_of(exe: &std::path::Path) -> Vec<String> {
let Some(exe) = std::fs::canonicalize(exe).ok() else { return Vec::new() };
// `<jdk>/bin/java`, or `<jdk>/jre/bin/java` on JDK 8.
let Some(home) = exe.parent().and_then(std::path::Path::parent) else { return Vec::new() };
// Only climb out of `jre/`, so a JDK without its own `release` cannot pick up an
// unrelated file in a shared parent such as `/usr/lib/jvm`.
let outer = if home.file_name().is_some_and(|n| n == "jre") { home.parent() } else { None };
[Some(home), outer]
.into_iter()
.flatten()
.filter_map(|dir| std::fs::read_to_string(dir.join("release")).ok())
.collect()
}
/// OpenJ9 (IBM Semeru) answers SIGQUIT by writing a `javacore` file into its working directory
/// instead of opening a listener. Its `release` files name it under varying keys.
#[cfg(any(target_os = "linux", target_os = "macos", test))]
pub(crate) fn is_openj9(exe: &std::path::Path) -> bool {
releases_of(exe).iter().any(|release| release.to_ascii_lowercase().contains("openj9"))
}
#[cfg(target_os = "linux")]
fn exe_path(pid: u32) -> Option<PathBuf> {
pub(crate) fn exe_path(pid: u32) -> Option<PathBuf> {
std::fs::read_link(format!("/proc/{pid}/exe")).ok()
}
#[cfg(target_os = "macos")]
fn exe_path(pid: u32) -> Option<PathBuf> {
pub(crate) fn exe_path(pid: u32) -> Option<PathBuf> {
use std::{ffi::c_void, os::unix::ffi::OsStringExt};
let mut buf = vec![0u8; libc::PROC_PIDPATHINFO_MAXSIZE as usize];
@@ -85,6 +104,7 @@ pub fn wants_listener_flag(jvm_args: &str) -> bool {
#[cfg(test)]
mod tests {
use super::*;
use std::path::{Path, PathBuf};
#[test]
fn release_versions() {
@@ -100,6 +120,44 @@ mod tests {
assert_eq!(parse_vm_version("OpenJDK 64-Bit Server VM version 25.512-b09\nJDK 8.0_512\n").unwrap().major, 8);
}
fn fake_jdk(dir: &Path, java: &str, release: Option<&str>) -> PathBuf {
let exe = dir.join(java);
std::fs::create_dir_all(exe.parent().unwrap()).unwrap();
std::fs::write(&exe, "").unwrap();
if let Some(release) = release {
std::fs::write(dir.join("release"), release).unwrap();
}
exe
}
#[test]
fn version_of_a_jre_falls_back_to_the_jdk_release() {
let root = tempfile::tempdir().unwrap();
let jdk = root.path().join("jdk8");
let exe = fake_jdk(&jdk, "jre/bin/java", Some("JAVA_VERSION=\"1.8.0_512\"\n"));
assert_eq!(version_of_exe(&exe).map(|v| v.major), Some(8));
// A `jre/release` without the version, as some JDK 8 builds ship.
std::fs::write(jdk.join("jre/release"), "IMPLEMENTOR=\"Oracle Corporation\"\n").unwrap();
assert_eq!(version_of_exe(&exe).map(|v| v.major), Some(8));
// Outside `jre/` nothing above the JDK is read.
let lone = fake_jdk(&root.path().join("jdk/x"), "bin/java", Some("IMPLEMENTOR=x\n"));
std::fs::write(root.path().join("jdk/release"), "JAVA_VERSION=\"17\"\n").unwrap();
assert_eq!(version_of_exe(&lone), None);
}
#[test]
fn openj9_is_told_by_its_release_file() {
let root = tempfile::tempdir().unwrap();
let semeru = "IMPLEMENTOR=\"IBM Corporation\"\nJAVA_VERSION=\"21.0.5\"\nJVM_VARIANT=\"Openj9\"\n";
let temurin = "IMPLEMENTOR=\"Eclipse Adoptium\"\nJAVA_VERSION=\"21.0.5\"\n";
let only_build = "JAVA_VERSION=\"17\"\nBUILD_INFO=\"OpenJDK 17 with Eclipse OpenJ9 VM\"\n";
assert!(is_openj9(&fake_jdk(&root.path().join("semeru"), "bin/java", Some(semeru))));
assert!(is_openj9(&fake_jdk(&root.path().join("other-key"), "bin/java", Some(only_build))));
assert!(is_openj9(&fake_jdk(&root.path().join("jdk8"), "jre/bin/java", Some(semeru))));
assert!(!is_openj9(&fake_jdk(&root.path().join("temurin"), "bin/java", Some(temurin))));
assert!(!is_openj9(&fake_jdk(&root.path().join("bare"), "bin/java", None)));
}
#[test]
fn suspended_gate() {
assert!(!histogram_safe_while_suspended(11));
+8
View File
@@ -2,8 +2,12 @@ mod discover;
mod heap_dump;
mod histogram;
mod jvm;
mod listener;
mod properties;
mod socket;
#[cfg(all(test, unix))]
mod test_serial;
mod threads;
pub use discover::find_jvm_by_jdwp_port;
pub use heap_dump::{HeapDumpReply, dump_timeout, heap_dump, heap_dump_command, parse_heap_dump_reply, vm_flags};
@@ -12,5 +16,9 @@ pub use jvm::{
JavaVersion, START_LISTENER_FLAG, histogram_safe_while_suspended, java_version_of, parse_release, parse_vm_version,
wants_listener_flag,
};
pub use listener::{LISTENER_START_TIMEOUT, ensure_listener, is_hotspot};
pub use properties::{jdwp_port, parse_properties};
pub use socket::{AttachError, MAX_OUTPUT, agent_properties, has_listener, jcmd, temp_dir};
pub use threads::{
ProcEntry, RUN_TOKEN_PROPERTY, THREAD_DUMP_TIMEOUT, is_application_jvm, process_table, select_run_jvm, thread_print,
};
+395
View File
@@ -0,0 +1,395 @@
use std::time::Duration;
use crate::socket::AttachError;
#[cfg(unix)]
use crate::socket::{check_socket, has_listener, has_listener_at, socket_path, temp_dir};
#[cfg(any(target_os = "linux", target_os = "macos", all(unix, test)))]
use std::time::UNIX_EPOCH;
#[cfg(unix)]
use std::{
fs::{Metadata, OpenOptions},
io,
os::unix::fs::{MetadataExt, OpenOptionsExt},
path::{Path, PathBuf},
time::{Instant, SystemTime},
};
/// Default budget for `ensure_listener`.
pub const LISTENER_START_TIMEOUT: Duration = Duration::from_secs(5);
#[cfg(unix)]
const POLL_INTERVAL: Duration = Duration::from_millis(50);
/// True when `pid` is confirmed to be a HotSpot JVM: it has an attach listener, a perf-data
/// file of the current user written since it started, or runs an executable named `java`
/// (`-XX:-UsePerfData` JVMs).
pub fn is_hotspot(pid: u32) -> bool {
#[cfg(unix)]
{
signal_target(pid).is_some() && (has_listener(pid) || has_perf_data(pid) || runs_java(pid))
}
#[cfg(not(unix))]
{
let _ = pid;
false
}
}
/// Opens `pid`'s attach listener if it has none, as the JDK's attach API does: a
/// `.attach_pid<pid>` trigger file, then SIGQUIT. Refuses anything `is_hotspot` does not
/// confirm (`NotAJvm`), because SIGQUIT's default action terminates any other process, and a
/// socket that fails the ownership check (`ForeignListener`).
///
/// Blocks for up to `timeout`. A JVM that ignores attach (`-XX:+DisableAttachMechanism`) still
/// handles the SIGQUIT: it prints a thread dump to its own stdout.
pub fn ensure_listener(pid: u32, timeout: Duration) -> Result<(), AttachError> {
#[cfg(unix)]
{
ensure_listener_at(&socket_path(pid), pid, timeout)
}
#[cfg(not(unix))]
{
let _ = (pid, timeout);
Err(AttachError::Unsupported)
}
}
#[cfg(unix)]
fn ensure_listener_at(socket: &Path, pid: u32, timeout: Duration) -> Result<(), AttachError> {
// `has_listener` reads a socket that fails the trust check as absent; signalling past it
// would leave its owner answering in the JVM's place.
match check_socket(socket) {
Ok(()) => return Ok(()),
Err(AttachError::NoListener) => {}
Err(e) => return Err(e),
}
let Some(target) = signal_target(pid).filter(|_| is_hotspot(pid)) else {
return Err(AttachError::NotAJvm);
};
let deadline = Instant::now() + timeout;
let _trigger = Trigger::create(pid)?;
signal(target, libc::SIGQUIT)?;
loop {
if has_listener_at(socket) {
return Ok(());
}
signal(target, 0)?;
let remaining = deadline.saturating_duration_since(Instant::now());
if remaining.is_zero() {
return Err(AttachError::ListenerDidNotStart);
}
std::thread::sleep(remaining.min(POLL_INTERVAL));
}
}
/// `kill` treats 0 and negative pids as process groups, which would signal the IDE itself.
#[cfg(unix)]
fn signal_target(pid: u32) -> Option<libc::pid_t> {
libc::pid_t::try_from(pid).ok().filter(|p| *p > 0)
}
#[cfg(unix)]
fn signal(pid: libc::pid_t, signal: libc::c_int) -> Result<(), AttachError> {
// SAFETY: kill has no memory preconditions; `pid` is positive, so only that process is targeted.
if unsafe { libc::kill(pid, signal) } == 0 {
return Ok(());
}
let err = io::Error::last_os_error();
if err.raw_os_error() == Some(libc::ESRCH) { Err(AttachError::NoListener) } else { Err(err.into()) }
}
/// `.attach_pid<pid>`, removed on every path out of `ensure_listener`.
#[cfg(unix)]
struct Trigger(PathBuf);
#[cfg(unix)]
impl Trigger {
fn create(pid: u32) -> Result<Self, AttachError> {
let name = format!(".attach_pid{pid}");
// HotSpot looks in its working directory before the temp dir; through /proc that also
// reaches a JVM in another mount namespace.
#[cfg(target_os = "linux")]
let candidates = [PathBuf::from(format!("/proc/{pid}/cwd")).join(&name), temp_dir().join(&name)];
#[cfg(not(target_os = "linux"))]
let candidates = [temp_dir().join(&name)];
let mut failure = None;
for path in candidates {
match create_private(&path) {
Ok(()) => return Ok(Self(path)),
Err(e) => failure = Some(e),
}
}
Err(failure.expect("at least one candidate").into())
}
}
#[cfg(unix)]
impl Drop for Trigger {
fn drop(&mut self) {
let _ = std::fs::remove_file(&self.0);
}
}
/// `create_new` refuses to follow a symlink planted in a shared directory.
#[cfg(unix)]
fn create_private(path: &Path) -> io::Result<()> {
match OpenOptions::new().write(true).create_new(true).mode(0o600).open(path) {
Ok(_) => Ok(()),
// Left by an attempt that died before its cleanup; nobody else's file is adopted.
Err(e) if e.kind() == io::ErrorKind::AlreadyExists && owned_regular_file(path) => Ok(()),
Err(e) => Err(e),
}
}
#[cfg(unix)]
fn owned_regular_file(path: &Path) -> bool {
std::fs::symlink_metadata(path).is_ok_and(|meta| owned_regular(&meta))
}
#[cfg(unix)]
fn owned_regular(meta: &Metadata) -> bool {
// SAFETY: geteuid has no preconditions and cannot fail.
meta.is_file() && meta.uid() == unsafe { libc::geteuid() }
}
/// `<temp>/hsperfdata_<user>/<pid>`, which HotSpot writes unless run with `-XX:-UsePerfData`.
/// Ownership matters outside macOS, where the directory sits in a shared `/tmp`.
#[cfg(unix)]
fn has_perf_data(pid: u32) -> bool {
let Some(user) = effective_user_name() else { return false };
let path = temp_dir().join(format!("hsperfdata_{user}")).join(pid.to_string());
std::fs::symlink_metadata(path).is_ok_and(|meta| {
owned_regular(&meta) && meta.modified().is_ok_and(|modified| written_since_start(modified, process_start(pid)))
})
}
/// Absorbs the coarser clock of the start time: Linux knows the boot time only to the second.
#[cfg(unix)]
const START_SLACK: Duration = Duration::from_secs(2);
/// A perf-data file older than the process was left by a JVM that died without removing it
/// (SIGKILL) and whose pid was reused. An unknown start time proves nothing.
#[cfg(unix)]
fn written_since_start(modified: SystemTime, started: Option<SystemTime>) -> bool {
started.and_then(|start| start.checked_sub(START_SLACK)).is_some_and(|earliest| modified >= earliest)
}
#[cfg(target_os = "macos")]
fn process_start(pid: u32) -> Option<SystemTime> {
let pid = libc::c_int::try_from(pid).ok()?;
// SAFETY: proc_bsdinfo is plain data; all-zero is a valid value.
let mut info: libc::proc_bsdinfo = unsafe { std::mem::zeroed() };
let size = std::mem::size_of::<libc::proc_bsdinfo>() as libc::c_int;
// SAFETY: `info` is writable for `size` bytes, the most PROC_PIDTBSDINFO writes.
let written = unsafe { libc::proc_pidinfo(pid, libc::PROC_PIDTBSDINFO, 0, (&raw mut info).cast(), size) };
if written != size {
return None;
}
Some(UNIX_EPOCH + Duration::from_secs(info.pbi_start_tvsec) + Duration::from_micros(info.pbi_start_tvusec))
}
#[cfg(target_os = "linux")]
fn process_start(pid: u32) -> Option<SystemTime> {
let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?;
let system = std::fs::read_to_string("/proc/stat").ok()?;
// SAFETY: sysconf has no preconditions.
let ticks_per_sec = unsafe { libc::sysconf(libc::_SC_CLK_TCK) };
start_from_proc(&stat, &system, u64::try_from(ticks_per_sec).ok().filter(|t| *t > 0)?)
}
#[cfg(all(unix, not(any(target_os = "linux", target_os = "macos"))))]
fn process_start(_pid: u32) -> Option<SystemTime> {
None
}
/// `/proc/<pid>/stat` field 22 is the start in clock ticks since boot; `btime` in `/proc/stat`
/// is the boot time in seconds since the epoch.
#[cfg(any(target_os = "linux", all(unix, test)))]
fn start_from_proc(stat: &str, system: &str, ticks_per_sec: u64) -> Option<SystemTime> {
// The command name (field 2) may contain spaces and parentheses; the fields after it start at 3.
let ticks: u64 = stat.rsplit_once(')')?.1.split_whitespace().nth(22 - 3)?.parse().ok()?;
let boot: u64 = system.lines().find_map(|line| line.strip_prefix("btime "))?.trim().parse().ok()?;
let since_boot = Duration::from_millis(ticks.checked_mul(1000)? / ticks_per_sec);
Some(UNIX_EPOCH + Duration::from_secs(boot) + since_boot)
}
/// HotSpot names the perf-data directory after the effective user's passwd entry.
#[cfg(unix)]
fn effective_user_name() -> Option<String> {
let mut buf = vec![0 as libc::c_char; 4096];
// SAFETY: passwd is plain data; all-zero is a valid value.
let mut pwd: libc::passwd = unsafe { std::mem::zeroed() };
let mut result: *mut libc::passwd = std::ptr::null_mut();
// SAFETY: every pointer refers to a live local buffer of the stated size.
let rc = unsafe { libc::getpwuid_r(libc::geteuid(), &mut pwd, buf.as_mut_ptr(), buf.len(), &mut result) };
if rc != 0 || result.is_null() || pwd.pw_name.is_null() {
return None;
}
// SAFETY: on success `pw_name` is a NUL-terminated string inside `buf`.
let name = unsafe { std::ffi::CStr::from_ptr(pwd.pw_name) };
Some(name.to_string_lossy().into_owned())
}
#[cfg(any(target_os = "linux", target_os = "macos"))]
fn runs_java(pid: u32) -> bool {
crate::jvm::exe_path(pid)
.is_some_and(|exe| exe.file_name().is_some_and(|name| name == "java") && !crate::jvm::is_openj9(&exe))
}
#[cfg(all(unix, not(any(target_os = "linux", target_os = "macos"))))]
fn runs_java(_pid: u32) -> bool {
false
}
#[cfg(all(test, unix))]
mod tests {
use super::*;
use std::process::Command;
/// Kills the child even when an assertion fails.
struct ChildGuard(std::process::Child);
impl Drop for ChildGuard {
fn drop(&mut self) {
let _ = self.0.kill();
let _ = self.0.wait();
}
}
fn spawn_sleep() -> ChildGuard {
ChildGuard(Command::new("sleep").arg("30").spawn().expect("spawn sleep"))
}
#[test]
fn is_hotspot_false_for_sleep() {
let _serial = crate::test_serial::hold();
let sleep = spawn_sleep();
assert!(!is_hotspot(sleep.0.id()));
}
/// `sleep` copied to `<jdk>/bin/java`: confirmed HotSpot by its name alone, unless the
/// JDK's `release` file says OpenJ9.
#[cfg(any(target_os = "linux", target_os = "macos"))]
fn sleep_as_java(release: &str) -> (tempfile::TempDir, ChildGuard) {
let jdk = tempfile::tempdir().unwrap();
let java = jdk.path().join("bin/java");
std::fs::create_dir(java.parent().unwrap()).unwrap();
let sleep = ["/bin/sleep", "/usr/bin/sleep"].into_iter().find(|p| Path::new(p).exists()).expect("sleep");
std::fs::copy(sleep, &java).unwrap();
std::fs::write(jdk.path().join("release"), release).unwrap();
let child = ChildGuard(Command::new(&java).arg("30").spawn().expect("spawn java"));
(jdk, child)
}
#[cfg(any(target_os = "linux", target_os = "macos"))]
#[test]
fn an_executable_named_java_is_hotspot_unless_its_jdk_is_openj9() {
let _serial = crate::test_serial::hold();
let (_jdk, hotspot) = sleep_as_java("IMPLEMENTOR=\"Eclipse Adoptium\"\nJAVA_VERSION=\"21.0.5\"\n");
assert!(is_hotspot(hotspot.0.id()));
let (_jdk, openj9) = sleep_as_java("IMPLEMENTOR=\"IBM Corporation\"\nJVM_VARIANT=\"Openj9\"\n");
let pid = openj9.0.id();
assert!(!is_hotspot(pid));
let result = ensure_listener(pid, Duration::from_millis(500));
assert!(matches!(result, Err(AttachError::NotAJvm)), "{result:?}");
}
#[test]
fn ensure_listener_refuses_a_non_jvm() {
let _serial = crate::test_serial::hold();
let sleep = spawn_sleep();
let pid = sleep.0.id();
let result = ensure_listener(pid, Duration::from_millis(500));
assert!(matches!(result, Err(AttachError::NotAJvm)), "{result:?}");
// SAFETY: signal 0 only checks that the pid exists.
assert_eq!(unsafe { libc::kill(pid as libc::pid_t, 0) }, 0, "the process must still be alive");
}
#[test]
fn foreign_socket_is_refused_without_a_signal() {
let _serial = crate::test_serial::hold();
use std::os::unix::{fs::PermissionsExt, net::UnixListener};
let dir = tempfile::tempdir().unwrap();
let socket = dir.path().join(".java_pid1");
let _listener = UnixListener::bind(&socket).unwrap();
std::fs::set_permissions(&socket, std::fs::Permissions::from_mode(0o666)).unwrap();
let sleep = spawn_sleep();
let pid = sleep.0.id();
let result = ensure_listener_at(&socket, pid, Duration::from_millis(500));
assert!(matches!(result, Err(AttachError::ForeignListener)), "{result:?}");
assert!(!temp_dir().join(format!(".attach_pid{pid}")).exists());
// SAFETY: signal 0 only checks that the pid exists.
assert_eq!(unsafe { libc::kill(pid as libc::pid_t, 0) }, 0, "the process must still be alive");
}
#[test]
fn perf_data_counts_only_when_written_since_the_process_started() {
let start = UNIX_EPOCH + Duration::from_secs(1_700_000_000);
assert!(!written_since_start(start - Duration::from_secs(60), Some(start)));
assert!(!written_since_start(start - Duration::from_secs(3), Some(start)));
assert!(written_since_start(start - Duration::from_secs(1), Some(start)));
assert!(written_since_start(start + Duration::from_secs(5), Some(start)));
assert!(!written_since_start(start + Duration::from_secs(5), None));
}
#[test]
fn our_own_start_time_is_known_and_recent() {
let start = process_start(std::process::id()).expect("start time of this process");
let age = SystemTime::now().duration_since(start).expect("started in the past");
assert!(age < Duration::from_secs(24 * 3600), "{age:?}");
}
#[test]
fn start_time_from_proc_files() {
let stat = "1234 (my (odd) proc) S 1 1234 1234 0 -1 4194560 100 0 0 0 1 2 0 0 20 0 1 0 5000 1000 50";
let system = "cpu 1 2 3
btime 1700000000
processes 9
";
let start = start_from_proc(stat, system, 100).unwrap();
assert_eq!(start, UNIX_EPOCH + Duration::from_secs(1_700_000_050));
assert_eq!(
start_from_proc(
stat,
"cpu 1 2 3
",
100
),
None
);
assert_eq!(start_from_proc("1234 (short) S 1", system, 100), None);
}
#[test]
fn process_group_pids_are_never_signalled() {
for pid in [0, u32::MAX, i32::MAX as u32 + 1] {
assert!(!is_hotspot(pid), "{pid}");
let result = ensure_listener(pid, Duration::from_millis(100));
assert!(matches!(result, Err(AttachError::NotAJvm)), "{pid}: {result:?}");
}
}
#[test]
fn trigger_file_is_private_and_removed_on_drop() {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join(".attach_pid1");
create_private(&path).unwrap();
assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600);
create_private(&path).expect("our own leftover is reused");
drop(Trigger(path.clone()));
assert!(!path.exists());
}
#[test]
fn trigger_file_refuses_a_planted_symlink() {
let dir = tempfile::tempdir().unwrap();
let target = dir.path().join("elsewhere");
let path = dir.path().join(".attach_pid1");
std::os::unix::fs::symlink(&target, &path).unwrap();
assert!(create_private(&path).is_err());
assert!(!target.exists());
}
}
+17 -2
View File
@@ -28,6 +28,10 @@ pub enum AttachError {
Unsupported,
#[error("the JVM has no attach listener")]
NoListener,
#[error("the process is not a HotSpot JVM")]
NotAJvm,
#[error("the JVM did not open its attach listener; it may run with -XX:+DisableAttachMechanism")]
ListenerDidNotStart,
#[error("the attach socket is not private to the current user")]
ForeignListener,
#[error("the attach listener refused the connection")]
@@ -98,14 +102,14 @@ pub fn jcmd(pid: u32, command_line: &str, timeout: Duration) -> Result<String, A
}
#[cfg(unix)]
fn socket_path(pid: u32) -> PathBuf {
pub(crate) fn socket_path(pid: u32) -> PathBuf {
temp_dir().join(format!(".java_pid{pid}"))
}
/// Same trust rule as the JDK's `VirtualMachineImpl`: only talk to a socket we own and
/// nobody else can reach, otherwise another user could answer in the JVM's place.
#[cfg(unix)]
fn check_socket(path: &Path) -> Result<(), AttachError> {
pub(crate) fn check_socket(path: &Path) -> Result<(), AttachError> {
// No symlink following: in a sticky, world-writable /tmp anyone can plant a symlink to a
// socket we own, pass this check, then re-point it before connect.
let meta = match std::fs::symlink_metadata(path) {
@@ -397,6 +401,7 @@ mod tests {
#[test]
fn sends_v1_jcmd_request_and_returns_body() {
let _serial = crate::test_serial::hold();
let dir = tempfile::tempdir().unwrap();
let (path, listener) = bind_private(dir.path());
let server = serve_once(listener, b"0\nhello\n");
@@ -407,6 +412,7 @@ mod tests {
#[test]
fn sends_v1_agent_properties_request_and_parses_body() {
let _serial = crate::test_serial::hold();
let dir = tempfile::tempdir().unwrap();
let (path, listener) = bind_private(dir.path());
let server = serve_once(listener, b"0\n#Mon\nsun.jdwp.listenerAddress=dt_socket\\:64390\n");
@@ -417,6 +423,7 @@ mod tests {
#[test]
fn nonzero_code_is_command_error() {
let _serial = crate::test_serial::hold();
let dir = tempfile::tempdir().unwrap();
let (path, listener) = bind_private(dir.path());
let _server = serve_once(listener, b"-1\njava.lang.IllegalArgumentException: Unknown diagnostic command");
@@ -431,6 +438,7 @@ mod tests {
#[test]
fn jcmd_times_out_when_listener_never_answers() {
let _serial = crate::test_serial::hold();
let dir = tempfile::tempdir().unwrap();
let (path, listener) = bind_private(dir.path());
let (release, hold) = mpsc::channel::<()>();
@@ -448,6 +456,7 @@ mod tests {
#[test]
fn stale_socket_maps_to_refused() {
let _serial = crate::test_serial::hold();
let dir = tempfile::tempdir().unwrap();
let (path, listener) = bind_private(dir.path());
drop(listener);
@@ -458,6 +467,7 @@ mod tests {
#[test]
fn rejects_socket_with_group_or_other_permissions() {
let _serial = crate::test_serial::hold();
let dir = tempfile::tempdir().unwrap();
let (path, _listener) = bind_private(dir.path());
fs::set_permissions(&path, fs::Permissions::from_mode(0o666)).unwrap();
@@ -468,6 +478,7 @@ mod tests {
#[test]
fn output_over_limit_is_too_large() {
let _serial = crate::test_serial::hold();
let (mut reader, mut writer) = UnixStream::pair().unwrap();
writer.write_all(b"0\n").unwrap();
writer.write_all(&[b'x'; 100]).unwrap();
@@ -479,6 +490,7 @@ mod tests {
#[test]
fn symlink_to_our_own_private_socket_is_rejected() {
let _serial = crate::test_serial::hold();
let dir = tempfile::tempdir().unwrap();
let (target, _listener) = bind_private(dir.path());
let link = dir.path().join(".java_pid2");
@@ -491,6 +503,7 @@ mod tests {
#[test]
fn peer_uid_check_passes_for_our_own_listener() {
let _serial = crate::test_serial::hold();
let dir = tempfile::tempdir().unwrap();
let (path, listener) = bind_private(dir.path());
let stream = connect_before(&path, Instant::now() + Duration::from_secs(1)).unwrap();
@@ -500,6 +513,7 @@ mod tests {
#[test]
fn connect_before_maps_missing_socket_to_no_listener() {
let _serial = crate::test_serial::hold();
let dir = tempfile::tempdir().unwrap();
let deadline = Instant::now() + Duration::from_secs(1);
let missing = connect_before(&dir.path().join("nope"), deadline);
@@ -510,6 +524,7 @@ mod tests {
/// connect must give up within its deadline instead of hanging.
#[test]
fn connect_before_gives_up_on_a_full_backlog() {
let _serial = crate::test_serial::hold();
let dir = tempfile::tempdir().unwrap();
let (path, _listener) = bind_private(dir.path());
let mut held = Vec::new();
+10
View File
@@ -0,0 +1,10 @@
use std::sync::{Mutex, MutexGuard};
static SERIAL: Mutex<()> = Mutex::new(());
/// Held for a whole test that binds or accepts on a socket or spawns a process. macOS sets
/// close-on-exec on a new socket only after `socket()` returns, so a child spawned meanwhile by
/// another test inherits the listening fd and keeps a dropped listener connectable.
pub fn hold() -> MutexGuard<'static, ()> {
SERIAL.lock().unwrap_or_else(|poisoned| poisoned.into_inner())
}
+281
View File
@@ -0,0 +1,281 @@
use std::collections::{HashMap, HashSet, VecDeque};
use std::process::Command;
use std::time::Duration;
use crate::listener::is_hotspot;
use crate::socket::{AttachError, jcmd};
/// Default budget for `thread_print`; a dump of a healthy JVM takes milliseconds, so this only
/// bounds a JVM stuck at a safepoint.
pub const THREAD_DUMP_TIMEOUT: Duration = Duration::from_secs(10);
/// System property the IDE adds to a run's JVM so it can be found even when the build tool
/// forks it outside the run's process tree (a Gradle daemon).
pub const RUN_TOKEN_PROPERTY: &str = "-Dopenidea.run.token=";
/// Gradle's own JVMs: the client that waits for the build, the daemon that runs it, and the
/// workers and Kotlin compile daemon it forks (beside the application under `--no-daemon`).
/// None is the application, even when it is the only JVM under the run's root.
const GRADLE_JVM_MARKERS: [&str; 5] = [
"org.gradle.wrapper.GradleWrapperMain",
"org.gradle.launcher.GradleMain",
"org.gradle.launcher.daemon",
"org.gradle.process.internal.worker.GradleWorkerMain",
"org.jetbrains.kotlin.daemon.KotlinCompileDaemon",
];
/// `Thread.print -l` also lists the owned `java.util.concurrent` locks, which deadlock
/// reports need.
pub fn thread_print(pid: u32, timeout: Duration) -> Result<String, AttachError> {
jcmd(pid, "Thread.print -l", timeout)
}
#[derive(Debug, Clone, PartialEq)]
pub struct ProcEntry {
pub pid: u32,
pub ppid: u32,
/// The full argv joined by spaces, as `ps` prints it.
pub command: String,
}
/// Every process of the machine; empty when `ps` is unavailable.
pub fn process_table() -> Vec<ProcEntry> {
let Ok(out) = Command::new("ps").args(["-A", "-o", "pid=,ppid=,command="]).output() else {
return Vec::new();
};
String::from_utf8_lossy(&out.stdout).lines().filter_map(parse_ps_line).collect()
}
fn parse_ps_line(line: &str) -> Option<ProcEntry> {
let (pid, rest) = line.trim_start().split_once(char::is_whitespace)?;
let (ppid, command) = rest.trim_start().split_once(char::is_whitespace)?;
Some(ProcEntry { pid: pid.parse().ok()?, ppid: ppid.parse().ok()?, command: command.trim().to_string() })
}
/// The JVM that runs a run configuration: the deepest HotSpot JVM below `root` that is not
/// Gradle's own (a Maven `spring-boot:run` forks the application under the Maven JVM), else
/// the one carrying `token` (a Gradle daemon forks it outside the run's tree, which then holds
/// only the Gradle client). Ties go to the highest pid.
pub fn select_run_jvm(
table: &[ProcEntry],
root: u32,
token: Option<&str>,
is_hotspot: impl Fn(u32) -> bool,
) -> Option<u32> {
// The tree first: a token is only as unique as the configuration and project it names.
deepest_jvm_in_tree(table, root, &is_hotspot).or_else(|| {
let wanted = format!("{RUN_TOKEN_PROPERTY}{}", token.filter(|token| !token.is_empty())?);
table
.iter()
// The Gradle client carries the token too: a delegated run passes it on its command line.
.filter(|entry| {
entry.command.split_whitespace().any(|arg| arg == wanted)
&& !is_gradle_jvm(&entry.command)
&& is_hotspot(entry.pid)
})
.map(|entry| entry.pid)
.max()
})
}
/// Confirmed HotSpot (`is_hotspot`) and, by its command line, not one of Gradle's own JVMs.
pub fn is_application_jvm(pid: u32) -> bool {
is_hotspot(pid) && !command_line(pid).is_some_and(|command| is_gradle_jvm(&command))
}
fn command_line(pid: u32) -> Option<String> {
let out = Command::new("ps").args(["-o", "command=", "-p", &pid.to_string()]).output().ok()?;
out.status.success().then(|| String::from_utf8_lossy(&out.stdout).trim().to_owned())
}
fn is_gradle_jvm(command: &str) -> bool {
GRADLE_JVM_MARKERS.iter().any(|marker| command.contains(marker))
}
fn deepest_jvm_in_tree(table: &[ProcEntry], root: u32, is_hotspot: &dyn Fn(u32) -> bool) -> Option<u32> {
let mut children: HashMap<u32, Vec<&ProcEntry>> = HashMap::new();
for entry in table {
children.entry(entry.ppid).or_default().push(entry);
}
let by_pid: HashMap<u32, &ProcEntry> = table.iter().map(|entry| (entry.pid, entry)).collect();
let mut seen = HashSet::from([root]);
let mut queue = VecDeque::from([(root, 0usize)]);
let mut best: Option<(usize, u32)> = None;
while let Some((pid, depth)) = queue.pop_front() {
let is_app_jvm = by_pid.get(&pid).is_some_and(|entry| !is_gradle_jvm(&entry.command)) && is_hotspot(pid);
if is_app_jvm && best.is_none_or(|found| (depth, pid) > found) {
best = Some((depth, pid));
}
for child in children.get(&pid).into_iter().flatten() {
if seen.insert(child.pid) {
queue.push_back((child.pid, depth + 1));
}
}
}
best.map(|(_, pid)| pid)
}
#[cfg(test)]
mod tests {
use super::*;
fn entry(pid: u32, ppid: u32, command: &str) -> ProcEntry {
ProcEntry { pid, ppid, command: command.to_string() }
}
fn any_pid(_: u32) -> bool {
true
}
/// The shell at pid 10 is not a JVM, as the real `is_hotspot` would say.
fn not_the_shell(pid: u32) -> bool {
pid != 10
}
fn gradle_run() -> Vec<ProcEntry> {
vec![
entry(10, 1, "/bin/zsh"),
entry(11, 10, "/jdk/bin/java -classpath wrapper.jar org.gradle.wrapper.GradleWrapperMain run"),
entry(50, 40, "/jdk/bin/java -Dopenidea.run.token=cfg-1 -cp app Main"),
]
}
#[test]
fn select_falls_back_to_the_token_when_the_tree_holds_only_gradle() {
let table = gradle_run();
assert_eq!(select_run_jvm(&table, 10, Some("cfg-1"), not_the_shell), Some(50));
assert_eq!(select_run_jvm(&table, 10, Some("cfg-2"), not_the_shell), None);
}
#[test]
fn select_skips_the_gradle_client_that_carries_the_token() {
let client = |pid| {
entry(
pid,
10,
"/jdk/bin/java -Dopenidea.run.token=cfg-1 -classpath wrapper.jar org.gradle.wrapper.GradleWrapperMain run",
)
};
let app = entry(50, 40, "/jdk/bin/java -Dopenidea.run.token=cfg-1 -cp app Main");
for client_pid in [11, 99] {
let table = vec![entry(10, 1, "/bin/zsh"), client(client_pid), app.clone()];
assert_eq!(select_run_jvm(&table, 10, Some("cfg-1"), not_the_shell), Some(50), "client {client_pid}");
}
// Only the client carries it: the tree rules apply, which skip the client too.
let table = vec![entry(10, 1, "/bin/zsh"), client(11), entry(12, 11, "/jdk/bin/java -cp app Main")];
assert_eq!(select_run_jvm(&table, 10, Some("cfg-1"), not_the_shell), Some(12));
let alone = vec![entry(10, 1, "/bin/zsh"), client(11)];
assert_eq!(select_run_jvm(&alone, 10, Some("cfg-1"), not_the_shell), None);
let launcher = entry(13, 10, "java -Dopenidea.run.token=cfg-1 org.gradle.launcher.GradleMain run");
assert_eq!(select_run_jvm(&[entry(10, 1, "sh"), launcher], 10, Some("cfg-1"), not_the_shell), None);
}
#[test]
fn select_prefers_the_run_tree_over_a_token_elsewhere() {
// Another worktree's delegated JVM carries the same token as this plain run.
let table = vec![
entry(10, 1, "/bin/zsh"),
entry(11, 10, "/jdk/bin/java -Dopenidea.run.token=cfg-1 -cp app Main"),
entry(50, 40, "/jdk/bin/java -Dopenidea.run.token=cfg-1 -cp app Main"),
];
assert_eq!(select_run_jvm(&table, 10, Some("cfg-1"), not_the_shell), Some(11));
}
#[test]
fn select_picks_deepest_jvm_in_tree() {
let table = vec![
entry(10, 1, "/bin/zsh"),
entry(11, 10, "/jdk/bin/java -classpath maven.jar org.codehaus.plexus.classworlds.launcher.Launcher"),
entry(12, 11, "/jdk/bin/java -cp app Main"),
];
assert_eq!(select_run_jvm(&table, 10, None, not_the_shell), Some(12));
}
#[test]
fn select_ignores_token_substring() {
let table = vec![entry(50, 1, "java -Dopenidea.run.token=cfg-10 -cp app Main")];
assert_eq!(select_run_jvm(&table, 10, Some("cfg-1"), any_pid), None);
assert_eq!(select_run_jvm(&table, 10, Some("cfg-10"), any_pid), Some(50));
}
#[test]
fn select_none_when_tree_has_no_jvm() {
let table = vec![entry(10, 1, "/bin/zsh"), entry(11, 10, "/bin/sleep 5"), entry(12, 1, "java -cp app Main")];
assert_eq!(select_run_jvm(&table, 10, None, |pid| pid == 12), None);
}
#[test]
fn select_treats_an_empty_token_as_no_token() {
// "-Dopenidea.run.token=" with nothing after it must not tag every such process.
let table =
vec![entry(50, 1, "java -Dopenidea.run.token= -cp app Main"), entry(10, 1, "sh"), entry(11, 10, "java a")];
assert_eq!(select_run_jvm(&table, 10, Some(""), not_the_shell), Some(11));
}
#[test]
fn select_takes_the_highest_pid_among_equally_deep_jvms() {
let table = vec![entry(10, 1, "sh"), entry(11, 10, "java a"), entry(12, 10, "java b")];
assert_eq!(select_run_jvm(&table, 10, None, not_the_shell), Some(12));
let tagged = vec![entry(5, 1, "java -Dopenidea.run.token=t"), entry(7, 1, "java -Dopenidea.run.token=t")];
assert_eq!(select_run_jvm(&tagged, 10, Some("t"), any_pid), Some(7));
}
#[test]
fn select_skips_tagged_processes_that_are_not_a_hotspot_jvm() {
let table = vec![entry(50, 1, "native -Dopenidea.run.token=t"), entry(10, 1, "sh"), entry(11, 10, "java a")];
assert_eq!(select_run_jvm(&table, 10, Some("t"), |pid| pid == 11), Some(11));
}
#[test]
fn select_includes_the_root_itself() {
let table = vec![entry(10, 1, "java -cp app Main")];
assert_eq!(select_run_jvm(&table, 10, None, any_pid), Some(10));
}
#[test]
fn select_survives_a_parent_cycle() {
let table = vec![entry(10, 11, "sh"), entry(11, 10, "java a")];
assert_eq!(select_run_jvm(&table, 10, None, not_the_shell), Some(11));
}
#[test]
fn select_skips_gradle_workers_and_the_kotlin_daemon() {
// `--no-daemon`: the build's helper JVMs sit beside the application in the run's tree.
let worker = "/jdk/bin/java -cp gradle-worker.jar worker.org.gradle.process.internal.worker.GradleWorkerMain 'Gradle Worker Daemon 1'";
let kotlin = "/jdk/bin/java -cp kotlin-compiler-embeddable.jar org.jetbrains.kotlin.daemon.KotlinCompileDaemon --daemon-runFilesPath x";
let build =
entry(11, 10, "/jdk/bin/java -cp gradle-launcher.jar org.gradle.launcher.GradleMain --no-daemon run");
let table = vec![
entry(10, 1, "/bin/zsh"),
build.clone(),
entry(12, 11, "/jdk/bin/java -cp app Main"),
entry(20, 11, worker),
entry(21, 11, kotlin),
];
assert_eq!(select_run_jvm(&table, 10, None, not_the_shell), Some(12));
let helpers = vec![entry(10, 1, "/bin/zsh"), build, entry(20, 11, worker), entry(21, 11, kotlin)];
assert_eq!(select_run_jvm(&helpers, 10, None, not_the_shell), None);
}
#[cfg(unix)]
#[test]
fn command_line_of_a_process_and_a_sleep_is_no_application_jvm() {
let mut sleep = Command::new("sleep").arg("30").spawn().expect("spawn sleep");
let pid = sleep.id();
let (command, application) = (command_line(pid), is_application_jvm(pid));
let _ = sleep.kill();
let _ = sleep.wait();
assert_eq!(command.as_deref(), Some("sleep 30"));
assert!(!application);
assert_eq!(command_line(pid), None, "an ended process has no command line");
}
#[test]
fn parses_ps_lines_with_arguments_and_padding() {
let parsed = parse_ps_line(" 123 45 /jdk/bin/java -Dk=v -cp a b").unwrap();
assert_eq!(parsed, entry(123, 45, "/jdk/bin/java -Dk=v -cp a b"));
assert_eq!(parse_ps_line(" PID PPID COMMAND"), None);
assert_eq!(parse_ps_line(" 7 1"), None);
}
}
+82 -6
View File
@@ -8,11 +8,31 @@ use std::sync::mpsc;
use std::time::{Duration, Instant};
use ide_jvm_attach::{
AttachError, HeapDumpReply, agent_properties, find_jvm_by_jdwp_port, has_listener, heap_dump, heap_dump_command,
histogram_safe_while_suspended, java_version_of, jcmd, jdwp_port, parse_class_histogram, parse_heap_dump_reply,
parse_release, vm_flags,
AttachError, HeapDumpReply, LISTENER_START_TIMEOUT, THREAD_DUMP_TIMEOUT, agent_properties, ensure_listener,
find_jvm_by_jdwp_port, has_listener, heap_dump, heap_dump_command, histogram_safe_while_suspended, is_hotspot,
java_version_of, jcmd, jdwp_port, parse_class_histogram, parse_heap_dump_reply, parse_release, process_table,
select_run_jvm, temp_dir, thread_print, vm_flags,
};
/// Two threads that each hold one monitor and wait for the other's after 200 ms.
const DEADLOCK_JAVA: &str = r#"
public class Deadlock {
static final Object A = new Object(), B = new Object();
static void sleep(long ms) {
try { Thread.sleep(ms); } catch (InterruptedException e) { throw new RuntimeException(e); }
}
public static void main(String[] args) {
new Thread(() -> { synchronized (A) { sleep(200); synchronized (B) { } } }, "sync-1").start();
new Thread(() -> { synchronized (B) { sleep(200); synchronized (A) { } } }, "sync-2").start();
System.out.println("READY");
System.out.flush();
sleep(60_000);
}
}
"#;
const MAIN_JAVA: &str = r#"
import java.util.ArrayList;
import java.util.List;
@@ -168,15 +188,19 @@ fn finds_a_real_jvm_by_its_jdwp_port() {
/// Compiles `MAIN_JAVA` with the `javac` next to `java`, since JDK 8 has no source launcher.
fn launch_main(java: &Path, dir: &Path, jvm_args: &[&str]) -> JvmGuard {
let source = dir.join("Main.java");
std::fs::write(&source, MAIN_JAVA).unwrap();
launch_class(java, dir, "Main", MAIN_JAVA, jvm_args)
}
fn launch_class(java: &Path, dir: &Path, class: &str, source_text: &str, jvm_args: &[&str]) -> JvmGuard {
let source = dir.join(format!("{class}.java"));
std::fs::write(&source, source_text).unwrap();
let status = Command::new(java.with_file_name("javac")).arg("-d").arg(dir).arg(&source).status().expect("javac");
assert!(status.success(), "javac failed");
let child = Command::new(java)
.args(jvm_args)
.arg("-cp")
.arg(dir)
.arg("Main")
.arg(class)
.current_dir(dir)
.stdout(Stdio::piped())
.stderr(Stdio::piped())
@@ -310,3 +334,55 @@ fn dumps_while_suspended() {
assert!(guard.0.try_wait().unwrap().is_none(), "the JVM exited after resume");
vm_flags(pid, Duration::from_secs(10)).expect("the attach listener answers after resume");
}
#[test]
#[ignore = "needs a real JDK >= 8: set OPENIDEA_TEST_JAVA to its bin/java"]
fn ensure_listener_starts_a_listener_on_demand() {
let Some(java) = std::env::var_os("OPENIDEA_TEST_JAVA").map(PathBuf::from) else {
eprintln!("OPENIDEA_TEST_JAVA is not set; skipping");
return;
};
let dir = tempfile::tempdir().unwrap();
let mut guard = launch_main(&java, dir.path(), &[]);
let pid = guard.0.id();
wait_for_ready(&output_lines(&mut guard.0));
assert!(!has_listener(pid), "the JVM opened its listener without being asked");
assert!(is_hotspot(pid));
let started = Instant::now();
ensure_listener(pid, LISTENER_START_TIMEOUT).unwrap();
eprintln!("on-demand listener for pid {pid} in {:?}", started.elapsed());
assert!(has_listener(pid));
jcmd(pid, "VM.version", Duration::from_secs(10)).expect("the new listener answers");
let trigger = format!(".attach_pid{pid}");
for parent in [temp_dir(), dir.path().to_path_buf()] {
assert!(!parent.join(&trigger).exists(), "trigger file left in {parent:?}");
}
ensure_listener(pid, LISTENER_START_TIMEOUT).expect("an open listener is accepted as is");
}
#[test]
#[ignore = "needs a real JDK >= 8: set OPENIDEA_TEST_JAVA to its bin/java"]
fn thread_print_reports_a_deadlock() {
let Some(java) = std::env::var_os("OPENIDEA_TEST_JAVA").map(PathBuf::from) else {
eprintln!("OPENIDEA_TEST_JAVA is not set; skipping");
return;
};
let dir = tempfile::tempdir().unwrap();
let mut guard = launch_class(&java, dir.path(), "Deadlock", DEADLOCK_JAVA, &["-XX:+StartAttachListener"]);
let pid = guard.0.id();
wait_for_ready(&output_lines(&mut guard.0));
wait_for_listener(pid);
// The threads take their first monitor at once and the second after 200 ms.
std::thread::sleep(Duration::from_secs(1));
let dump = thread_print(pid, THREAD_DUMP_TIMEOUT).unwrap();
assert!(dump.contains("Found one Java-level deadlock"), "{dump}");
assert!(dump.contains("sync-1") && dump.contains("sync-2"), "{dump}");
// The run's JVM is found through the real process table, as the dump action does.
let table = process_table();
assert!(table.iter().any(|entry| entry.pid == pid && entry.command.contains("Deadlock")));
assert_eq!(select_run_jvm(&table, pid, None, is_hotspot), Some(pid));
}
+20 -1
View File
@@ -12,6 +12,7 @@ const BUILTIN: &[(&str, &str)] = &[
("arduino", include_str!("../../../languages/arduino.toml")),
("asciidoc", include_str!("../../../languages/asciidoc.toml")),
("astro", include_str!("../../../languages/astro.toml")),
("axaml", include_str!("../../../languages/axaml.toml")),
("bat", include_str!("../../../languages/bat.toml")),
("c", include_str!("../../../languages/c.toml")),
("clojure", include_str!("../../../languages/clojure.toml")),
@@ -885,10 +886,16 @@ mod tests {
let cfg = reg.get(&LanguageId::new("php")).unwrap();
let names: Vec<&str> = cfg.language_servers.iter().map(|s| s.name.as_str()).collect();
// After the fallback: hover, rename and symbols stay with Intelephense.
assert_eq!(names, ["intelephense", "phpactor", "phoxite", "laravel-lsp"]);
assert_eq!(names, ["intelephense", "phpactor", "phoxite", "devsense-php-ls", "laravel-lsp"]);
// Phoxite answers the Laravel strings itself.
let phoxite = cfg.language_servers.iter().find(|s| s.name == "phoxite").unwrap();
assert!(phoxite.fallback && phoxite.replaces == ["laravel-lsp"]);
// DEVSENSE runs without Node or PHP of its own (the npm launcher needs Node) and
// answers the Laravel strings itself. https://docs.devsense.com/other/lsp/docs/
let devsense = cfg.language_servers.iter().find(|s| s.name == "devsense-php-ls").unwrap();
assert!(devsense.fallback && devsense.replaces == ["laravel-lsp"]);
assert_eq!(devsense.command.as_str(), "devsense-php-ls");
assert_eq!(devsense.install_hint.as_deref(), Some("npm i -g devsense-php-ls"));
let lsp = cfg.language_servers.iter().find(|s| s.name == "laravel-lsp").unwrap();
assert_eq!(lsp.command.as_str(), "laravel-lsp");
// Its `lsp` command takes no options and speaks over stdio; `--stdio` stops it at startup.
@@ -1271,6 +1278,8 @@ mod tests {
("Cargo.toml", "toml"),
("Cargo.lock", "toml"),
("pom.xml", "xml"),
("Views/MainWindow.axaml", "axaml"),
("MainWindow.xaml", "xml"),
("README.md", "markdown"),
("Dockerfile", "dockerfile"),
("Dockerfile.dev", "dockerfile"),
@@ -1308,6 +1317,16 @@ mod tests {
}
}
#[test]
fn avalonia_xaml_is_xml_with_its_own_server() {
let reg = reg();
let axaml = reg.get(&LanguageId::new("axaml")).unwrap();
assert_eq!(axaml.tree_sitter.as_deref(), Some("xml"));
assert_eq!(axaml.ui_mode.as_deref(), Some("XML"));
let servers: Vec<_> = axaml.language_servers.iter().map(|s| (s.name.as_str(), s.fallback)).collect();
assert_eq!(servers, [("axsg-lsp", false), ("lemminx", true)]);
}
#[test]
fn gdscript_definition() {
let reg = reg();
+71 -1
View File
@@ -60,6 +60,11 @@ pub struct PythonMethodFacts {
/// Decorated with `override` from `typing` / `typing_extensions`.
pub override_decorated: bool,
pub body: MethodBody,
/// For 'Method may be static': the receiver parameter up to the next parameter (what
/// Make method static deletes), when the method is undecorated and not a dunder, and its
/// body does more than `pass`, `...`, a docstring or one `raise` without ever naming the
/// receiver, `super` or `__class__`.
pub unused_receiver: Option<crate::Range>,
}
/// What a method body does, for the shapes a check can decide without guessing.
@@ -209,18 +214,65 @@ fn methods_of(class: Node, text: &str, idx: &LineIndex, imports: &ImportBindings
}
let decorators = decorators_of(method, text);
out.push(PythonMethodFacts {
name,
selection: idx.range(name_node.start_byte(), name_node.end_byte()),
definition_line: member.start_position().row as u32,
params: parameters_of(method, text),
abstract_method: decorators.iter().any(|d| last_segment(d) == "abstractmethod"),
override_decorated: decorators.iter().any(|d| imports.is_typing_override(d)),
body: body_of(method, text),
unused_receiver: if decorators.is_empty() && !is_dunder(&name) {
unused_receiver(method, text).map(|(start, end)| idx.range(start, end))
} else {
None
},
name,
});
}
out
}
fn is_dunder(name: &str) -> bool {
name.len() > 4 && name.starts_with("__") && name.ends_with("__")
}
/// The bytes Make method static deletes: the receiver up to the next parameter (or up to the
/// closing parenthesis), when the body does real work without naming the receiver.
fn unused_receiver(function: Node, text: &str) -> Option<(usize, usize)> {
let body = function.child_by_field_name("body")?;
let statements: Vec<Node> = statements_of(body).into_iter().filter(|s| !is_string(*s)).collect();
// Stubs and placeholders (`pass`, `...`, `raise NotImplementedError`) are meant to be overridden.
if statements.iter().all(|s| is_noop(*s))
|| matches!(statements.as_slice(), [only] if only.kind() == "raise_statement")
{
return None;
}
let params = function.child_by_field_name("parameters")?;
let mut cursor = params.walk();
let mut named = params.named_children(&mut cursor);
let receiver = named.next()?;
let name = match receiver.kind() {
"identifier" => receiver,
"typed_parameter" => receiver.named_child(0).filter(|n| n.kind() == "identifier")?,
_ => return None,
};
let name = &text[name.byte_range()];
let next = named.next();
if next.is_some_and(|n| matches!(n.kind(), "positional_separator" | "keyword_separator")) {
return None;
}
let mut used = false;
let mut cursor = body.walk();
visit(&mut cursor, &mut |node| {
used |= node.kind() == "identifier"
&& matches!(&text[node.byte_range()], n if n == name || n == "super" || n == "__class__");
});
if used {
return None;
}
let end = next.map_or(params.end_byte() - 1, |n| n.start_byte());
Some((receiver.start_byte(), end))
}
/// The parameter names of a `function_definition`, or `None` when the signature contains a
/// form whose forwarding cannot be compared without guessing.
fn parameters_of(function: Node, text: &str) -> Option<Vec<String>> {
@@ -578,4 +630,22 @@ mod tests {
let f = facts("@dataclass\nclass C:\n x: int\n");
assert_eq!(f.classes[0].definition_line, 0);
}
#[test]
fn unused_receiver_is_the_parameter_make_static_deletes() {
let src = "class C:\n def helper(self, x):\n return x * 2\n\n def only(self):\n print(1)\n\n def typed(self: 'C',) -> int:\n return 1\n\n def uses(self):\n return self.x\n\n def nested(self):\n return lambda: self\n\n def sup(self):\n return super().sup()\n\n def stub(self):\n raise NotImplementedError\n\n def empty(self):\n \"\"\"Doc.\"\"\"\n\n @property\n def prop(self):\n return 1\n\n def __repr__(self):\n return 'C'\n\n def positional(self, /, x):\n return x\n";
let f = facts(src);
let deleted = |name: &str| {
method(&f, "C", name).unused_receiver.map(|r| {
let line = src.lines().nth(r.start.line as usize).unwrap();
line[r.start.col as usize..r.end.col as usize].to_string()
})
};
assert_eq!(deleted("helper").as_deref(), Some("self, "));
assert_eq!(deleted("only").as_deref(), Some("self"));
assert_eq!(deleted("typed").as_deref(), Some("self: 'C',"));
for name in ["uses", "nested", "sup", "stub", "empty", "prop", "__repr__", "positional"] {
assert_eq!(deleted(name), None, "{name}");
}
}
}
+5
View File
@@ -645,6 +645,11 @@ impl Handler for ClientHandler {
{
self.show_message(&mgr, &json!({ "type": 1, "message": text.lines().next().unwrap_or(text) }));
}
if self.server.name == "jdtls"
&& let Some(failure) = crate::jdtls::gradle_sync_failure(text)
{
mgr.report_gradle_sync_failure(failure);
}
if self.server.name == "jdtls"
&& params.get("type").and_then(Value::as_u64) == Some(1)
&& let Some(failure) = crate::jdtls::logged_build_plan_failure(text)
+96
View File
@@ -1293,7 +1293,66 @@ pub(crate) fn logged_build_plan_failure(message: &str) -> Option<(String, String
Some((reason, body))
}
/// How long a failed Gradle sync waits for jdtls' incompatible-JDK message (sent a few ms later).
const GRADLE_JDK_MESSAGE_WAIT: std::time::Duration = std::time::Duration::from_millis(1500);
/// Buildship's log when a Gradle sync fails ("Synchronize project app failed due to an error
/// connecting to the Gradle build.", then the stack trace), as (project, notification body).
/// jdtls logs it below error level, so without this the import fails silently: every Java file
/// shows unresolved types and nothing says why. The deepest `Caused by` is the build's own error.
pub(crate) fn gradle_sync_failure(message: &str) -> Option<(String, String)> {
let first = message.lines().next()?;
let (_, rest) = first.split_once("Synchronize project ")?;
let (project, _) = rest.split_once(" failed due to ")?;
let cause = message
.lines()
.rev()
.find_map(|l| l.trim_start().strip_prefix("Caused by: "))
.or_else(|| message.lines().nth(1))
.map(|l| match l.split_once(": ") {
// `org.gradle.Some.Exception: what happened` → what happened
Some((class, text)) if class.contains('.') && !class.contains(char::is_whitespace) => text,
_ => l,
})
.map(str::trim)
.filter(|c| !c.is_empty() && !c.starts_with("at "));
const MAX: usize = 500;
let cause = cause.map(|c| match c.char_indices().nth(MAX) {
Some((end, _)) => format!("{}…", &c[..end]),
None => c.to_owned(),
});
let body = match cause {
Some(cause) => format!(
"Gradle could not sync {project}. Java code insight may not work until the build syncs. Fix the build, then reload the Gradle project. Cause: {cause}"
),
None => format!(
"Gradle could not sync {project}. Java code insight may not work until the build syncs. Fix the build, then reload the Gradle project."
),
};
Some((project.to_owned(), body))
}
impl LspManager {
/// A failed Gradle sync of `project` (see [`gradle_sync_failure`]), shown once. jdtls follows
/// a sync that failed on an incompatible JDK with "Can't use Java … to import Gradle project
/// …", which has its own notification with the fix; wait for it so that one is the only one.
pub(crate) fn report_gradle_sync_failure(&self, (project, body): (String, String)) {
let Some(me) = self.me.upgrade() else { return };
self.runtime.spawn(async move {
tokio::time::sleep(GRADLE_JDK_MESSAGE_WAIT).await;
if me.shown_message_containing(SERVER, &format!(" to import Gradle project {project}")) {
return;
}
if me.first_message(SERVER, &body) {
me.sink().emit(ide_core::IdeEvent::Notify {
level: ide_core::event::NotifyLevel::Error,
title: "Gradle project sync failed".into(),
body: Some(body),
});
}
});
}
/// JDT LS aborted its import with `message`: when reserved Windows device names
/// below `root` are the cause, say which (once). The walk runs off the RPC thread.
pub(crate) fn report_import_failure(&self, root: PathBuf, message: String) {
@@ -1402,6 +1461,43 @@ mod tests {
);
}
#[test]
fn a_failed_gradle_sync_is_explained_with_its_root_cause() {
let log = "Nov 25, 2026, 2:00:14 PM Synchronize project repro failed due to an error connecting to the Gradle build.\n\
org.gradle.tooling.BuildActionFailureException: The supplied phased action failed with an exception.\n\
\tat org.gradle.tooling.internal.consumer.connection.PhasedActionAwareConsumerConnection.doRun(PhasedActionAwareConsumerConnection.java:58)\n\
Caused by: org.gradle.api.plugins.InvalidPluginException: An exception occurred applying plugin request [id: 'war']\n\
\tat x\n\
Caused by: java.lang.IllegalArgumentException: Unable to determine constructor argument #2: missing parameter of type IdeArtifactRegistry, or no service of type IdeArtifactRegistry.\n\
\tat org.gradle.groovy.scripts.DefaultScript.apply(DefaultScript.java:133)\n\
\t... 12 more";
let (project, body) = gradle_sync_failure(log).unwrap();
assert_eq!(project, "repro");
assert_eq!(
body,
"Gradle could not sync repro. Java code insight may not work until the build syncs. Fix the build, then reload the Gradle project. \
Cause: Unable to determine constructor argument #2: missing parameter of type IdeArtifactRegistry, or no service of type IdeArtifactRegistry."
);
// Without a `Caused by`, the logged exception's own message.
let (_, body) = gradle_sync_failure(
"Synchronize project app failed due to an error in the referenced Gradle build.\n\
org.gradle.tooling.BuildException: Could not run build action.\n\tat y",
)
.unwrap();
assert!(body.ends_with(" Cause: Could not run build action."), "{body}");
// A cause that is a plain sentence keeps its colons.
let (_, body) = gradle_sync_failure(
"Synchronize project app failed due to an error connecting to the Gradle build.\nx\nCaused by: Build failed: see above",
)
.unwrap();
assert!(body.ends_with(" Cause: Build failed: see above"), "{body}");
assert_eq!(gradle_sync_failure("Synchronizing projects\nCaused by: x.Y: z"), None);
assert_eq!(gradle_sync_failure("Failed to configure some Maven project(s)"), None);
}
#[test]
fn source_settings_preserve_java_defaults_and_library_resolution() {
let mut cfg = java_config();
+25
View File
@@ -1218,6 +1218,11 @@ impl LspManager {
self.shown_messages.lock().insert((server.to_owned(), text.to_owned()))
}
/// Whether `server` has shown a message containing `needle` in this project.
pub(crate) fn shown_message_containing(&self, server: &str, needle: &str) -> bool {
self.shown_messages.lock().iter().any(|(s, text)| s == server && text.contains(needle))
}
pub(crate) fn apply_edit_hook(&self) -> Option<ApplyEditHook> {
self.apply_edit_hook.read().clone()
}
@@ -2630,6 +2635,26 @@ impl LspManager {
Ok(())
}
/// Where other files import `doc`'s file (VS Code's Find File References): tsserver's
/// `fileReferences` through vtsls' `typescript.tsserverRequest`, which also answers for a
/// `.vue` component with the Vue TypeScript plugin (vtsls' own command refuses non-TS
/// documents). Unavailable when no TypeScript server serves the document.
pub async fn file_references(&self, doc: DocId, cancel: CancellationToken) -> IdeResult<Vec<Location>> {
let snap = self.snapshot(doc)?;
let targets =
self.ready_targets(&snap.servers, |c| c.commands().iter().any(|c| c == ts_file_moves::COMMAND)).await;
let t = targets
.iter()
.find(|t| t.server.config.tsserver_project)
.ok_or_else(|| IdeError::unavailable("No language server finds file references"))?;
let params = json!({
"command": ts_file_moves::COMMAND,
"arguments": ["fileReferences", { "file": snap.path }],
});
let result: Value = self.call(t, "workspace/executeCommand", params, Some(&cancel), LONG_TIMEOUT).await?;
Ok(ts_file_moves::file_references(&result))
}
/// Whether a server of `doc` (`server`, when given) provides the command `name`. Code actions
/// can carry commands other editors' extensions run themselves after the edit (vtsls'
/// `_typescript.didOrganizeImports`): no server provides those.
+37
View File
@@ -63,10 +63,47 @@ pub(crate) fn edit(result: &Value) -> WorkspaceEdit {
}
}
#[derive(Deserialize)]
struct FileReference {
file: PathBuf,
start: Location,
end: Location,
}
#[derive(Deserialize)]
struct FileReferences {
refs: Vec<FileReference>,
}
/// tsserver's `fileReferences` answer (the command's `body`; 1-based lines and UTF-16 offsets): the imports of a file.
pub(crate) fn file_references(result: &Value) -> Vec<ide_core::Location> {
let body = result.get("body").unwrap_or(result);
let Ok(found) = serde_json::from_value::<FileReferences>(body.clone()) else { return Vec::new() };
let pos = |l: &Location| Pos::new(l.line.saturating_sub(1), l.offset.saturating_sub(1));
found
.refs
.into_iter()
.map(|r| ide_core::Location { path: r.file.into(), range: Range::new(pos(&r.start), pos(&r.end)), uri: None })
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn converts_tsserver_file_references() {
let result = json!({ "success": true, "body": { "symbolName": "\"./Hello.vue\"", "refs": [
{ "file": "/p/src/App.vue", "start": { "line": 2, "offset": 19 }, "end": { "line": 2, "offset": 41 },
"lineText": "import Hello from './components/Hello.vue'", "isWriteAccess": false }
] } });
let refs = file_references(&result);
assert_eq!(refs.len(), 1);
assert_eq!(refs[0].path, ide_core::IpcPath::from(PathBuf::from("/p/src/App.vue")));
assert_eq!(refs[0].range, Range::new(Pos::new(1, 18), Pos::new(1, 40)));
assert!(file_references(&json!({ "success": false })).is_empty());
}
#[test]
fn converts_tsserver_file_code_edits() {
let result = json!({ "success": true, "body": [
+52
View File
@@ -7652,6 +7652,58 @@ async fn gradle_incompatible_jdk_log_is_surfaced_once_across_message_channels()
assert_eq!(messages, vec![failure, "after"]);
}
#[tokio::test(flavor = "multi_thread")]
async fn a_failed_gradle_sync_is_surfaced_once_unless_an_incompatible_jdk_explains_it() {
let h = harness_for("java", "java", &[("jdtls", incremental_caps())], &[]);
let s = h.launcher.state("jdtls");
h.open("A.java", "class A {}");
h.wait_status("jdtls", ServerStatus::Ready).await;
let sync = |project: &str, cause: &str| {
format!(
"Nov 25, 2026, 2:00:14 PM Synchronize project {project} failed due to an error connecting to the Gradle build.\n\
org.gradle.tooling.BuildActionFailureException: The supplied phased action failed with an exception.\n\
\tat org.gradle.tooling.internal.consumer.DefaultPhasedBuildActionExecuter.run(DefaultPhasedBuildActionExecuter.java:68)\n\
Caused by: java.lang.IllegalArgumentException: {cause}\n\
\tat org.gradle.groovy.scripts.DefaultScript.apply(DefaultScript.java:133)"
)
};
// jdtls logs it below error level, and again on every sync.
for _ in 0..2 {
let message = sync("repro", "Unable to determine constructor argument #2");
s.peer().notify("window/logMessage", json!({ "type": 3, "message": message })).unwrap();
}
// An incompatible JDK fails the sync too, and jdtls then says so with its own fix.
s.peer()
.notify(
"window/logMessage",
json!({ "type": 3, "message": sync("old", "Unsupported class file major version 71") }),
)
.unwrap();
let jdk = "Can't use Java 27.0.1 and Gradle 7.5.1 to import Gradle project old.";
s.peer()
.notify("window/logMessage", json!({ "type": 1, "message": format!("{jdk}\njava.lang.Exception: details") }))
.unwrap();
let notes = || -> Vec<(String, String)> {
h.events
.lock()
.iter()
.filter_map(|e| match e {
IdeEvent::Notify { title, body: Some(b), .. } => Some((title.clone(), b.clone())),
_ => None,
})
.collect()
};
eventually(|| notes().iter().any(|(t, _)| t == "Gradle project sync failed")).await;
tokio::time::sleep(std::time::Duration::from_millis(500)).await;
let notes = notes();
let synced: Vec<_> =
notes.iter().filter(|(t, _)| t == "Gradle project sync failed").map(|(_, b)| b.as_str()).collect();
assert_eq!(synced.len(), 1, "{notes:?}");
assert!(synced[0].starts_with("Gradle could not sync repro. "), "{notes:?}");
assert!(synced[0].ends_with(" Cause: Unable to determine constructor argument #2"), "{notes:?}");
assert!(notes.iter().any(|(_, b)| b == jdk), "{notes:?}");
}
/// Pull Members Up / Push Members Down: the extension's answers, refusals and edits.
#[tokio::test(flavor = "multi_thread")]
async fn java_hierarchy_refactorings_use_the_extension_commands() {
+13
View File
@@ -119,6 +119,13 @@ pub struct PickItem {
pub description: Option<String>,
}
/// A group of file extensions in a plugin's native chooser.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
pub struct PluginFileFilter {
pub name: String,
pub extensions: Vec<String>,
}
/// What a plugin asks the user (`ui.pick`, `ui.pick-many`, `ui.input`,
/// `ui.input-multiline`, `ui.confirm`).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
@@ -132,6 +139,8 @@ pub enum Prompt {
Confirm { title: String, message: String },
#[serde(rename_all = "camelCase")]
PickDirectory { title: String, initial: Option<String> },
#[serde(rename_all = "camelCase")]
PickFile { title: String, save: bool, name: Option<String>, filters: Vec<PluginFileFilter> },
/// The host's own question under `net:ask` (never plugin-initiated): the
/// plugin reached an HTTPS host its manifest does not list.
#[serde(rename_all = "camelCase")]
@@ -993,11 +1002,15 @@ pub struct FileProblems {
}
/// An editor decoration.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct Decoration {
pub range: ide_core::Range,
pub style: String,
pub hover: Option<String>,
pub after: Option<String>,
/// Markdown rendered in the editor's hover card (API 1.16); `hover` is the
/// plain-text fallback shown when this is absent.
pub markdown_hover: Option<String>,
}
/// A tree decoration.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
+77 -20
View File
@@ -289,6 +289,8 @@ const MAX_FIND: u32 = 10_000;
const MAX_STATUS_TEXT: usize = 128;
const MAX_PICK_ITEMS: usize = 5000;
const MAX_PICK_KEY: usize = 256;
/// Filters of a `ui.pick-file` dialog, and extensions of each.
const MAX_FILE_FILTERS: usize = 32;
const MAX_ARGS: usize = 256;
const MAX_ARG_BYTES: usize = 4096;
const MAX_ENV: usize = 64;
@@ -419,6 +421,17 @@ impl log::Host for StoreData {
}
impl StoreData {
fn pick_path(&mut self, prompt: Prompt) -> Fallible<Option<String>> {
let answer = self.ask(prompt);
Ok(answer.and_then(|answer| {
let path = answer.and_then(|items| items.into_iter().next());
if let Some(path) = &path {
validate_ui_path(path)?;
}
Ok(path)
}))
}
/// Asks the user and waits; the wait doesn't count against the call's
/// wall-clock budget.
fn ask(&mut self, prompt: Prompt) -> Result<Option<Vec<String>>, wit::Error> {
@@ -794,14 +807,27 @@ impl ui::Host for StoreData {
{
return Ok(Err(error));
}
let answer = self.ask(Prompt::PickDirectory { title: clip(title, MAX_TITLE), initial });
Ok(answer.and_then(|answer| {
let path = answer.and_then(|items| items.into_iter().next());
if let Some(path) = &path {
validate_ui_path(path)?;
}
Ok(path)
}))
self.pick_path(Prompt::PickDirectory { title: clip(title, MAX_TITLE), initial })
}
fn pick_file(&mut self, title: String, dialog: ui::FileDialog) -> Fallible<Option<String>> {
let filters = dialog
.filters
.into_iter()
.take(MAX_FILE_FILTERS)
.map(|f| crate::PluginFileFilter {
name: clip(f.name, MAX_TITLE),
extensions: f.extensions.into_iter().take(MAX_FILE_FILTERS).map(|e| clip(e, MAX_PICK_KEY)).collect(),
})
.collect();
// A suggested file name only: the dialog starts where the user last was, never at a
// directory the plugin names.
let name = dialog
.name
.and_then(|n| n.rsplit(['/', '\\']).next().map(str::to_owned))
.filter(|n| !n.is_empty() && n != "." && n != "..")
.map(|n| clip(n, MAX_TITLE));
self.pick_path(Prompt::PickFile { title: clip(title, MAX_TITLE), save: dialog.save, name, filters })
}
fn pick_many(&mut self, title: String, items: Vec<ui::PickItem>) -> Fallible<Option<Vec<String>>> {
@@ -2802,6 +2828,23 @@ fn diagnostic_to_wit(d: ide_core::Diagnostic) -> diagnostics::Diagnostic {
related: Vec::new(),
}
}
impl StoreData {
/// Shared by `set` and `set-markdown`: both replace the same set-id namespace.
fn replace_decorations(&mut self, path: String, set_id: String, items: Vec<crate::Decoration>) -> Fallible<()> {
if let Err(e) = self.require(Capability::ProjectRead) {
return Ok(Err(e));
}
if items.len() > 10_000 {
return Ok(Err(wit::Error::Invalid("at most 10000 decorations per file".into())));
}
let real = match self.decoration_path(&path) {
Ok(real) => real,
Err(e) => return Ok(Err(e)),
};
Ok(self.host.decorations(Some(&real), &set_id, items).map_err(to_wit))
}
}
impl bindings::openidea::plugin::decorations::Host for StoreData {
fn set(
&mut self,
@@ -2809,21 +2852,35 @@ impl bindings::openidea::plugin::decorations::Host for StoreData {
set_id: String,
items: Vec<bindings::openidea::plugin::decorations::Decoration>,
) -> Fallible<()> {
if let Err(e) = self.require(Capability::ProjectRead) {
return Ok(Err(e));
}
if items.len() > 10_000 {
return Ok(Err(wit::Error::Invalid("at most 10000 decorations per file".into())));
}
let items = items
.into_iter()
.map(|d| crate::Decoration { range: core_range(d.range), style: d.style, hover: d.hover, after: d.after })
.map(|d| crate::Decoration {
range: core_range(d.range),
style: d.style,
hover: d.hover,
after: d.after,
markdown_hover: None,
})
.collect();
let real = match self.decoration_path(&path) {
Ok(real) => real,
Err(e) => return Ok(Err(e)),
};
Ok(self.host.decorations(Some(&real), &set_id, items).map_err(to_wit))
self.replace_decorations(path, set_id, items)
}
fn set_markdown(
&mut self,
path: String,
set_id: String,
items: Vec<bindings::openidea::plugin::decorations::MarkdownDecoration>,
) -> Fallible<()> {
let items = items
.into_iter()
.map(|d| crate::Decoration {
range: core_range(d.range),
style: d.style,
hover: d.hover,
after: d.after,
markdown_hover: d.markdown_hover,
})
.collect();
self.replace_decorations(path, set_id, items)
}
fn clear(&mut self, set_id: String) -> Fallible<()> {
if let Err(e) = self.require(Capability::ProjectRead) {
+1
View File
@@ -38,6 +38,7 @@ fn components() -> Vec<PathBuf> {
repo().join("crates/ide-plugin/tests/fixtures/symbols/dist/plugin.wasm"),
repo().join("crates/ide-plugin/tests/fixtures/api14/dist/plugin.wasm"),
repo().join("crates/ide-plugin/tests/fixtures/execution/dist/plugin.wasm"),
repo().join("crates/ide-plugin/tests/fixtures/decorations/dist/plugin.wasm"),
repo().join("crates/ide-plugin/tests/fixtures/search/dist/plugin.wasm"),
];
let official = repo().join("plugins/official");
Loaded 100 of 712 files, more files were not shown because too many files have changed in this diff. Show more