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

...
34 Коміти
Автор SHA1 Повідомлення Дата
l0ng-ai f5e8d77dcf chore: v0.1.7
Claude-Session: https://claude.ai/code/session_01B65qLEKnkeYTGdbwhLpjCu
2026-10-24 11:34:42 +08:00
l0ng-ai c3ea376899 feat(tools): Install 15 more language servers and debug adapters
Release downloads: buf, clojure-lsp, texlab, neocmakelsp, LemMinX, Perl
Navigator, kotlin-language-server, kotlin-debug-adapter and netcoredbg;
Open VSX: bash-debug and php-debug (run through node). Two new methods:
`gem` (ruby-lsp, solargraph), installed into the tool's folder and
launched with GEM_HOME, and `dotnet tool` (csharp-ls, fsautocomplete),
launched with DOTNET_ROOT so a Homebrew / user-local .NET is found.
Tools declare the runtime they need (Java, Node.js, Perl).

Each was installed from its real source and started on macOS arm64.

Claude-Session: https://claude.ai/code/session_01B65qLEKnkeYTGdbwhLpjCu
2026-10-24 11:26:31 +08:00
l0ng-ai fde075457b feat(editor): Tree-sitter highlighting for Zig, Nix, Make, GraphQL and HCL
Every grammar-only language now gets colours: Zig, Nix and Make from the
queries their crates ship, GraphQL and HCL (Terraform) from our own, as
those crates ship none.

Grammar queries follow two conventions, so the precedence is set per
grammar: nvim-style (the later pattern wins) or tree-sitter CLI style
(the first one wins, Nix). nvim's `#lua-match?` is evaluated; patterns
with predicates we cannot evaluate no longer match unconditionally,
which coloured every Zig identifier as a constant.

Claude-Session: https://claude.ai/code/session_01B65qLEKnkeYTGdbwhLpjCu
2026-10-24 11:26:31 +08:00
l0ng-ai 135723bca6 feat(tools): Install ElixirLS and its debugger, checking for Elixir first
ElixirLS ships one platform-independent zip of launcher scripts that
build the server with the project's Elixir / OTP on first start. Both
the language server and the debug adapter are installed from it, each
linked to its own launcher (language_server / debug_adapter).

Tools can now declare runtimes they need on PATH; Install stays
disabled with the reason ("Elixir is required") until they are found.

The Elixir debug adapter is renamed elixir-ls-debugger so it no longer
shares the server's tool name.

Claude-Session: https://claude.ai/code/session_01B65qLEKnkeYTGdbwhLpjCu
2026-10-24 11:26:31 +08:00
l0ng-ai 03a660354c feat(tools): Custom language server paths and a list/details Language Servers page
Servers and debug adapters could only be found on PATH or in the IDE's
tools folder; the only way to pick another executable (a version that
matches the project's Elixir/OTP, a local build) was an undocumented
languages/*.toml override. `tools.<command>.path` now names the
executable to launch: language servers (configure_server, restarted on
change), debug sessions and the tool list honour it, the latter
reporting a Custom status with its version or why the path is unusable.

The Language Servers page is laid out like Plugins: a compact list
grouped by availability on the left, the selected tool's command, path,
location, version, install actions and hints on the right.

A debugger named like its language server (ElixirLS's elixir-ls /
elixir-ls-debugger) was folded into the server's row and never listed;
it now gets a row of its own.

Claude-Session: https://claude.ai/code/session_01B65qLEKnkeYTGdbwhLpjCu
2026-10-24 11:26:31 +08:00
l0ng-ai 1572fc36ea feat(editor): Highlight languages without a CodeMirror mode from tree-sitter
Elixir files opened as plain text: highlighting only came from
@codemirror/language-data, which has no Elixir mode. Grammars now carry
their own highlights.scm; `doc_highlights` folds its captures into a small
kind vocabulary (inner nodes and later patterns win, interpolation clears
the string colour), memoised per document version on the incremental
tree. The editor maps kinds onto Lezer tags, so colours follow the active
scheme, and requests them only when no CodeMirror mode exists.

Enabled for Elixir; other grammar-only languages need their query wired.

Claude-Session: https://claude.ai/code/session_01B65qLEKnkeYTGdbwhLpjCu
2026-10-24 11:26:31 +08:00
l0ng-ai 4f74f22624 fix(ui): Size Select popups to the widest option and truncate the PR repo name
Virtualised list rows are absolutely positioned, so the popup only took the
trigger's width and cut short labels like "Merged". The Pull Requests header
now keeps the repository on one line with an ellipsis and a tooltip.
2026-10-24 10:02:13 +08:00
l0ng-ai 1309ce10e4 chore: v0.1.6 2026-10-24 09:21:16 +08:00
l0ng-ai 49be259232 fix(ui): Show the full SDK name in selects and shorten Windows home paths
A long detail (an installation path) was not cut, so it pushed the option label out
(e.g. "Eclipse Adopti…", the Maven name hidden) and scrolled the popup sideways. The
label now keeps its width and the detail is cut with an ellipsis (full path in the
tooltip, detail text translated). Paths under C:/Users/<name> are shown as ~/…
2026-10-24 09:11:58 +08:00
l0ng-ai 6a8016b888 fix(vcs): Keep submodule entries out of Rollback and refresh the log of another repository
- Rollback no longer offers a submodule's own entry: it cannot be reverted from the
  enclosing repository (it did nothing while reporting "Rolled back 1 file"). Rolling
  back only that entry explains how to revert it instead.
- A selected change is rolled back alone; only folders take the changes below them, so
  selecting a submodule's entry no longer pulls in the uncommitted files inside it.
- The Git log loads the branches of the newly selected repository, so it reloads when
  that repository's refs move (a new branch showed up only after a manual refresh).
2026-10-24 09:11:58 +08:00
l0ng-ai b8f422d451 fix(vcs): Route a nested repository's own entry to the enclosing one and harden multi-root
Review fixes for several repositories in one project:

- A path equal to a nested repository's root (a submodule's entry, an untracked
  clone) belongs to the enclosing repository, in the backend and the Commit view.
  It was routed to the nested repository as ".", so Rollback ran `git restore` and
  `git clean` over the whole submodule and Commit staged everything in it.
- Repository-scoped commands take the repository root exactly and fail when it is
  gone instead of running in an enclosing repository; path-based ones resolve the
  file's repository (Project::with_repo_of).
- The rescan on a repository appearing or going watches `.git/HEAD`: the watcher
  never reports a `.git` path itself, so the old check never fired.
- Status skips a repository that cannot be read; refresh falls back to the primary
  repository when the selected one is gone instead of failing every time.
- Commit and Compare-with-Local diffs resolve repository-relative paths against the
  selected repository's root, not the project root.
- Update Project and Fetch go on after a failing repository and report the failures
  together; Update skips repositories with a detached HEAD or no upstream.
- The Push dialog leaves out a repository that cannot be read.
- Shelve and patches fail clearly for changes of a nested repository instead of
  leaving them out silently (they still support the main repository only).
- Fix the repository discovery test on Windows (path separators); Chinese text for
  the new strings.
2026-10-23 23:15:09 +08:00
l0ng-ai c868ec8b68 fix(java): Apply the Maven settings to jdtls and Lombok, find more Maven installs
Review fixes for the Project JDK / Maven settings:

- jdtls gets the user settings.xml as java.configuration.maven.userSettings, so the
  editor resolves dependencies through the same mirrors and servers as sync and builds.
- The configured local repository (else <localRepository> of the chosen settings.xml)
  is where the static POM model looks for parent POMs / BOMs and where the Lombok
  agent is looked for.
- Maven discovery finds mvn.cmd on PATH on Windows and the homes Maven Wrapper 3.3+
  downloads (dists/<name>/<hash> without a nested folder).
- A Project JDK pointing at the JDK's bin directory is accepted.
- Detected run configurations reload when language settings change, so Maven and
  Gradle runs use the new JDK, Maven home and options.
- Chinese text for the new settings.
2026-10-23 23:15:09 +08:00
l0ng-ai 059a5193ff feat(vcs): Support several git repositories in one project (multi-root)
Only the repository containing the project root was known, so nested clones and
submodules (or a folder of side-by-side service repositories) showed no changes and
could not be committed or pushed. The project now has IDEA's VCS roots: the enclosing
repository plus those found below the project (scanned in the background, rescanned when
a .git appears or goes). Status covers all of them; path-based commands go to the file's
repository and repository-scoped ones take the selected repository.

The Commit view groups changes by repository and commits each one with included changes;
the branch widget names the selected repository and switches between them; Update Project
and Fetch run in every repository; Push lists every repository with outgoing commits; a
repository that stops in a merge or rebase is selected so Continue / Abort act on it.

Closes #12
2026-10-23 23:15:09 +08:00
l0ng-ai 0f7008391c feat(java): Add Project JDK and Maven home / settings.xml / local repository settings
The JDK was always picked automatically (JAVA_HOME, PATH, the usual install dirs, by the
module's Java version) and Maven was the project's mvnw or mvn on PATH, with no way to
override either. languages.java.jdk (Languages & Frameworks › Java › Project JDK) now sets
the default jdtls runtime, the JDK of Run/Debug and JAVA_HOME for Maven and Gradle;
languages.java.maven (Build Tools › Maven) sets the Maven home, -s and
-Dmaven.repo.local for sync, builds, tool-window goals and detected run configurations.
JDKs and Maven installations are detected for the pickers.

Closes #13
2026-10-23 23:15:09 +08:00
l0ng-ai c59f93988b feat(vcs): PyCharm-style Commit view and one shared message dialog
- workbench/messages: one promise-based ask/confirm/confirmChecked/showError
  host replaces the per-feature confirm dialogs (app, services, vcs,
  project tree, keymap, run, database, find, LSP choice popup).
- Commit tool window: Commit | Shelf | Stash tabs as the title, IDEA's
  toolbar (Update Project, View Options, Select Opened File), Unversioned
  collapsed, Commit / Commit and Push on one row, empty-message error.
- Commit Options popup: author, sign-off, before-commit checks, Git hooks;
  vcs_commit takes CommitOptions (--author, --no-verify).
- Remove from Recent Projects asks first; refused history rewrites show an
  error dialog.

Claude-Session: https://claude.ai/code/session_01B65qLEKnkeYTGdbwhLpjCu
2026-10-23 22:59:06 +08:00
l0ng-ai 76d33f0306 feat(ui): IDEA-style message dialogs, project widget popup and Chinese UI text
Message dialogs: `Dialog` gets an `icon` (question / info / warning / error)
that renders IDEA's alert layout: no title bar, a 32px icon, bold title,
text, checkbox under it. Every confirmation helper (prompt, VCS, services,
project tree, keymap, LSP choices, run, database, Replace All) uses it. Open
Project matches IDEA: "This Window" is the default and has focus. The Code
Analysis and TODO commit checks default to Review.

Project widget: the title bar project button opens a popup like IDEA's
ProjectWidget, with Open… / Clone Repository…, the projects open in other
windows (new `window_open_projects` command) and recent projects, filtered by
typing.

Chinese UI: UI text stays written in English and is translated through a
source-text catalog (`locales/text/zh.json`, about 2300 strings). The UI
primitives (buttons, checkboxes, selects, tabs, dialogs, menus, tooltips,
toasts, settings labels and hints) translate the strings they are given.
Action titles and categories are localised in the registry, and static JSX
text uses `<T>`, so text follows a locale switch without a reload. The
Settings window now syncs the locale too. Settings search matches both
languages.

Claude-Session: https://claude.ai/code/session_01B65qLEKnkeYTGdbwhLpjCu
2026-10-23 22:18:50 +08:00
l0ng-ai cd55bc8f7f chore: v0.1.5 2026-10-23 21:38:02 +08:00
l0ng-ai deec86fab9 refactor(perf): Remove the Memory Usage settings page
It was a live metrics view, not a setting, and duplicated the memory
indicator's popup, its status bar toggle and Clear Caches.

Claude-Session: https://claude.ai/code/session_01B65qLEKnkeYTGdbwhLpjCu
2026-10-23 21:35:02 +08:00
l0ng-ai 29e89f2525 fix(app): Give the Settings window a plain loader and make the splash bar progress
The Settings window loads the same page as project windows, so it showed the
launch splash with the logo. It now shows only the bar, after 400 ms.

The bar's sliding animation was switched off under reduced motion, leaving a
static 40% fill. It is now a fake progress that eases towards ~90% and fills
to 100% before the splash fades out.

Claude-Session: https://claude.ai/code/session_01B65qLEKnkeYTGdbwhLpjCu
2026-10-23 21:31:57 +08:00
l0ng-ai b1bb4a69cd fix(app): Keep the dark theme's background under a fast window resize
splash.css painted html light and only switched body to dark, so the page
canvas showed the light colour wherever a live resize outran relayout.
Leave html unpainted so the canvas takes body's themed background.

Also set the webview's background (not just the native window's) on a
theme change; it otherwise kept the colour the window was created with.
2026-10-23 21:29:45 +08:00
l0ng-ai ee99b3641f fix(ui): Hide the focus outline around dropdown popups
The global :focus-visible rule loads after the module CSS and has the same
specificity, so it overrode `outline: none` on the focused listbox wrapper
and drew a square blue frame inside the Select popup.

Claude-Session: https://claude.ai/code/session_01B65qLEKnkeYTGdbwhLpjCu
2026-10-23 21:23:06 +08:00
l0ng-ai 19aee5f262 fix(app): Never show the webview's native context menu (#11)
Right-clicks the app doesn't handle itself, such as on code-lens or inlay
widgets inside the editor or in text fields, fell through to WebKit's own
menu, whose Reload item reloads the whole app. Block it everywhere; the
app's own menus already call preventDefault before this guard runs.

Claude-Session: https://claude.ai/code/session_01B65qLEKnkeYTGdbwhLpjCu
2026-10-23 20:02:58 +08:00
l0ng-ai acf6931017 fix(java): Run jdtls with a Lombok agent and show build errors at launch (#9)
* fix(java): Run jdtls with a Lombok agent and show build errors at launch

jdtls compiles with ECJ, which only generates Lombok members when the
server JVM runs -javaagent:lombok.jar. Nothing put it there, so @Data /
@Setter classes lost their accessors and Run launched stale classes
with "Unresolved compilation problem" stubs and no explanation.

- Projects whose build files mention Lombok get the newest jar: the
  IDE-managed one (new "Lombok (jdtls agent)" tool, latest release from
  Maven Central), else ~/.m2 (incl. settings.xml localRepository) or the
  Gradle cache. Each agent gets its own jdtls workspace so everything is
  rebuilt with it.
- Settings › Languages & Frameworks › Java › JVM options
  (java.jdt.ls.vmargs); a Lombok agent there wins.
- Run (and Debug, as a notification) list the first compile errors when
  the build has errors, plus a hint when Lombok is missing or older than
  1.18.34.

Fixes #3

* fix(java): Base the Lombok hint on the agent jdtls actually runs

A Lombok agent in Settings › Java › JVM options wins over the managed
and cached jars, but the launch hint still looked only at those: with
no cached jar it said Lombok was missing, and with an old cached one it
blamed that version although jdtls ran the user's. The hint and the
startup warning now use the user's agent (version from its file name).
2026-10-23 18:46:13 +08:00
l0ng-ai 555ea8901f chore: v0.1.4
Claude-Session: https://claude.ai/code/session_01B65qLEKnkeYTGdbwhLpjCu
2026-10-23 18:41:02 +08:00
l0ng-ai 769c1248d6 fix(app): Load the splash CSS from a file so release editors keep their styles (#10)
Release builds hash inline <style> blocks from index.html into the CSP.
With a hash present, style-src 'unsafe-inline' is ignored, so CodeMirror's
runtime-injected styles were blocked and the editor rendered blank (bare
line numbers, no text). Dev builds don't rewrite the CSP, so it only
showed in v0.1.3 release bundles.

Claude-Session: https://claude.ai/code/session_01B65qLEKnkeYTGdbwhLpjCu
2026-10-23 18:40:49 +08:00
l0ng-ai 61ab1851fa chore: Remove stale .ideal and .vscode folders 2026-10-23 17:48:52 +08:00
l0ng-ai c6a1a36676 chore: v0.1.3
Claude-Session: https://claude.ai/code/session_01B65qLEKnkeYTGdbwhLpjCu
2026-10-23 17:30:21 +08:00
l0ng-ai 6165cb0174 perf: Add a black-box comparison with other IDEs (#6)
perf/compare/bench.py launches each IDE in apps.toml on the same project
and measures it from the outside, the same way for each: time to the
project window, to CPU settling and to log markers; memory and CPU of the
whole process tree; idle CPU, exit time, cache and install size. Runs on
Windows, macOS and Linux with psutil; --wipe-caches measures a cold index.

README: a Benchmark section with the first results against IntelliJ IDEA.
2026-10-23 16:54:39 +08:00
l0ng-ai 79f6caeaa8 test: Count ignored names in the excluded-folders glob test (#8)
a66f01e adds files.ignoredNames to exclude_globs(), so the expected
length is file_excludes() + 1, not files.exclude + 1. The test failed on
every platform since.
2026-10-23 16:41:18 +08:00
l0ng-ai dbfe66a119 chore: Add generated IDE-state .gitignore files 2026-10-23 15:40:41 +08:00
l0ng-ai a66f01ec87 feat(files): Add Ignored Files and Folders setting, honoured everywhere
Name patterns the IDE treats as nonexistent (.DS_Store, __pycache__, *.pyc, VCS dirs, ...) were hard-coded in five places, and Git changes ignored none of them, so .DS_Store showed up as unversioned. files.ignoredNames (IDEA's default list) now drives the project view, navigation bar, index, watcher, Find in Files, inspections and the Git status.
2026-10-23 15:40:41 +08:00
l0ng-ai bf06ca7832 feat(app): Show a themed splash until the launch project opens
Project windows are created in setup with the saved theme's frame colour, and the splash covers the first render while the launch project opens, so a window no longer flashes white or the Welcome screen. Single-instance is now release-only so a dev build can run beside an installed release.
2026-10-23 15:40:41 +08:00
l0ng-ai 63a03d1c08 fix: Status refresh loop, double project open at startup, jdtls Java requirement (#5)
* fix: Stop the status refresh loop and the double project open at startup

Every status rewrote .git/index, even with nothing to persist: gix's
`write_changes` writes an empty change set too. The watcher reports
.git/index writes as VCS changes, so each status triggered the next one,
together with an ahead/behind walk. On a repository with a long history
(freqtrade, 33k commits behind upstream) that kept a core busy for as long
as the project was open. Write back only when `has_changes()`.

A project passed on the command line was opened twice: the launch and the
"reopen last project" restore ran concurrently, and the restore checked
for an open project before the launch had finished. The second open found
the index cache locked and indexed in memory only; with a different last
project, the window ended up on whichever finished last. The restore now
waits for the startup launch.

* fix(lsp): Run jdtls on the Java version its bundles need

jdtls's launcher checks for Java 21, and so did JDTLS_MIN_JAVA, but the
Eclipse platform a release ships moves on: 1.63 bundles
org.eclipse.core.filesystem with JavaSE-25, so on a JDK 21 the server died
resolving its bundles ("jdtls is not ready (Crashed)") and the error told
users to install the 21 they already had.

Read the requirement from the installed jdtls instead: the highest osgi.ee
capability / Bundle-RequiredExecutionEnvironment among its plugins'
manifests (cached per install), never below 21. The runtime choice, the
rescan while no JDK fits and the "needs JDK N" message use it.

Fixes #4
2026-10-23 15:20:36 +08:00
l0ng-ai 4be1b152ef fix(ui): Drop the inner focus outline on text and search fields
The global :focus-visible outline outranked the module's `outline: none`
by load order, drawing a second ring inside the framed field's own focus
ring (visible on the Settings search box).

Claude-Session: https://claude.ai/code/session_01B65qLEKnkeYTGdbwhLpjCu
2026-10-23 14:52:13 +08:00
295 змінених файлів з 12446 додано та 2700 видалено

No files matched your search

+1 -2
Переглянути файл
@@ -13,8 +13,7 @@ dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.vscode
.idea
.DS_Store
*.suo
+3
Переглянути файл
@@ -0,0 +1,3 @@
# Per-user IDE state
/shelf/
/changelists.json
-3
Переглянути файл
@@ -1,3 +0,0 @@
{
"recommendations": ["tauri-apps.tauri-vscode", "rust-lang.rust-analyzer"]
}
Створено
+27 -26
Переглянути файл
@@ -3962,7 +3962,7 @@ checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
[[package]]
name = "ide-analysis"
version = "0.1.2"
version = "0.1.7"
dependencies = [
"ast-grep-core",
"ide-core",
@@ -3976,7 +3976,7 @@ dependencies = [
[[package]]
name = "ide-build"
version = "0.1.2"
version = "0.1.7"
dependencies = [
"dirs 6.0.0",
"dunce",
@@ -3991,7 +3991,7 @@ dependencies = [
[[package]]
name = "ide-core"
version = "0.1.2"
version = "0.1.7"
dependencies = [
"dunce",
"serde",
@@ -4003,7 +4003,7 @@ dependencies = [
[[package]]
name = "ide-coverage"
version = "0.1.2"
version = "0.1.7"
dependencies = [
"ide-core",
"ide-run",
@@ -4017,7 +4017,7 @@ dependencies = [
[[package]]
name = "ide-dap"
version = "0.1.2"
version = "0.1.7"
dependencies = [
"ide-core",
"ide-jsonrpc",
@@ -4034,7 +4034,7 @@ dependencies = [
[[package]]
name = "ide-db"
version = "0.1.2"
version = "0.1.7"
dependencies = [
"dirs 6.0.0",
"futures",
@@ -4054,7 +4054,7 @@ dependencies = [
[[package]]
name = "ide-docker"
version = "0.1.2"
version = "0.1.7"
dependencies = [
"ide-core",
"libc",
@@ -4067,7 +4067,7 @@ dependencies = [
[[package]]
name = "ide-github"
version = "0.1.2"
version = "0.1.7"
dependencies = [
"ide-core",
"ide-vcs",
@@ -4081,7 +4081,7 @@ dependencies = [
[[package]]
name = "ide-http"
version = "0.1.2"
version = "0.1.7"
dependencies = [
"ide-core",
"parking_lot",
@@ -4099,7 +4099,7 @@ dependencies = [
[[package]]
name = "ide-index"
version = "0.1.2"
version = "0.1.7"
dependencies = [
"blake3",
"criterion",
@@ -4121,7 +4121,7 @@ dependencies = [
[[package]]
name = "ide-jsonrpc"
version = "0.1.2"
version = "0.1.7"
dependencies = [
"futures",
"ide-core",
@@ -4136,7 +4136,7 @@ dependencies = [
[[package]]
name = "ide-language"
version = "0.1.2"
version = "0.1.7"
dependencies = [
"blake3",
"criterion",
@@ -4188,7 +4188,7 @@ dependencies = [
[[package]]
name = "ide-lsp"
version = "0.1.2"
version = "0.1.7"
dependencies = [
"futures",
"globset",
@@ -4211,7 +4211,7 @@ dependencies = [
[[package]]
name = "ide-plugin"
version = "0.1.2"
version = "0.1.7"
dependencies = [
"ide-core",
"ide-language",
@@ -4229,7 +4229,7 @@ dependencies = [
[[package]]
name = "ide-profiler"
version = "0.1.2"
version = "0.1.7"
dependencies = [
"ide-core",
"ide-run",
@@ -4242,7 +4242,7 @@ dependencies = [
[[package]]
name = "ide-run"
version = "0.1.2"
version = "0.1.7"
dependencies = [
"encoding_rs",
"ide-core",
@@ -4260,7 +4260,7 @@ dependencies = [
[[package]]
name = "ide-sdk"
version = "0.1.2"
version = "0.1.7"
dependencies = [
"dunce",
"ide-core",
@@ -4272,11 +4272,12 @@ dependencies = [
"tempfile",
"toml 0.9.12+spec-1.1.0",
"tracing",
"zip 2.4.2",
]
[[package]]
name = "ide-search"
version = "0.1.2"
version = "0.1.7"
dependencies = [
"criterion",
"globset",
@@ -4295,7 +4296,7 @@ dependencies = [
[[package]]
name = "ide-syntax"
version = "0.1.2"
version = "0.1.7"
dependencies = [
"ide-core",
"ide-language",
@@ -4310,7 +4311,7 @@ dependencies = [
[[package]]
name = "ide-terminal"
version = "0.1.2"
version = "0.1.7"
dependencies = [
"ide-core",
"libc",
@@ -4323,7 +4324,7 @@ dependencies = [
[[package]]
name = "ide-text"
version = "0.1.2"
version = "0.1.7"
dependencies = [
"criterion",
"ide-core",
@@ -4335,7 +4336,7 @@ dependencies = [
[[package]]
name = "ide-tools"
version = "0.1.2"
version = "0.1.7"
dependencies = [
"flate2",
"hex",
@@ -4355,7 +4356,7 @@ dependencies = [
[[package]]
name = "ide-vcs"
version = "0.1.2"
version = "0.1.7"
dependencies = [
"dunce",
"gix",
@@ -4372,7 +4373,7 @@ dependencies = [
[[package]]
name = "ide-vfs"
version = "0.1.2"
version = "0.1.7"
dependencies = [
"chardetng",
"dunce",
@@ -4392,7 +4393,7 @@ dependencies = [
[[package]]
name = "ide-workspace"
version = "0.1.2"
version = "0.1.7"
dependencies = [
"blake3",
"dunce",
@@ -5816,7 +5817,7 @@ dependencies = [
[[package]]
name = "openidea"
version = "0.1.2"
version = "0.1.7"
dependencies = [
"dirs 6.0.0",
"dunce",
+1 -1
Переглянути файл
@@ -3,7 +3,7 @@ resolver = "3"
members = ["crates/*", "src-tauri"]
[workspace.package]
version = "0.1.2"
version = "0.1.7"
edition = "2024"
rust-version = "1.96"
license = "Apache-2.0"
+20
Переглянути файл
@@ -17,6 +17,26 @@ its search-everything habits — to a native app with a Rust core.
Editor, code insight, debugger, Git, terminal, database and HTTP clients,
for 60+ languages.
## Benchmark
Opening [freqtrade](https://github.com/freqtrade/freqtrade) (Python, ~770 files)
with warm caches, median of 5 runs:
| | OpenIDEA | IntelliJ IDEA 2026.2.3 |
|---|---|---|
| Window with the project | **0.9 s** | 3.1 s |
| Ready (CPU settled) | **1.1 s** | 13.2 s |
| Memory (USS, all processes) | **169 MB** | 2011 MB |
| CPU time until ready | **2.4 s** | 47.9 s |
| Idle CPU | **4 %** of a core | 7 % of a core |
| Quit | **0.3 s** | 5.9 s |
A release build of OpenIDEA from `main` and IDEA with default settings and plugins, on
Windows 11, 32-core AMD, 62 GB RAM.
IDEA analyses Python more deeply, so "ready" doesn't mean the same work on
both sides. Both are measured from the outside, the same way: see
[`perf/compare`](perf/compare) to run it on your machine and projects.
## Build
```sh
+1 -1
Переглянути файл
@@ -19,7 +19,7 @@ fn main() {
eprintln!("synced in {:?}: {r:?}", started.elapsed());
}
let started = std::time::Instant::now();
let model = ide_build::load(&root, &cache);
let model = ide_build::load(&root, &cache, None);
println!("{}", serde_json::to_string_pretty(&model).unwrap());
eprintln!("loaded in {:?}", started.elapsed());
}
+3 -2
Переглянути файл
@@ -225,6 +225,7 @@ fn maven_steps(root: &Path, model: &BuildModel, kind: BuildKind, module: Option<
}
let step = |p: &maven::MavenProject, extra: &[String]| {
let mut s = BuildStep::new(&p.command, &["-B", "-Dstyle.color=never"], &subdir(root, &p.dir), Format::Maven);
s.args.extend(p.options.iter().cloned());
s.args.extend(extra.iter().cloned());
s.args.extend(goals.iter().map(|g| (*g).to_owned()));
s.env = p.env.clone();
@@ -671,7 +672,7 @@ mod tests {
);
write(&root, "core/pom.xml", "<project><artifactId>core</artifactId></project>");
write(&root, "core/src/main/java/A.java", "class A {}");
let model = crate::load(&root, &tmp.path().join("cache"));
let model = crate::load(&root, &tmp.path().join("cache"), None);
let p = plan(&root, &model, BuildKind::Build, None).unwrap();
assert_eq!(p.system, BuildSystem::Maven);
assert_eq!(p.title, "demo");
@@ -685,7 +686,7 @@ mod tests {
let g = tmp.path().join("g");
write(&g, "settings.gradle", "include 'app'");
write(&g, "app/build.gradle", "apply plugin: 'java'");
let model = crate::load(&g, &tmp.path().join("cache2"));
let model = crate::load(&g, &tmp.path().join("cache2"), None);
let p = plan(&g, &model, BuildKind::Build, Some(&g.join("app/src/A.java"))).unwrap();
assert_eq!(p.system, BuildSystem::Gradle);
assert_eq!(p.steps[0].args, ["--console=plain", ":app:classes", ":app:testClasses"]);
+6 -5
Переглянути файл
@@ -18,7 +18,7 @@ pub use sync::{SyncOptions, SyncProgress, sync_gradle, sync_maven};
use serde::{Deserialize, Serialize};
use specta::Type;
use std::path::Path;
use std::path::{Path, PathBuf};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
@@ -36,9 +36,10 @@ pub struct BuildModel {
}
/// Static model of the builds under `root`, merged with the sync results cached in `cache_dir`.
pub fn load(root: &Path, cache_dir: &Path) -> BuildModel {
/// Parent POMs are looked up in `maven_repo` (the configured local repository), else the default one.
pub fn load(root: &Path, cache_dir: &Path, maven_repo: Option<PathBuf>) -> BuildModel {
let maven = maven::is_maven_project(root).then(|| {
let mut m = maven::load(root);
let mut m = maven::load_with_repo(root, maven_repo.or_else(maven::default_local_repo));
sync::apply_maven_cache(root, cache_dir, &mut m);
m
});
@@ -68,10 +69,10 @@ mod tests {
let cache = tmp.path().join("cache");
let root = tmp.path().join("p");
std::fs::create_dir_all(root.join("svc")).unwrap();
assert_eq!(load(&root, &cache), BuildModel::default());
assert_eq!(load(&root, &cache, None), BuildModel::default());
std::fs::write(root.join("svc/pom.xml"), "<project><artifactId>svc</artifactId></project>").unwrap();
std::fs::write(root.join("build.gradle"), "").unwrap();
let m = load(&root, &cache);
let m = load(&root, &cache, None);
assert_eq!(m.maven.unwrap().projects[0].pom, "svc/pom.xml");
assert_eq!(m.gradle.unwrap().projects[0].path, ":");
assert!(affects_build(Path::new("a/pom.xml")) && affects_build(Path::new("settings.gradle.kts")));
+4 -1
Переглянути файл
@@ -92,6 +92,8 @@ pub struct MavenProject {
pub java_version: Option<u32>,
/// Maven launcher: the nearest `mvnw` up to the project root (absolute), else `mvn`.
pub command: String,
/// Options before the goals (`-s`, `-Dmaven.repo.local=`); filled in by the shell from settings.
pub options: Vec<String>,
/// Environment for runs (`JAVA_HOME` of the matching JDK); filled in by the shell.
pub env: BTreeMap<String, String>,
}
@@ -410,7 +412,7 @@ struct Resolver {
}
/// `~/.m2/repository`, or `<localRepository>` from `~/.m2/settings.xml`.
fn default_local_repo() -> Option<PathBuf> {
pub(crate) fn default_local_repo() -> Option<PathBuf> {
let m2 = dirs::home_dir()?.join(".m2");
if let Some(settings) = std::fs::read_to_string(m2.join("settings.xml")).ok().and_then(|t| xml::parse(&t))
&& let Some(repo) = settings.text_of("localRepository")
@@ -924,6 +926,7 @@ pub(crate) fn load_with_repo(root: &Path, local_repo: Option<PathBuf>) -> MavenM
profiles: pom.profiles.iter().map(|p| p.id.clone()).collect(),
java_version: jv,
command: wrapper(root, &dir),
options: Vec::new(),
env: BTreeMap::new(),
});
for m in modules.into_iter().rev() {
+7 -1
Переглянути файл
@@ -29,6 +29,10 @@ pub struct SyncOptions {
pub profiles: Vec<String>,
/// Extra environment (`JAVA_HOME`).
pub env: BTreeMap<String, String>,
/// Maven launcher replacing the project's `mvnw` / `mvn` (Settings › Maven home).
pub maven_command: Option<String>,
/// Maven options before the goals (`-s`, `-Dmaven.repo.local=`).
pub maven_options: Vec<String>,
}
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
@@ -184,6 +188,7 @@ pub fn sync_maven(
let effective = cache_dir.join(format!("effective-pom-{n}.xml"));
let _ = std::fs::remove_file(&effective);
let mut args: Vec<String> = vec!["-B".into(), "-fae".into(), "-Dstyle.color=never".into()];
args.extend(options.maven_options.iter().cloned());
if options.offline {
args.push("-o".into());
}
@@ -194,7 +199,8 @@ pub fn sync_maven(
args.push(format!("-Doutput={}", effective.to_string_lossy()));
args.push("dependency:tree".into());
progress(SyncProgress { message: format!("Reading {}", top.display_name), fraction: None });
let out = run(&top.command, &args, &root.join(&top.dir), &options.env, cancel, |line| {
let command = options.maven_command.as_deref().unwrap_or(&top.command);
let out = run(command, &args, &root.join(&top.dir), &options.env, cancel, |line| {
if let Some((name, i, total)) = maven_building(line) {
let fraction = (i.saturating_sub(1) as f32 / total.max(1) as f32).min(1.0);
progress(SyncProgress { message: format!("Building model of {name}"), fraction: Some(fraction) });
+106
Переглянути файл
@@ -0,0 +1,106 @@
//! "Ignored Files and Folders" (IDEA: Settings › File Types): file names the IDE
//! treats as nonexistent — hidden from the project view and navigation, never
//! indexed or searched, never offered as unversioned changes.
/// IDEA's default list, plus `.jj` and the Windows shell files.
pub const DEFAULT_IGNORED_NAMES: &[&str] = &[
"*.pyc",
"*.pyo",
"*.rbc",
"*.yarb",
"*~",
".DS_Store",
".git",
".hg",
".jj",
".svn",
"CVS",
"__pycache__",
"_svn",
"vssver.scc",
"vssver2.scc",
"Thumbs.db",
"desktop.ini",
];
/// Matches single path segments against name patterns (`*` and `?` wildcards).
#[derive(Clone, Debug, Default)]
pub struct IgnoredNames {
exact: Vec<String>,
wildcards: Vec<String>,
}
impl IgnoredNames {
pub fn new(patterns: &[String]) -> Self {
let mut out = Self::default();
for p in patterns.iter().map(|p| p.trim()).filter(|p| !p.is_empty() && !p.contains('/')) {
if p.contains(['*', '?']) {
out.wildcards.push(p.to_owned());
} else {
out.exact.push(p.to_owned());
}
}
out
}
pub fn is_ignored_name(&self, name: &str) -> bool {
self.exact.iter().any(|e| e == name) || self.wildcards.iter().any(|w| wildcard(w.as_bytes(), name.as_bytes()))
}
/// Whether any segment of a `/`-separated relative path is ignored.
pub fn is_ignored_path(&self, rel: &str) -> bool {
rel.split('/').any(|seg| !seg.is_empty() && self.is_ignored_name(seg))
}
}
fn wildcard(p: &[u8], s: &[u8]) -> bool {
let (mut pi, mut si, mut star, mut mark) = (0, 0, None, 0);
while si < s.len() {
if pi < p.len() && (p[pi] == b'?' || p[pi] == s[si]) {
pi += 1;
si += 1;
} else if pi < p.len() && p[pi] == b'*' {
star = Some(pi);
pi += 1;
mark = si;
} else if let Some(st) = star {
pi = st + 1;
mark += 1;
si = mark;
} else {
return false;
}
}
p[pi..].iter().all(|&c| c == b'*')
}
#[cfg(test)]
mod tests {
use super::*;
fn defaults() -> IgnoredNames {
IgnoredNames::new(&DEFAULT_IGNORED_NAMES.iter().map(|s| s.to_string()).collect::<Vec<_>>())
}
#[test]
fn matches_names_and_wildcards() {
let m = defaults();
for name in [".DS_Store", "__pycache__", "a.pyc", "notes.txt~", "Thumbs.db"] {
assert!(m.is_ignored_name(name), "{name}");
}
for name in ["DS_Store", "a.py", "pyc", "src", ".gitignore"] {
assert!(!m.is_ignored_name(name), "{name}");
}
assert!(wildcard(b"a?c*", b"abcdef"));
assert!(!wildcard(b"a?c", b"abcd"));
}
#[test]
fn matches_any_path_segment() {
let m = defaults();
assert!(m.is_ignored_path("src/.DS_Store"));
assert!(m.is_ignored_path("pkg/__pycache__/"));
assert!(m.is_ignored_path("pkg/__pycache__/mod.cpython-312.pyc"));
assert!(!m.is_ignored_path("src/main.rs"));
}
}
+1
Переглянути файл
@@ -8,6 +8,7 @@ pub mod editor_settings;
pub mod error;
pub mod event;
pub mod ids;
pub mod ignored;
pub mod ipc_path;
pub mod project_dir;
pub mod settings;
+60 -2
Переглянути файл
@@ -37,6 +37,23 @@ pub struct Settings {
pub terminal: TerminalSettings,
pub actions_on_save: ActionsOnSaveSettings,
pub external_tools: Vec<ExternalTool>,
/// Language servers / debug adapters at a user-chosen location, by the
/// command the language definition launches (`elixir-ls`, `codelldb`).
pub tools: BTreeMap<String, ToolSettings>,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct ToolSettings {
/// Executable to launch instead of the managed / `PATH` one; empty = auto-detect.
pub path: String,
}
impl Settings {
/// The configured executable for `command`, if any (`~/` not yet expanded).
pub fn tool_path(&self, command: &str) -> Option<&str> {
self.tools.get(command).map(|t| t.path.trim()).filter(|p| !p.is_empty())
}
}
impl Default for Settings {
@@ -59,6 +76,7 @@ impl Default for Settings {
terminal: TerminalSettings::default(),
actions_on_save: ActionsOnSaveSettings::default(),
external_tools: Vec::new(),
tools: BTreeMap::new(),
}
}
}
@@ -303,6 +321,8 @@ pub struct FileSettings {
/// Save on focus loss / tab switch, like IDEA.
pub auto_save: bool,
pub exclude: Vec<String>,
/// Ignored Files and Folders: name patterns hidden everywhere; see [`crate::ignored`].
pub ignored_names: Vec<String>,
pub trim_trailing_whitespace: bool,
pub ensure_final_newline: bool,
/// Local History keeps changes from this many working days (days with changes), like IDEA.
@@ -316,6 +336,7 @@ impl Default for FileSettings {
Self {
auto_save: true,
exclude: vec!["**/.git".into(), "**/node_modules".into(), "**/target".into()],
ignored_names: crate::ignored::DEFAULT_IGNORED_NAMES.iter().map(|s| (*s).into()).collect(),
trim_trailing_whitespace: true,
ensure_final_newline: true,
local_history_days: 5,
@@ -332,6 +353,7 @@ pub struct LanguagesSettings {
pub rust: RustSettings,
pub go: GoSettings,
pub typescript: TypeScriptSettings,
pub java: JavaSettings,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
@@ -394,6 +416,31 @@ pub struct GoSettings {
pub gopath: String,
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct JavaSettings {
/// Project JDK home; empty = per module, the installed JDK matching the
/// Java version it targets.
pub jdk: String,
/// Extra JVM options for the Java language server (jdtls), space-separated
/// (VS Code's `java.jdt.ls.vmargs`).
pub jdtls_vm_args: String,
/// Build Tools › Maven.
pub maven: MavenSettings,
}
/// Build Tools › Maven.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct MavenSettings {
/// Maven home (or its `mvn` executable); empty = the project's `mvnw`, else `mvn` on `PATH`.
pub home: String,
/// User `settings.xml` (`-s`); empty = `~/.m2/settings.xml`.
pub user_settings: String,
/// Local repository (`-Dmaven.repo.local`); empty = from `settings.xml`.
pub local_repository: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct TypeScriptSettings {
@@ -423,9 +470,9 @@ pub struct ProjectStructureSettings {
}
impl Settings {
/// `files.exclude` plus the Project Structure excluded folders as globs.
/// `files.exclude`, the ignored names and the Project Structure excluded folders as globs.
pub fn exclude_globs(&self) -> Vec<String> {
let mut out = self.files.exclude.clone();
let mut out = self.file_excludes();
for dir in &self.project_structure.excluded {
let dir = dir.trim().trim_matches('/');
if !dir.is_empty() {
@@ -434,6 +481,17 @@ impl Settings {
}
out
}
/// `files.exclude` plus `files.ignoredNames` (a bare name matches at any depth).
pub fn file_excludes(&self) -> Vec<String> {
let mut out = self.files.exclude.clone();
out.extend(self.files.ignored_names.iter().filter(|n| !n.trim().is_empty()).cloned());
out
}
pub fn ignored_names(&self) -> crate::ignored::IgnoredNames {
crate::ignored::IgnoredNames::new(&self.files.ignored_names)
}
}
#[cfg(test)]
+14
Переглянути файл
@@ -522,6 +522,17 @@ impl DebugManager {
/// waits for `initialized`, sends breakpoints, then `configurationDone`.
/// Events of the session (including cargo build output) go to `owner` only.
pub async fn start(&self, config: LaunchConfig, owner: SessionOwner) -> IdeResult<DebugSessionId> {
self.start_with(config, owner, |_| None).await
}
/// [`start`](Self::start) with the adapter executable chosen by `custom_command`
/// (the configured command → a user-chosen executable, from settings).
pub async fn start_with(
&self,
config: LaunchConfig,
owner: SessionOwner,
custom_command: impl FnOnce(&str) -> Option<String>,
) -> IdeResult<DebugSessionId> {
let mut arguments = launch_arguments(&config)?;
let cwd = config
.cwd
@@ -531,6 +542,9 @@ impl DebugManager {
let dbg = adapter::find_config(&self.languages, &config.adapter)
.ok_or_else(|| IdeError::unavailable(format!("unknown debug adapter `{}`", config.adapter)))?;
let mut spec = adapter::resolve(&dbg, cwd.clone());
if let Some(command) = custom_command(&spec.command) {
spec.command = command;
}
// debugpy: run the adapter with the debuggee's interpreter (venvs carry their own debugpy).
if config.adapter == "debugpy" {
let python = match arguments.get("python") {
+2 -2
Переглянути файл
@@ -9,8 +9,8 @@ use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc;
use std::time::UNIX_EPOCH;
/// VCS metadata directories are never indexed.
const ALWAYS_SKIP: &[&str] = &[".git", ".hg", ".svn", ".jj", ".DS_Store"];
/// VCS metadata directories are never indexed, whatever the ignored names say.
const ALWAYS_SKIP: &[&str] = &[".git", ".hg", ".svn", ".jj"];
pub(crate) struct PathFilter {
root: PathBuf,
+49
Переглянути файл
@@ -0,0 +1,49 @@
; GraphQL highlighting (the grammar crate ships no query). Later patterns win.
(comment) @comment
(description (string_value) @comment.doc)
(string_value) @string
(int_value) @number
(float_value) @number
[(boolean_value) (null_value)] @keyword
(enum_value (name) @constant)
(variable) @variable
(argument (name) @variable.parameter)
(input_value_definition (name) @variable.parameter)
(object_field (name) @property)
(field (name) @property)
(alias (name) @property)
(field_definition (name) @property)
(enum_value_definition (enum_value (name) @constant))
(named_type (name) @type)
(object_type_definition (name) @type)
(interface_type_definition (name) @type)
(union_type_definition (name) @type)
(enum_type_definition (name) @type)
(input_object_type_definition (name) @type)
(scalar_type_definition (name) @type)
(object_type_extension (name) @type)
(interface_type_extension (name) @type)
(union_type_extension (name) @type)
(enum_type_extension (name) @type)
(input_object_type_extension (name) @type)
(scalar_type_extension (name) @type)
(operation_definition (name) @function)
(fragment_name (name) @function)
(directive_definition (name) @attribute)
(directive (name) @attribute)
"@" @attribute
(directive_location) @constant
(operation_type) @keyword
[
"query" "mutation" "subscription" "fragment" "on" "type" "interface" "union"
"enum" "input" "scalar" "schema" "extend" "implements" "directive" "repeatable"
] @keyword
["(" ")" "[" "]" "{" "}"] @punctuation.bracket
[":" "=" "|" "&" "!" "..."] @punctuation.delimiter
+29
Переглянути файл
@@ -0,0 +1,29 @@
; HCL / Terraform highlighting (the grammar crate ships no query). Later patterns win.
(comment) @comment
(string_lit) @string
(quoted_template) @string
(heredoc_template) @string
[(heredoc_start) (heredoc_identifier)] @string.special
(template_literal) @string
(numeric_lit) @number
[(bool_lit) (null_lit)] @keyword
(identifier) @variable
(attribute (identifier) @property)
(object_elem key: (expression (variable_expr (identifier) @property)))
(get_attr (identifier) @property)
(function_call (identifier) @function)
; `resource "aws_instance" "web" {`
(block (identifier) @keyword)
(block (string_lit (template_literal) @type))
(template_interpolation) @embedded
[(template_interpolation_start) (template_interpolation_end)] @punctuation.special
[(template_directive_start) (template_directive_end) (strip_marker)] @punctuation.special
["for" "in" "if" "else" "endfor" "endif"] @keyword
(operation) @operator
["!" "!=" "%" "&&" "*" "+" "-" "/" "<" "<=" "==" ">" ">=" "||" "?" "=>"] @operator
["=" ":" "," "."] @punctuation.delimiter
["(" ")" "[" "]" "{" "}" "[*]" ".*"] @punctuation.bracket
+4 -1
Переглянути файл
@@ -12,7 +12,10 @@ use std::collections::BTreeMap;
mod registry;
mod syntax;
pub use registry::LanguageRegistry;
pub use syntax::{MAX_CACHED_TREES, MAX_PARSE_BYTES, ParsedTree, Syntax, SyntaxCache, SyntaxCacheStats, TreeError};
pub use syntax::{
MAX_CACHED_TREES, MAX_PARSE_BYTES, ParsedTree, Syntax, SyntaxCache, SyntaxCacheStats, SyntaxHighlightKind,
SyntaxHighlights, TreeError,
};
/// Parsed form of `languages/<id>.toml`. Backend-only; the UI gets [`LanguageInfo`].
#[derive(Clone, Debug, Serialize, Deserialize)]
+20 -1
Переглянути файл
@@ -5,7 +5,10 @@
//! Structure / folding / Extend Selection on a large file cost an incremental
//! parse instead of a full one.
use super::{Grammar, MAX_PARSE_BYTES, ParsedTree, Syntax, TreeError, folding, outline, parse_cancellable, selection};
use super::{
Grammar, MAX_PARSE_BYTES, ParsedTree, Syntax, SyntaxHighlights, TreeError, folding, highlight, outline,
parse_cancellable, selection,
};
use crate::FoldRange;
use ide_core::{DocId, LanguageId, OutlineItem, Range};
use ide_text::ByteEdit;
@@ -59,6 +62,7 @@ struct Memo {
key: Option<(u32, LanguageId)>,
outline: Option<Arc<Vec<OutlineItem>>>,
folding: Option<Arc<Vec<FoldRange>>>,
highlights: Option<Arc<Vec<u32>>>,
}
impl Memo {
@@ -211,6 +215,21 @@ impl SyntaxCache {
)
}
/// Highlighting from the grammar's own query; empty without one.
pub fn highlights(&self, doc: DocId, lang: &LanguageId, version: u32, text: &str) -> SyntaxHighlights {
SyntaxHighlights::new(self.memoized(
doc,
lang,
version,
|m| &mut m.highlights,
|| {
self.with_tree(doc, lang, version, text, |g, tree, text| {
Some(highlight::highlights(g.highlight_query()?, tree, text))
})
},
))
}
/// `compute()` once per document version; `None` (no grammar / query) is not memoized.
fn memoized<T: Clone>(
&self,
+53
Переглянути файл
@@ -9,6 +9,8 @@ pub(crate) struct Spec {
pub language: LanguageFn,
/// `queries/<name>/outline.scm`; see `queries/README.md` for the capture vocabulary.
pub outline: &'static str,
/// The grammar's `highlights.scm`, for languages without a CodeMirror mode.
pub highlights: Option<Highlights>,
/// Node kinds folded when they span several lines (in addition to every
/// bracket-delimited node, which is folded generically).
pub fold_nodes: &'static [&'static str],
@@ -20,6 +22,21 @@ pub(crate) struct Spec {
pub constructors: &'static [&'static str],
}
/// A highlights query and how its patterns rank against each other.
pub(crate) struct Highlights {
pub query: &'static str,
/// For the same node, the first matching pattern wins (tree-sitter CLI /
/// GitHub queries) instead of the last one (nvim / Zed queries).
pub first_wins: bool,
}
/// Our own `queries/<name>/highlights.scm`, for grammars that ship none.
macro_rules! highlights {
($name:literal) => {
include_str!(concat!("../../queries/", $name, "/highlights.scm"))
};
}
macro_rules! outline {
($name:literal) => {
include_str!(concat!("../../queries/", $name, "/outline.scm"))
@@ -33,6 +50,7 @@ pub(crate) static SPECS: &[Spec] = &[
name: "rust",
language: tree_sitter_rust::LANGUAGE,
outline: outline!("rust"),
highlights: None,
fold_nodes: NONE,
fold_bodies: NONE,
imports: &["use_declaration", "extern_crate_declaration"],
@@ -42,6 +60,7 @@ pub(crate) static SPECS: &[Spec] = &[
name: "typescript",
language: tree_sitter_typescript::LANGUAGE_TYPESCRIPT,
outline: outline!("typescript"),
highlights: None,
fold_nodes: &["template_string"],
fold_bodies: NONE,
imports: &["import_statement"],
@@ -51,6 +70,7 @@ pub(crate) static SPECS: &[Spec] = &[
name: "tsx",
language: tree_sitter_typescript::LANGUAGE_TSX,
outline: outline!("typescript"),
highlights: None,
fold_nodes: &["template_string", "jsx_element"],
fold_bodies: NONE,
imports: &["import_statement"],
@@ -60,6 +80,7 @@ pub(crate) static SPECS: &[Spec] = &[
name: "javascript",
language: tree_sitter_javascript::LANGUAGE,
outline: outline!("javascript"),
highlights: None,
fold_nodes: &["template_string", "jsx_element"],
fold_bodies: NONE,
imports: &["import_statement"],
@@ -69,6 +90,7 @@ pub(crate) static SPECS: &[Spec] = &[
name: "python",
language: tree_sitter_python::LANGUAGE,
outline: outline!("python"),
highlights: None,
fold_nodes: &["string"],
fold_bodies: &["block"],
imports: &["import_statement", "import_from_statement", "future_import_statement"],
@@ -78,6 +100,7 @@ pub(crate) static SPECS: &[Spec] = &[
name: "go",
language: tree_sitter_go::LANGUAGE,
outline: outline!("go"),
highlights: None,
fold_nodes: &["raw_string_literal"],
fold_bodies: NONE,
imports: &["import_declaration"],
@@ -87,6 +110,7 @@ pub(crate) static SPECS: &[Spec] = &[
name: "java",
language: tree_sitter_java::LANGUAGE,
outline: outline!("java"),
highlights: None,
fold_nodes: &["text_block"],
fold_bodies: NONE,
imports: &["import_declaration"],
@@ -96,6 +120,7 @@ pub(crate) static SPECS: &[Spec] = &[
name: "kotlin",
language: tree_sitter_kotlin_ng::LANGUAGE,
outline: outline!("kotlin"),
highlights: None,
fold_nodes: &["string_literal"],
fold_bodies: NONE,
imports: &["import"],
@@ -105,6 +130,7 @@ pub(crate) static SPECS: &[Spec] = &[
name: "scala",
language: tree_sitter_scala::LANGUAGE,
outline: outline!("scala"),
highlights: None,
fold_nodes: &["string"],
fold_bodies: &["indented_block", "template_body"],
imports: &["import_declaration"],
@@ -114,6 +140,7 @@ pub(crate) static SPECS: &[Spec] = &[
name: "c",
language: tree_sitter_c::LANGUAGE,
outline: outline!("c"),
highlights: None,
fold_nodes: &["preproc_if", "preproc_ifdef", "preproc_function_def"],
fold_bodies: NONE,
imports: &["preproc_include"],
@@ -123,6 +150,7 @@ pub(crate) static SPECS: &[Spec] = &[
name: "cpp",
language: tree_sitter_cpp::LANGUAGE,
outline: outline!("cpp"),
highlights: None,
fold_nodes: &["preproc_if", "preproc_ifdef", "preproc_function_def", "raw_string_literal"],
fold_bodies: NONE,
imports: &["preproc_include", "using_declaration"],
@@ -132,6 +160,7 @@ pub(crate) static SPECS: &[Spec] = &[
name: "csharp",
language: tree_sitter_c_sharp::LANGUAGE,
outline: outline!("csharp"),
highlights: None,
fold_nodes: &["preproc_region", "raw_string_literal", "verbatim_string_literal"],
fold_bodies: NONE,
imports: &["using_directive"],
@@ -141,6 +170,7 @@ pub(crate) static SPECS: &[Spec] = &[
name: "swift",
language: tree_sitter_swift::LANGUAGE,
outline: outline!("swift"),
highlights: None,
// Control-flow statements hold `{ statements }` without a block node of their own.
fold_nodes: &[
"multi_line_string_literal",
@@ -160,6 +190,7 @@ pub(crate) static SPECS: &[Spec] = &[
name: "ruby",
language: tree_sitter_ruby::LANGUAGE,
outline: outline!("ruby"),
highlights: None,
fold_nodes: &[
"method",
"singleton_method",
@@ -185,6 +216,7 @@ pub(crate) static SPECS: &[Spec] = &[
name: "php",
language: tree_sitter_php::LANGUAGE_PHP,
outline: outline!("php"),
highlights: None,
fold_nodes: &["heredoc", "nowdoc"],
fold_bodies: NONE,
imports: &["namespace_use_declaration"],
@@ -194,6 +226,7 @@ pub(crate) static SPECS: &[Spec] = &[
name: "lua",
language: tree_sitter_lua::LANGUAGE,
outline: outline!("lua"),
highlights: None,
fold_nodes: &[
"function_declaration",
"function_definition",
@@ -212,6 +245,7 @@ pub(crate) static SPECS: &[Spec] = &[
name: "dart",
language: tree_sitter_dart::LANGUAGE,
outline: outline!("dart"),
highlights: None,
fold_nodes: NONE,
fold_bodies: NONE,
imports: &["import_or_export", "library_name", "part_directive", "part_of_directive"],
@@ -221,6 +255,7 @@ pub(crate) static SPECS: &[Spec] = &[
name: "zig",
language: tree_sitter_zig::LANGUAGE,
outline: outline!("zig"),
highlights: Some(Highlights { query: tree_sitter_zig::HIGHLIGHTS_QUERY, first_wins: false }),
fold_nodes: NONE,
fold_bodies: NONE,
imports: NONE,
@@ -230,6 +265,7 @@ pub(crate) static SPECS: &[Spec] = &[
name: "elixir",
language: tree_sitter_elixir::LANGUAGE,
outline: outline!("elixir"),
highlights: Some(Highlights { query: tree_sitter_elixir::HIGHLIGHTS_QUERY, first_wins: false }),
fold_nodes: &["do_block", "anonymous_function", "string", "sigil"],
fold_bodies: NONE,
imports: NONE,
@@ -239,6 +275,7 @@ pub(crate) static SPECS: &[Spec] = &[
name: "haskell",
language: tree_sitter_haskell::LANGUAGE,
outline: outline!("haskell"),
highlights: None,
// `bind`: equations without arguments (`main = do …`).
fold_nodes: &["function", "bind", "data_type", "newtype", "class", "instance", "signature"],
fold_bodies: NONE,
@@ -249,6 +286,7 @@ pub(crate) static SPECS: &[Spec] = &[
name: "ocaml",
language: tree_sitter_ocaml::LANGUAGE_OCAML,
outline: outline!("ocaml"),
highlights: None,
fold_nodes: &[
"value_definition",
"type_definition",
@@ -266,6 +304,7 @@ pub(crate) static SPECS: &[Spec] = &[
name: "ocaml_interface",
language: tree_sitter_ocaml::LANGUAGE_OCAML_INTERFACE,
outline: outline!("ocaml_interface"),
highlights: None,
fold_nodes: &["module_definition", "module_type_definition", "signature", "type_definition"],
fold_bodies: NONE,
imports: &["open_module"],
@@ -275,6 +314,7 @@ pub(crate) static SPECS: &[Spec] = &[
name: "bash",
language: tree_sitter_bash::LANGUAGE,
outline: outline!("bash"),
highlights: None,
fold_nodes: &["do_group", "if_statement", "case_statement", "heredoc_body"],
fold_bodies: NONE,
imports: NONE,
@@ -284,6 +324,7 @@ pub(crate) static SPECS: &[Spec] = &[
name: "html",
language: tree_sitter_html::LANGUAGE,
outline: outline!("html"),
highlights: None,
fold_nodes: &["element", "script_element", "style_element"],
fold_bodies: NONE,
imports: NONE,
@@ -293,6 +334,7 @@ pub(crate) static SPECS: &[Spec] = &[
name: "xml",
language: tree_sitter_xml::LANGUAGE_XML,
outline: outline!("xml"),
highlights: None,
fold_nodes: &["element", "CDSect"],
fold_bodies: NONE,
imports: NONE,
@@ -302,6 +344,7 @@ pub(crate) static SPECS: &[Spec] = &[
name: "css",
language: tree_sitter_css::LANGUAGE,
outline: outline!("css"),
highlights: None,
fold_nodes: NONE,
fold_bodies: NONE,
imports: &["import_statement"],
@@ -311,6 +354,7 @@ pub(crate) static SPECS: &[Spec] = &[
name: "json",
language: tree_sitter_json::LANGUAGE,
outline: outline!("json"),
highlights: None,
fold_nodes: NONE,
fold_bodies: NONE,
imports: NONE,
@@ -320,6 +364,7 @@ pub(crate) static SPECS: &[Spec] = &[
name: "yaml",
language: tree_sitter_yaml::LANGUAGE,
outline: outline!("yaml"),
highlights: None,
fold_nodes: &["block_mapping_pair", "block_sequence_item", "block_scalar"],
fold_bodies: NONE,
imports: NONE,
@@ -329,6 +374,7 @@ pub(crate) static SPECS: &[Spec] = &[
name: "toml",
language: tree_sitter_toml_ng::LANGUAGE,
outline: outline!("toml"),
highlights: None,
fold_nodes: &["table", "table_array_element", "string"],
fold_bodies: NONE,
imports: NONE,
@@ -338,6 +384,7 @@ pub(crate) static SPECS: &[Spec] = &[
name: "markdown",
language: tree_sitter_md::LANGUAGE,
outline: outline!("markdown"),
highlights: None,
fold_nodes: &["section", "fenced_code_block", "list", "block_quote", "html_block"],
fold_bodies: NONE,
imports: NONE,
@@ -347,6 +394,7 @@ pub(crate) static SPECS: &[Spec] = &[
name: "hcl",
language: tree_sitter_hcl::LANGUAGE,
outline: outline!("hcl"),
highlights: Some(Highlights { query: highlights!("hcl"), first_wins: false }),
fold_nodes: &["block", "heredoc_template"],
fold_bodies: NONE,
imports: NONE,
@@ -356,6 +404,7 @@ pub(crate) static SPECS: &[Spec] = &[
name: "nix",
language: tree_sitter_nix::LANGUAGE,
outline: outline!("nix"),
highlights: Some(Highlights { query: tree_sitter_nix::HIGHLIGHTS_QUERY, first_wins: true }),
fold_nodes: &["let_expression", "indented_string_expression"],
fold_bodies: NONE,
imports: NONE,
@@ -365,6 +414,7 @@ pub(crate) static SPECS: &[Spec] = &[
name: "proto",
language: tree_sitter_proto::LANGUAGE,
outline: outline!("proto"),
highlights: None,
fold_nodes: NONE,
fold_bodies: NONE,
imports: &["import"],
@@ -374,6 +424,7 @@ pub(crate) static SPECS: &[Spec] = &[
name: "graphql",
language: tree_sitter_graphql::LANGUAGE,
outline: outline!("graphql"),
highlights: Some(Highlights { query: highlights!("graphql"), first_wins: false }),
fold_nodes: NONE,
fold_bodies: NONE,
imports: NONE,
@@ -383,6 +434,7 @@ pub(crate) static SPECS: &[Spec] = &[
name: "make",
language: tree_sitter_make::LANGUAGE,
outline: outline!("make"),
highlights: Some(Highlights { query: tree_sitter_make::HIGHLIGHTS_QUERY, first_wins: false }),
fold_nodes: &["rule", "conditional", "define_directive"],
fold_bodies: NONE,
imports: &["include_directive"],
@@ -392,6 +444,7 @@ pub(crate) static SPECS: &[Spec] = &[
name: "cmake",
language: tree_sitter_cmake::LANGUAGE,
outline: outline!("cmake"),
highlights: None,
fold_nodes: &["function_def", "macro_def", "if_condition", "foreach_loop", "while_loop", "block_def"],
fold_bodies: NONE,
imports: NONE,
+483
Переглянути файл
@@ -0,0 +1,483 @@
//! Syntax highlighting from a grammar's own `highlights.scm`, for languages the
//! UI has no CodeMirror mode for.
//!
//! Capture names follow the nvim-treesitter / Zed conventions (`@keyword`,
//! `@string.special.symbol`, ...) and are folded into [`SyntaxHighlightKind`] by
//! their longest known dotted prefix. Overlaps resolve the way those editors
//! do: a smaller node wins over the node containing it, and for the same node
//! the later pattern wins (the first one for tree-sitter CLI style queries). `@embedded` (string interpolation) clears the
//! surrounding colour. Besides tree-sitter's own text predicates, nvim's
//! `#lua-match?` is understood; patterns with other predicates never match.
use super::lines::LineIndex;
use serde::{Deserialize, Serialize};
use specta::Type;
use tree_sitter::{Language, Query, QueryCursor, QueryMatch, QueryPredicateArg, StreamingIterator, Tree};
/// Highlight classes sent to the UI, which maps each onto a Lezer tag.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum SyntaxHighlightKind {
Keyword,
String,
StringSpecial,
Escape,
Regexp,
Atom,
Number,
Constant,
Comment,
DocComment,
Function,
FunctionCall,
Builtin,
Type,
Namespace,
Variable,
SelfVariable,
Property,
Attribute,
Macro,
Label,
Tag,
Operator,
Punctuation,
}
impl SyntaxHighlightKind {
/// Every kind, in `as u32` order: the legend for [`SyntaxHighlights::data`].
pub const ALL: [Self; 24] = [
Self::Keyword,
Self::String,
Self::StringSpecial,
Self::Escape,
Self::Regexp,
Self::Atom,
Self::Number,
Self::Constant,
Self::Comment,
Self::DocComment,
Self::Function,
Self::FunctionCall,
Self::Builtin,
Self::Type,
Self::Namespace,
Self::Variable,
Self::SelfVariable,
Self::Property,
Self::Attribute,
Self::Macro,
Self::Label,
Self::Tag,
Self::Operator,
Self::Punctuation,
];
}
/// Highlighted ranges of a whole document, packed like LSP semantic tokens.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct SyntaxHighlights {
/// Legend: `data` kind `i` is `kinds[i]`.
pub kinds: Vec<SyntaxHighlightKind>,
/// `[from, to, kind]` triples: sorted, non-overlapping UTF-16 offsets.
pub data: Vec<u32>,
}
impl SyntaxHighlights {
pub(crate) fn new(data: Vec<u32>) -> Self {
Self { kinds: SyntaxHighlightKind::ALL.to_vec(), data }
}
}
/// What a capture paints over its node.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Paint {
Kind(SyntaxHighlightKind),
/// `@embedded`: code inside a string, uncoloured unless captured itself.
Clear,
}
/// Capture name prefixes, most specific first within each family.
const CAPTURES: &[(&str, Paint)] = {
use Paint::{Clear, Kind};
use SyntaxHighlightKind as K;
&[
("embedded", Clear),
("keyword", Kind(K::Keyword)),
("include", Kind(K::Keyword)),
("import", Kind(K::Keyword)),
("conditional", Kind(K::Keyword)),
("repeat", Kind(K::Keyword)),
("exception", Kind(K::Keyword)),
("boolean", Kind(K::Keyword)),
("string.escape", Kind(K::Escape)),
("escape", Kind(K::Escape)),
("string.regex", Kind(K::Regexp)),
("string.regexp", Kind(K::Regexp)),
("string.special.symbol", Kind(K::Atom)),
("symbol", Kind(K::Atom)),
("string.special", Kind(K::StringSpecial)),
("string", Kind(K::String)),
("character", Kind(K::String)),
("number", Kind(K::Number)),
("float", Kind(K::Number)),
("constant.builtin", Kind(K::Constant)),
("constant.macro", Kind(K::Macro)),
("constant", Kind(K::Constant)),
// nvim greys out unused bindings (`_acc`); IDEA shows them as variables.
("comment.unused", Kind(K::Variable)),
("comment.doc", Kind(K::DocComment)),
("comment.documentation", Kind(K::DocComment)),
("comment", Kind(K::Comment)),
("function.builtin", Kind(K::Builtin)),
("function.macro", Kind(K::Macro)),
("function.definition", Kind(K::Function)),
("function", Kind(K::FunctionCall)),
("method", Kind(K::FunctionCall)),
("constructor", Kind(K::Type)),
("type.builtin", Kind(K::Builtin)),
("type", Kind(K::Type)),
("module", Kind(K::Namespace)),
("namespace", Kind(K::Namespace)),
("variable.builtin", Kind(K::SelfVariable)),
("variable.member", Kind(K::Property)),
("variable.field", Kind(K::Property)),
("variable", Kind(K::Variable)),
("parameter", Kind(K::Variable)),
("property", Kind(K::Property)),
("field", Kind(K::Property)),
("attribute", Kind(K::Attribute)),
("label", Kind(K::Label)),
("tag", Kind(K::Tag)),
("operator", Kind(K::Operator)),
("punctuation", Kind(K::Punctuation)),
]
};
/// The paint for a capture name: its longest prefix (on `.` boundaries) in
/// [`CAPTURES`]. Private captures (`@__name__`) and unknown names paint nothing.
fn paint_for(name: &str) -> Option<Paint> {
if name.starts_with('_') {
return None;
}
let mut prefix = name;
loop {
if let Some((_, p)) = CAPTURES.iter().find(|(n, _)| *n == prefix) {
return Some(*p);
}
prefix = &prefix[..prefix.rfind('.')?];
}
}
/// A predicate tree-sitter leaves to the caller.
enum Check {
/// `#lua-match?` / `#not-lua-match?` on a capture's text.
Matches {
capture: u32,
regex: regex_lite::Regex,
negate: bool,
},
Unsupported,
}
pub(crate) struct HighlightQuery {
query: Query,
/// By capture index.
paints: Vec<Option<Paint>>,
/// By pattern index.
checks: Vec<Vec<Check>>,
first_wins: bool,
}
impl HighlightQuery {
pub(crate) fn new(language: &Language, source: &str, first_wins: bool) -> Result<Self, tree_sitter::QueryError> {
let query = Query::new(language, source)?;
let paints = query.capture_names().iter().map(|n| paint_for(n)).collect();
let checks = (0..query.pattern_count())
.map(|i| {
query
.general_predicates(i)
.iter()
.filter_map(|p| match (&*p.operator, &*p.args) {
// Locals are not tracked: builtins are assumed not to be shadowed.
("is-not?", [QueryPredicateArg::String(s)]) if &**s == "local" => None,
(
op @ ("lua-match?" | "not-lua-match?"),
[QueryPredicateArg::Capture(c), QueryPredicateArg::String(pat)],
) => Some(match regex_lite::Regex::new(&lua_pattern_to_regex(pat)) {
Ok(regex) => Check::Matches { capture: *c, regex, negate: op.starts_with("not-") },
Err(_) => Check::Unsupported,
}),
_ => Some(Check::Unsupported),
})
.collect()
})
.collect();
Ok(Self { query, paints, checks, first_wins })
}
fn accepts(&self, m: &QueryMatch<'_, '_>, text: &str) -> bool {
self.checks[m.pattern_index].iter().all(|check| match check {
Check::Matches { capture, regex, negate } => m
.captures
.iter()
.filter(|c| c.index == *capture)
.all(|c| regex.is_match(&text[c.node.byte_range()]) != *negate),
Check::Unsupported => false,
})
}
}
/// Translates the Lua patterns used by nvim queries (`^[A-Z][A-Z_0-9]+$`, `^//!`) to regex syntax.
fn lua_pattern_to_regex(pat: &str) -> String {
let class = |c: char| match c {
'a' => Some("A-Za-z"),
'd' => Some("0-9"),
'l' => Some("a-z"),
'u' => Some("A-Z"),
'w' => Some("A-Za-z0-9"),
's' => Some("\\s"),
'x' => Some("0-9A-Fa-f"),
'p' => Some("[:punct:]"),
_ => None,
};
let mut out = String::with_capacity(pat.len() + 8);
let mut in_set = false;
let mut chars = pat.chars();
while let Some(c) = chars.next() {
match c {
'%' => {
let Some(next) = chars.next() else { break };
match class(next) {
Some(set) if in_set => out.push_str(set),
Some(set) => {
out.push('[');
out.push_str(set);
out.push(']');
}
None => out.push_str(&regex_lite::escape(&next.to_string())),
}
}
'[' if !in_set => {
in_set = true;
out.push(c);
}
']' if in_set => {
in_set = false;
out.push(c);
}
// Lua's lazy `*` (inside a set, `-` is a range).
'-' if !in_set => out.push_str("*?"),
'\\' | '{' | '}' | '|' => {
out.push('\\');
out.push(c);
}
_ => out.push(c),
}
}
out
}
/// Byte value for "no colour" in the paint buffer; kinds are `1 + index`.
const NONE: u8 = 0;
/// `[from, to, kind]` UTF-16 triples for `text`; see [`SyntaxHighlights::data`].
pub(crate) fn highlights(q: &HighlightQuery, tree: &Tree, text: &str) -> Vec<u32> {
// (byte len, rank, start, end, paint): painted largest first, then by rank,
// so inner nodes and winning patterns overwrite.
let mut captures: Vec<(usize, usize, usize, usize, Paint)> = Vec::new();
let mut cursor = QueryCursor::new();
let mut matches = cursor.matches(&q.query, tree.root_node(), text.as_bytes());
while let Some(m) = matches.next() {
if !q.accepts(m, text) {
continue;
}
for c in m.captures {
if let Some(paint) = q.paints[c.index as usize] {
let r = c.node.byte_range();
if r.start < r.end {
let rank = if q.first_wins { usize::MAX - m.pattern_index } else { m.pattern_index };
captures.push((r.end - r.start, rank, r.start, r.end, paint));
}
}
}
}
captures.sort_by(|a, b| b.0.cmp(&a.0).then(a.1.cmp(&b.1)));
let mut painted = vec![NONE; text.len()];
for &(_, _, start, end, paint) in &captures {
let v = match paint {
Paint::Kind(k) => 1 + k as u8,
Paint::Clear => NONE,
};
painted[start..end].fill(v);
}
let lines = LineIndex::new(text);
let mut data = Vec::new();
let mut i = 0;
while i < painted.len() {
let v = painted[i];
let start = i;
while i < painted.len() && painted[i] == v {
i += 1;
}
// Node boundaries are char boundaries; whitespace-only runs stay uncoloured.
if v != NONE && text.is_char_boundary(start) && text.is_char_boundary(i) && !text[start..i].trim().is_empty() {
data.extend([lines.utf16_at(start) as u32, lines.utf16_at(i) as u32, (v - 1) as u32]);
}
}
data
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn capture_names_fold_to_the_longest_known_prefix() {
use SyntaxHighlightKind as K;
assert_eq!(paint_for("keyword.function"), Some(Paint::Kind(K::Keyword)));
assert_eq!(paint_for("string.special.symbol"), Some(Paint::Kind(K::Atom)));
assert_eq!(paint_for("string.special.path"), Some(Paint::Kind(K::StringSpecial)));
assert_eq!(paint_for("comment.doc.__attribute__"), Some(Paint::Kind(K::DocComment)));
assert_eq!(paint_for("punctuation.bracket"), Some(Paint::Kind(K::Punctuation)));
assert_eq!(paint_for("embedded"), Some(Paint::Clear));
assert_eq!(paint_for("__name__"), None);
assert_eq!(paint_for("spell"), None);
}
/// `(text, kind)` of every highlighted range.
fn spans(lang: &str, text: &str) -> Vec<(String, SyntaxHighlightKind)> {
let h = crate::Syntax::new().highlights(&ide_core::LanguageId::new(lang), text).unwrap();
let units: Vec<u16> = text.encode_utf16().collect();
h.data
.chunks(3)
.map(|t| (String::from_utf16(&units[t[0] as usize..t[1] as usize]).unwrap(), h.kinds[t[2] as usize]))
.collect()
}
#[test]
fn highlights_elixir() {
use SyntaxHighlightKind as K;
let src = "defmodule Greeter do\n @moduledoc \"Hi\"\n # 😀 note\n def hello(name, _opts) do\n IO.puts(\"Hello #{name}\")\n :ok\n end\nend\n";
let got = spans("elixir", src);
let kind = |t: &str| got.iter().find(|(s, _)| s == t).map(|(_, k)| *k);
assert_eq!(kind("defmodule"), Some(K::Keyword));
assert_eq!(kind("Greeter"), Some(K::Namespace));
assert_eq!(kind("\"Hi\""), Some(K::DocComment));
assert_eq!(kind("# 😀 note"), Some(K::Comment));
assert_eq!(kind("def"), Some(K::Keyword));
assert_eq!(kind("hello"), Some(K::FunctionCall));
assert_eq!(kind("_opts"), Some(K::Variable));
assert_eq!(kind("puts"), Some(K::FunctionCall));
// Interpolation clears the string colour; its contents are coloured on their own.
assert_eq!(kind("\"Hello "), Some(K::String));
assert_eq!(kind("#{"), Some(K::Punctuation));
assert_eq!(kind(":ok"), Some(K::Atom));
assert_eq!(kind("end"), Some(K::Keyword));
// Sorted and non-overlapping.
let h = crate::Syntax::new().highlights(&ide_core::LanguageId::new("elixir"), src).unwrap();
assert!(h.data.chunks(3).zip(h.data.chunks(3).skip(1)).all(|(a, b)| a[0] < a[1] && a[1] <= b[0]));
}
#[test]
fn highlights_other_grammar_only_languages() {
use SyntaxHighlightKind as K;
type Expect<'a> = &'a [(&'a str, SyntaxHighlightKind)];
let cases: &[(&str, &str, Expect)] = &[
(
"zig",
"const std = @import(\"std\");\n// hi\npub fn main() void {\n var x: u32 = 42;\n _ = x;\n}\n",
&[
("const", K::Keyword),
("\"std\"", K::String),
("// hi", K::Comment),
("42", K::Number),
("u32", K::Builtin),
],
),
(
"nix",
"{ pkgs ? import <nixpkgs> {} }:\n# hi\nlet x = 1; in pkgs.mkShell { name = \"dev\"; }\n",
&[
("let", K::Keyword),
("# hi", K::Comment),
("1", K::Number),
("\"dev\"", K::String),
("import", K::Builtin),
],
),
(
"graphql",
"# hi\nquery Hero($id: ID!) @cached {\n hero(id: $id) { name ...Friends }\n}\nenum Episode { NEWHOPE }\n",
&[
("# hi", K::Comment),
("query", K::Keyword),
("Hero", K::FunctionCall),
("$id", K::Variable),
("ID", K::Type),
("@cached", K::Attribute),
("name", K::Property),
("Friends", K::FunctionCall),
("NEWHOPE", K::Constant),
],
),
(
"hcl",
"# hi\nresource \"aws_instance\" \"web\" {\n ami = var.ami\n count = 2\n tags = { Name = \"web-${var.env}\" }\n name = upper(\"x\")\n}\n",
&[
("# hi", K::Comment),
("resource", K::Keyword),
("aws_instance", K::Type),
("ami", K::Property),
("2", K::Number),
("upper", K::FunctionCall),
("\"web-", K::String),
("env", K::Property),
("var", K::Variable),
],
),
("make", "# hi\nCC := gcc\nall: main.o\n\t$(CC) -o app main.o\n", &[("# hi", K::Comment)]),
];
for (lang, src, expect) in cases {
let got = spans(lang, src);
for (text, kind) in *expect {
assert!(got.iter().any(|(s, k)| s == text && k == kind), "{lang}: {text:?} as {kind:?} in {got:?}");
}
}
}
#[test]
fn languages_without_a_query_have_none() {
assert_eq!(crate::Syntax::new().highlights(&ide_core::LanguageId::new("rust"), "fn a() {}"), None);
}
#[test]
fn every_highlights_query_compiles() {
for spec in super::super::grammars::SPECS {
if let Some(h) = &spec.highlights {
let lang = Language::new(spec.language);
if let Err(e) = HighlightQuery::new(&lang, h.query, h.first_wins) {
panic!("{}: {e}", spec.name);
}
}
}
}
#[test]
fn lua_patterns_translate() {
assert_eq!(lua_pattern_to_regex("^[A-Z][A-Z_0-9]+$"), "^[A-Z][A-Z_0-9]+$");
assert_eq!(lua_pattern_to_regex("^//!"), "^//!");
assert_eq!(lua_pattern_to_regex("^%u[%w_]*$"), "^[A-Z][A-Za-z0-9_]*$");
assert_eq!(lua_pattern_to_regex("a.-b%."), "a.*?b\\.");
}
#[test]
fn legend_matches_discriminants() {
for (i, k) in SyntaxHighlightKind::ALL.iter().enumerate() {
assert_eq!(*k as usize, i);
}
}
}
+1 -1
Переглянути файл
@@ -40,7 +40,7 @@ impl<'a> LineIndex<'a> {
}
/// UTF-16 offset of a char-boundary byte offset.
fn utf16_at(&self, byte: usize) -> usize {
pub(crate) fn utf16_at(&self, byte: usize) -> usize {
if self.checkpoints.is_empty() {
return byte;
}
+23 -1
Переглянути файл
@@ -1,8 +1,9 @@
//! Tree-sitter driven structure: outline, folding, symbol tags, selection ranges.
//! Tree-sitter driven structure: outline, folding, symbol tags, selection ranges, highlighting.
mod cache;
mod folding;
mod grammars;
mod highlight;
pub(crate) mod lines;
mod outline;
mod selection;
@@ -10,6 +11,7 @@ mod selection;
use crate::{FoldRange, LanguageConfig, LanguageRegistry, SymbolTag};
pub use cache::{MAX_CACHED_TREES, SyntaxCache, SyntaxCacheStats};
use grammars::{SPECS, Spec};
pub use highlight::{SyntaxHighlightKind, SyntaxHighlights};
use ide_core::{LanguageId, OutlineItem, Range};
use std::cell::RefCell;
use std::collections::HashMap;
@@ -31,6 +33,7 @@ pub(crate) struct Grammar {
pub(crate) spec: &'static Spec,
pub(crate) language: Language,
outline: OnceLock<Option<outline::OutlineQuery>>,
highlights: OnceLock<Option<highlight::HighlightQuery>>,
kinds: OnceLock<folding::KindTable>,
}
@@ -50,6 +53,17 @@ impl Grammar {
})
.as_ref()
}
fn highlight_query(&self) -> Option<&highlight::HighlightQuery> {
self.highlights
.get_or_init(|| {
let h = self.spec.highlights.as_ref()?;
highlight::HighlightQuery::new(&self.language, h.query, h.first_wins)
.inspect_err(|e| tracing::error!("highlights query for {} is invalid: {e}", self.spec.name))
.ok()
})
.as_ref()
}
}
thread_local! {
@@ -72,6 +86,7 @@ impl Syntax {
spec,
language: Language::new(spec.language),
outline: OnceLock::new(),
highlights: OnceLock::new(),
kinds: OnceLock::new(),
})
.collect();
@@ -150,6 +165,13 @@ impl Syntax {
.unwrap_or_default()
}
/// Highlighting from the grammar's own query; `None` without one.
pub fn highlights(&self, lang: &LanguageId, text: &str) -> Option<SyntaxHighlights> {
self.analyze(lang, text, |g, tree, text| {
Some(SyntaxHighlights::new(highlight::highlights(g.highlight_query()?, tree, text)))
})
}
/// Syntax-aware selection ranges for IDEA "Extend Selection" (⌥↑), innermost first.
pub fn selection_ranges(&self, lang: &LanguageId, text: &str, offset_utf16: u32) -> Vec<Range> {
match self.analyze(lang, text, |_, tree, text| Some(selection::selection_ranges(tree, text, offset_utf16))) {
+82
Переглянути файл
@@ -24,6 +24,10 @@ const BUILD_TIMEOUT: Duration = Duration::from_secs(300);
const COMMAND_TIMEOUT: Duration = Duration::from_secs(120);
/// How long to retry while the project is still being imported.
const IMPORT_WAIT: Duration = Duration::from_secs(90);
/// Compile errors listed with a launch; the rest are only counted.
const MAX_LAUNCH_ERRORS: usize = 10;
/// Build markers can be published just after `java/buildWorkspace` answers.
const ERRORS_WAIT: Duration = Duration::from_secs(2);
/// Result of `java/buildWorkspace` (jdtls `BuildWorkspaceStatus`).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
@@ -70,6 +74,43 @@ pub struct JavaLaunchInfo {
pub java_home: Option<ide_core::IpcPath>,
/// The `java` launcher to use (filled in by the caller from the installed JDKs).
pub java_exec: Option<String>,
/// First compile errors of the workspace when the build had errors.
pub errors: Vec<JavaCompileError>,
/// All compile errors (`errors` is capped).
pub error_count: u32,
/// Likely causes of the errors worth telling the user (e.g. a missing Lombok agent).
pub hints: Vec<String>,
}
/// One error diagnostic; `line` / `column` are 1-based for display.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct JavaCompileError {
pub path: ide_core::IpcPath,
pub line: u32,
pub column: u32,
pub message: String,
}
/// Error diagnostics sorted by file and position, capped at `limit`, and their total.
pub fn compile_errors(
diagnostics: Vec<(PathBuf, lsp_types::Diagnostic)>,
limit: usize,
) -> (Vec<JavaCompileError>, u32) {
let mut errors: Vec<JavaCompileError> = diagnostics
.into_iter()
.filter(|(_, d)| d.severity == Some(lsp_types::DiagnosticSeverity::ERROR))
.map(|(path, d)| JavaCompileError {
path: path.into(),
line: d.range.start.line + 1,
column: d.range.start.character + 1,
message: d.message.lines().next().unwrap_or_default().to_owned(),
})
.collect();
errors.sort_by(|a, b| (&a.path, a.line, a.column).cmp(&(&b.path, b.line, b.column)));
let count = u32::try_from(errors.len()).unwrap_or(u32::MAX);
errors.truncate(limit);
(errors, count)
}
/// `java.project.getClasspaths` result.
@@ -210,6 +251,10 @@ impl LspManager {
/// Builds (when asked), then resolves the classpath and JDK of the module at `module`.
pub async fn java_launch(&self, module: &Path, test: bool, build: bool) -> IdeResult<JavaLaunchInfo> {
let build = if build { Some(self.java_build(module).await?) } else { None };
let (errors, error_count) = match build {
Some(JavaBuildStatus::WithErrors | JavaBuildStatus::Failed) => self.java_compile_errors(module).await,
_ => (Vec::new(), 0),
};
let cp = self.java_classpath(module, test).await?;
let java_home = match self.java_vm_location(module).await {
Ok(home) => home,
@@ -225,9 +270,24 @@ impl LspManager {
module_paths: cp.module_paths,
java_home: java_home.map(Into::into),
java_exec: None,
errors,
error_count,
hints: Vec::new(),
})
}
/// Compile errors jdtls reports for its workspace (all modules it imported).
async fn java_compile_errors(&self, module: &Path) -> (Vec<JavaCompileError>, u32) {
let Ok((server, _)) = self.jdtls(module).await else { return (Vec::new(), 0) };
let collect = || compile_errors(server.diagnostics_snapshot(), MAX_LAUNCH_ERRORS);
let found = collect();
if found.1 > 0 {
return found;
}
let _ = tokio::time::timeout(ERRORS_WAIT, server.published_notify.notified()).await;
collect()
}
/// Starts (or reuses) java-debug's DAP server inside jdtls and returns its port.
pub async fn java_debug_server(&self, path: &Path) -> IdeResult<u16> {
let v = self.jdtls_command(path, "vscode.java.startDebugSession", Vec::new()).await.map_err(|e| {
@@ -256,6 +316,28 @@ impl LspManager {
mod tests {
use super::*;
#[test]
fn launch_errors_are_sorted_and_capped() {
let diag = |line: u32, severity, message: &str| lsp_types::Diagnostic {
range: lsp_types::Range::new(lsp_types::Position::new(line, 4), lsp_types::Position::new(line, 9)),
severity: Some(severity),
message: message.into(),
..Default::default()
};
let (errors, count) = compile_errors(
vec![
(PathBuf::from("/p/B.java"), diag(1, lsp_types::DiagnosticSeverity::ERROR, "b")),
(PathBuf::from("/p/A.java"), diag(9, lsp_types::DiagnosticSeverity::ERROR, "a2\nmore")),
(PathBuf::from("/p/A.java"), diag(2, lsp_types::DiagnosticSeverity::WARNING, "warning")),
(PathBuf::from("/p/A.java"), diag(3, lsp_types::DiagnosticSeverity::ERROR, "a1")),
],
2,
);
assert_eq!(count, 3);
let shown: Vec<(u32, u32, &str)> = errors.iter().map(|e| (e.line, e.column, e.message.as_str())).collect();
assert_eq!(shown, [(4, 5, "a1"), (10, 5, "a2")]);
}
#[test]
fn classpaths() {
let v = json!({
+6
Переглянути файл
@@ -330,6 +330,12 @@ impl Server {
self.diagnostics.lock().get(path).cloned().unwrap_or_default()
}
/// Every published diagnostic, by file.
pub fn diagnostics_snapshot(&self) -> Vec<(PathBuf, lsp::Diagnostic)> {
let d = self.diagnostics.lock();
d.iter().flat_map(|(p, items)| items.iter().map(move |i| (p.clone(), i.clone()))).collect()
}
pub fn take_diagnostic_paths(&self) -> Vec<PathBuf> {
self.published.lock().clear();
self.diagnostics.lock().drain().map(|(p, _)| p).collect()
+1
Переглянути файл
@@ -15,6 +15,7 @@ serde_json.workspace = true
specta.workspace = true
toml.workspace = true
tracing.workspace = true
zip = { version = "=2.4.2", default-features = false, features = ["deflate"] }
[dev-dependencies]
tempfile.workspace = true
+85 -2
Переглянути файл
@@ -16,7 +16,7 @@ fn non_empty(s: &str) -> Option<&str> {
}
/// Resolves `~/` and project-relative paths of a setting.
fn setting_path(root: &Path, s: &str) -> Option<PathBuf> {
pub fn setting_path(root: &Path, s: &str) -> Option<PathBuf> {
let s = non_empty(s)?;
let p = match s.strip_prefix("~/") {
Some(rest) => crate::home_dir()?.join(rest),
@@ -56,6 +56,55 @@ fn goroot(root: &Path, s: &Settings) -> Option<PathBuf> {
setting_path(root, &s.languages.go.goroot)
}
/// The project JDK (`languages.java.jdk`): a JDK home, its `bin` or its `bin/java`.
pub fn project_jdk(root: &Path, s: &Settings) -> Option<crate::java::Jdk> {
let p = setting_path(root, &s.languages.java.jdk)?;
let jdk = p.ancestors().take(3).find_map(crate::java::jdk_at);
if jdk.is_none() {
tracing::warn!("project JDK {} is not a JDK home", p.display());
}
jdk
}
/// `mvn` of the configured Maven home (`languages.java.maven.home`): the
/// executable itself, `<home>/bin/mvn` or `<bin>/mvn`.
pub fn maven_command(root: &Path, s: &Settings) -> Option<PathBuf> {
let p = setting_path(root, &s.languages.java.maven.home)?;
let name = if cfg!(windows) { "mvn.cmd" } else { "mvn" };
let found = [p.clone(), p.join("bin").join(name), p.join(name)].into_iter().find(|c| c.is_file());
if found.is_none() {
tracing::warn!("Maven home {} has no {name}", p.display());
}
found
}
/// Maven options from settings, placed before the goals: `-s <settings.xml>`
/// and `-Dmaven.repo.local=<dir>`.
pub fn maven_options(root: &Path, s: &Settings) -> Vec<String> {
let m = &s.languages.java.maven;
let mut out = Vec::new();
if let Some(file) = setting_path(root, &m.user_settings) {
out.extend(["-s".to_owned(), file.to_string_lossy().into_owned()]);
}
if let Some(dir) = setting_path(root, &m.local_repository) {
out.push(format!("-Dmaven.repo.local={}", dir.to_string_lossy()));
}
out
}
/// The Maven local repository from settings: the configured one, else
/// `<localRepository>` of the configured user `settings.xml`; `None` = Maven's default.
pub fn maven_local_repository(root: &Path, s: &Settings) -> Option<PathBuf> {
let m = &s.languages.java.maven;
setting_path(root, &m.local_repository).or_else(|| {
let text = std::fs::read_to_string(setting_path(root, &m.user_settings)?).ok()?;
let repo = crate::java::xml_value(&crate::lombok::strip_xml_comments(&text), "localRepository")?;
let home = crate::home_dir().map(|h| h.to_string_lossy().into_owned()).unwrap_or_default();
let repo = repo.replace("${user.home}", &home);
(!repo.is_empty() && !repo.contains("${")).then(|| PathBuf::from(repo))
})
}
/// TypeScript `lib` directory for the selected version; `None` = the server's bundled one.
pub fn tsdk(root: &Path, s: &Settings) -> Option<PathBuf> {
match s.languages.typescript.version.trim() {
@@ -104,6 +153,9 @@ pub(crate) fn merge_init_options(cfg: &mut LanguageServerConfig, layer: Value) {
/// server settings (`python.pythonPath`, rust-analyzer `check.command`, `typescript.tsdk`).
/// `root` is the project root, `server_root` the server's workspace root.
pub fn configure_server(cfg: &mut LanguageServerConfig, root: &Path, server_root: &Path, s: &Settings) {
if let Some(custom) = s.tool_path(&cfg.command).and_then(|p| setting_path(root, p)) {
cfg.command = custom.to_string_lossy().into_owned();
}
let mut path_dirs: Vec<PathBuf> = Vec::new();
let name = cfg.name.clone();
let name = name.as_str();
@@ -166,6 +218,20 @@ pub fn configure_server(cfg: &mut LanguageServerConfig, root: &Path, server_root
}
}
if name == "jdtls" {
// The jdtls launcher forwards `--jvm-arg=` values to the JVM it starts.
let args = s.languages.java.jdtls_vm_args.split_whitespace().map(|a| format!("--jvm-arg={a}"));
cfg.args.extend(args);
// m2e (the Maven import) reads mirrors, servers and `<localRepository>` from it.
if let Some(file) = setting_path(root, &s.languages.java.maven.user_settings) {
let file = file.to_string_lossy();
merge_init_options(
cfg,
json!({ "settings": { "java": { "configuration": { "maven": { "userSettings": file } } } } }),
);
}
}
if let Some(lib) = tsdk(server_root, s).or_else(|| tsdk(root, s)) {
let lib_s = lib.to_string_lossy().into_owned();
match name {
@@ -200,7 +266,8 @@ const PY_RUNNERS: [&str; 3] = ["uv", "poetry", "pdm"];
/// Points run configurations at the selected toolchains: Python configs use the
/// project interpreter, npm scripts the chosen package manager and Node.js,
/// cargo / go configs the selected toolchain.
/// cargo / go configs the selected toolchain, Maven / Gradle the project JDK
/// (and Maven the configured home and options).
pub fn apply_to_run_configs(configs: &mut [RunConfig], root: &Path, s: &Settings) {
let explicit_python = setting_path(root, &s.languages.python.interpreter);
let python = python_interpreter(root, s);
@@ -209,6 +276,9 @@ pub fn apply_to_run_configs(configs: &mut [RunConfig], root: &Path, s: &Settings
let rust = rust_bin(root, s);
let go = goroot(root, s);
let gopath = setting_path(root, &s.languages.go.gopath);
let jdk = project_jdk(root, s);
let mvn = maven_command(root, s);
let mvn_options = maven_options(root, s);
for c in configs.iter_mut() {
let mut path_dirs: Vec<PathBuf> = Vec::new();
@@ -275,6 +345,19 @@ pub fn apply_to_run_configs(configs: &mut [RunConfig], root: &Path, s: &Settings
c.env.entry("GOPATH".into()).or_insert_with(|| gopath.to_string_lossy().into_owned());
}
}
"maven" | "gradle" => {
if let Some(jdk) = &jdk {
c.env.entry("JAVA_HOME".into()).or_insert_with(|| jdk.home.to_string_lossy().into_owned());
}
if c.kind == "maven" && c.detected {
if let Some(mvn) = &mvn {
c.command = mvn.to_string_lossy().into_owned();
}
if !c.args.starts_with(&mvn_options) {
c.args.splice(0..0, mvn_options.iter().cloned());
}
}
}
_ => {}
}
if !path_dirs.is_empty() && !c.env.contains_key("PATH") {
+107
Переглянути файл
@@ -18,6 +18,8 @@ pub fn detect(kind: SdkKind, root: Option<&Path>) -> Vec<Sdk> {
SdkKind::Rust => rust(),
SdkKind::Go => go(),
SdkKind::TypeScript => typescript(root),
SdkKind::Jdk => jdk(),
SdkKind::Maven => maven(),
}
}
@@ -382,3 +384,108 @@ fn typescript(root: Option<&Path>) -> Vec<Sdk> {
}
out
}
// ------------------------------------------------------------------ jdk
/// `KEY="value"` of a JDK `release` file.
fn release_value(release: &str, key: &str) -> Option<String> {
let line = release.lines().find_map(|l| l.trim().strip_prefix(key)?.strip_prefix('='))?;
Some(line.trim().trim_matches('"').to_owned()).filter(|v| !v.is_empty())
}
fn jdk() -> Vec<Sdk> {
let java_home = std::env::var_os("JAVA_HOME").and_then(|h| dunce::canonicalize(h).ok());
crate::java::rescan_jdks()
.iter()
.map(|j| {
let release = std::fs::read_to_string(j.home.join("release")).unwrap_or_default();
let version = release_value(&release, "JAVA_VERSION").unwrap_or_else(|| j.major.to_string());
let name = match release_value(&release, "IMPLEMENTOR") {
Some(vendor) => format!("{vendor} {version}"),
None => format!("JDK {version}"),
};
let source = if java_home.as_ref() == Some(&j.home) { "JAVA_HOME" } else { "system" };
Sdk {
path: j.home.clone().into(),
name,
version: Some(version),
source: source.to_owned(),
home: Some(j.home.clone().into()),
extra: None,
}
})
.collect()
}
// ------------------------------------------------------------------ maven
/// Maven version from `lib/maven-core-<version>.jar`.
fn maven_version(home: &Path) -> Option<String> {
std::fs::read_dir(home.join("lib")).ok()?.flatten().find_map(|e| {
let name = e.file_name().to_string_lossy().into_owned();
Some(name.strip_prefix("maven-core-")?.strip_suffix(".jar")?.to_owned())
})
}
/// A Maven home (`bin/mvn` and `lib/`); Homebrew's formula keeps it in `libexec`.
fn maven_home(dir: &Path) -> Option<PathBuf> {
let mvn = if cfg!(windows) { "mvn.cmd" } else { "mvn" };
[dir.join("libexec"), dir.to_path_buf()]
.into_iter()
.find(|h| h.join("bin").join(mvn).is_file() && h.join("lib").is_dir())
}
fn maven() -> Vec<Sdk> {
let mut found: Vec<(PathBuf, &'static str)> = Vec::new();
// Windows' Maven ships `mvn.cmd` only (`which` looks for `mvn.exe`).
let on_path = if cfg!(windows) {
std::env::split_paths(&search_path()).map(|d| d.join("mvn.cmd")).find(|p| p.is_file())
} else {
which("mvn")
};
if let Some(mvn) = on_path.and_then(|p| dunce::canonicalize(p).ok())
&& let Some(home) = mvn.parent().and_then(Path::parent)
{
found.push((home.to_path_buf(), "path"));
}
for var in ["MAVEN_HOME", "M2_HOME"] {
if let Some(h) = std::env::var_os(var) {
found.push((PathBuf::from(h), "env"));
}
}
for p in ["/opt/homebrew/opt/maven", "/usr/local/opt/maven", "/usr/share/maven", "/opt/maven"] {
found.push((PathBuf::from(p), "system"));
}
if let Some(home) = home_dir() {
for d in subdirs(&home.join(".sdkman/candidates/maven")) {
found.push((d, "sdkman"));
}
// Distributions the Maven wrapper downloaded: `dists/apache-maven-3.9.6-bin/<hash>/apache-maven-3.9.6`,
// or since wrapper 3.3 the home itself, `dists/apache-maven-3.9.6/<hash>`.
for dist in subdirs(&home.join(".m2/wrapper/dists")) {
for hash in subdirs(&dist) {
found.extend(subdirs(&hash).into_iter().map(|d| (d, "wrapper")));
found.push((hash, "wrapper"));
}
}
}
let mut seen = HashSet::new();
let mut out = Vec::new();
for (dir, source) in found {
let Some(home) = maven_home(&dir) else { continue };
let home = dunce::canonicalize(&home).unwrap_or(home);
if !seen.insert(home.clone()) {
continue;
}
let version = maven_version(&home);
out.push(Sdk {
path: home.clone().into(),
name: format!("Maven {}", version.clone().unwrap_or_default()).trim().to_owned(),
version,
source: source.to_owned(),
home: Some(home.into()),
extra: None,
});
}
out
}
+240 -27
Переглянути файл
@@ -25,7 +25,8 @@ pub fn parse_release(release: &str) -> Option<u32> {
if first == 1 { parts.next()?.parse().ok() } else { Some(first) }
}
fn jdk_at(home: &Path) -> Option<Jdk> {
/// The JDK at `home`, if it is one (a `release` file and `bin/java`).
pub fn jdk_at(home: &Path) -> Option<Jdk> {
let release = std::fs::read_to_string(home.join("release")).ok()?;
if !home.join("bin").join(crate::exe("java")).is_file() {
return None;
@@ -117,6 +118,11 @@ fn rescan(slot: &mut Option<Scan>) -> Arc<[Jdk]> {
slot.insert(Scan { at: Instant::now(), jdks: scan().into() }).jdks.clone()
}
/// Scans for installed JDKs again (Settings › Detect again).
pub fn rescan_jdks() -> Arc<[Jdk]> {
rescan(&mut JDKS.lock().unwrap_or_else(|e| e.into_inner()))
}
/// Installed JDKs (scanned on first use; [`jdtls_jdks`] may refresh them).
pub fn installed_jdks() -> Arc<[Jdk]> {
let mut slot = JDKS.lock().unwrap_or_else(|e| e.into_inner());
@@ -126,23 +132,101 @@ pub fn installed_jdks() -> Arc<[Jdk]> {
}
}
/// Like [`installed_jdks`], but while none can run jdtls the list is rescanned
/// (at most every [`RESCAN_AFTER`]), so a JDK installed after startup is picked
/// up when the server is restarted.
pub fn jdtls_jdks() -> Arc<[Jdk]> {
/// Like [`installed_jdks`], but while none can run jdtls (on Java `min_java`)
/// the list is rescanned (at most every [`RESCAN_AFTER`]), so a JDK installed
/// after startup is picked up when the server is restarted.
pub fn jdtls_jdks(min_java: u32) -> Arc<[Jdk]> {
let mut slot = JDKS.lock().unwrap_or_else(|e| e.into_inner());
match &*slot {
Some(s) if jdtls_runtime(&s.jdks).is_some() || s.at.elapsed() < RESCAN_AFTER => s.jdks.clone(),
Some(s) if jdtls_runtime(&s.jdks, min_java).is_some() || s.at.elapsed() < RESCAN_AFTER => s.jdks.clone(),
_ => rescan(&mut slot),
}
}
/// Oldest Java version jdtls itself runs on (projects may target older ones).
/// Oldest Java version jdtls runs on when its install can't tell (its launcher's check).
pub const JDTLS_MIN_JAVA: u32 = 21;
/// The JDK to run jdtls with: the first found that is new enough (`JAVA_HOME` wins).
pub fn jdtls_runtime(jdks: &[Jdk]) -> Option<&Jdk> {
jdks.iter().find(|j| j.major >= JDTLS_MIN_JAVA)
pub fn jdtls_runtime(jdks: &[Jdk], min_java: u32) -> Option<&Jdk> {
jdks.iter().find(|j| j.major >= min_java)
}
/// The Java version the jdtls that `cfg` launches needs: the highest any of its
/// bundles requires, never below [`JDTLS_MIN_JAVA`]. Its launcher only checks
/// for 21, but the Eclipse platform it ships moves on (1.63 needs 25), and on
/// an older JDK the server dies resolving its bundles.
pub fn jdtls_min_java(cfg: &LanguageServerConfig) -> u32 {
let search = cfg.env.get("PATH").map(std::ffi::OsString::from).or_else(|| std::env::var_os("PATH"));
let required = search
.and_then(|s| ide_run::which::find_executable(&cfg.command, &s))
.and_then(|exe| dunce::canonicalize(exe).ok())
.and_then(|exe| Some(exe.parent()?.parent()?.to_path_buf()))
.and_then(|home| bundles_min_java(&home));
required.map_or(JDTLS_MIN_JAVA, |v| v.max(JDTLS_MIN_JAVA))
}
/// Per install: (plugins directory mtime, its requirement).
static BUNDLE_JAVA: Mutex<BTreeMap<PathBuf, (std::time::SystemTime, Option<u32>)>> = Mutex::new(BTreeMap::new());
/// Highest Java version required by the bundles in `home`'s `plugins` (or Homebrew's
/// `libexec/plugins`); `None` when there are none to read.
fn bundles_min_java(home: &Path) -> Option<u32> {
let plugins = [home.join("plugins"), home.join("libexec").join("plugins")].into_iter().find(|p| p.is_dir())?;
let modified = std::fs::metadata(&plugins).and_then(|m| m.modified()).ok()?;
let mut cache = BUNDLE_JAVA.lock().unwrap_or_else(|e| e.into_inner());
if let Some((at, v)) = cache.get(&plugins)
&& *at == modified
{
return *v;
}
let required = std::fs::read_dir(&plugins)
.ok()?
.filter_map(Result::ok)
.map(|e| e.path())
.filter(|p| p.extension().is_some_and(|x| x == "jar"))
.filter_map(|jar| jar_manifest(&jar))
.filter_map(|manifest| manifest_min_java(&manifest))
.max();
cache.insert(plugins, (modified, required));
required
}
fn jar_manifest(jar: &Path) -> Option<String> {
use std::io::Read;
let mut zip = zip::ZipArchive::new(std::fs::File::open(jar).ok()?).ok()?;
let mut entry = zip.by_name("META-INF/MANIFEST.MF").ok()?;
let mut text = String::new();
entry.read_to_string(&mut text).ok()?;
Some(text)
}
/// The Java version an OSGi bundle manifest requires: its `osgi.ee` capability
/// (`version=25`), else the oldest of its `Bundle-RequiredExecutionEnvironment`s.
fn manifest_min_java(manifest: &str) -> Option<u32> {
// Long headers continue on lines starting with a space.
let mut headers: Vec<String> = Vec::new();
for line in manifest.lines() {
match (line.strip_prefix(' '), headers.last_mut()) {
(Some(rest), Some(last)) => last.push_str(rest),
_ => headers.push(line.to_owned()),
}
}
let header = |name: &str| headers.iter().find_map(|h| h.strip_prefix(name)?.strip_prefix(':')).map(str::trim);
if let Some(caps) = header("Require-Capability") {
let ee = caps.split(',').filter(|c| c.trim_start().starts_with("osgi.ee")).find_map(|c| {
let v = c.split("version=").nth(1)?;
let digits: String = v.chars().take_while(char::is_ascii_digit).collect();
digits.parse::<u32>().ok()
});
if ee.is_some() {
return ee;
}
}
header("Bundle-RequiredExecutionEnvironment")?
.split(',')
.filter_map(|ee| ee.trim().strip_prefix("JavaSE-"))
.filter_map(|v| if v == "1.8" { Some(8) } else { v.parse().ok() })
.min()
}
/// jdtls `java.configuration.runtimes`: one JDK per Java version (the first
@@ -178,21 +262,35 @@ const METADATA_PROPERTY: &str = "java.import.generatesMetadataFilesAtProjectRoot
/// jdtls: its Eclipse workspace (`-data`) lives under the IDE's data
/// directory, one per server root, and no Eclipse metadata is written into
/// the project; it runs on a JDK 21+ (via `JAVA_HOME`, which its launcher
/// reads), installed JDKs are registered as runtimes and `bundles` (e.g. the
/// java-debug plugin jar) are loaded into the server.
/// the project; it runs on a JDK `min_java`+ (via `JAVA_HOME`, which its
/// launcher reads), installed JDKs are registered as runtimes and `bundles`
/// (e.g. the java-debug plugin jar) are loaded into the server. The project
/// JDK, when set, is the default runtime and preferred for running the server.
#[allow(clippy::too_many_arguments)]
pub fn configure_jdtls(
cfg: &mut LanguageServerConfig,
server_root: &Path,
data_dir: &Path,
jdks: &[Jdk],
project_jdk: Option<&Jdk>,
min_java: u32,
bundles: &[PathBuf],
lombok: Option<&Path>,
) {
if cfg.name != "jdtls" {
return;
}
// A Lombok agent from the user's JVM arguments wins.
let own_agent = crate::lombok::agent_in_args(cfg.args.iter().map(String::as_str));
let agent = own_agent.as_deref().or(lombok);
if !cfg.args.iter().any(|a| a == "-data") {
let dir = data_dir.join("lsp").join("jdtls").join(path_key(server_root));
// ECJ builds incrementally: classes compiled without (or with another) Lombok
// agent would be kept, so each agent gets its own workspace and a full build.
let key = match agent {
Some(jar) => format!("{}-{}", path_key(server_root), path_key(jar)),
None => path_key(server_root),
};
let dir = data_dir.join("lsp").join("jdtls").join(key);
cfg.args.extend(["-data".to_owned(), dir.to_string_lossy().into_owned()]);
}
// jdtls reads this one as a system property (its file-system bundle
@@ -200,15 +298,31 @@ pub fn configure_jdtls(
if !cfg.args.iter().any(|a| a.contains(METADATA_PROPERTY)) {
cfg.args.push(format!("--jvm-arg=-D{METADATA_PROPERTY}=false"));
}
if own_agent.is_none()
&& let Some(jar) = lombok
{
cfg.args.push(format!("--jvm-arg=-javaagent:{}", jar.to_string_lossy()));
}
let jdks: Vec<Jdk> =
project_jdk.into_iter().chain(jdks.iter().filter(|j| Some(*j) != project_jdk)).cloned().collect();
let jdks = jdks.as_slice();
if !cfg.env.contains_key("JAVA_HOME") {
match jdtls_runtime(jdks) {
match jdtls_runtime(jdks, min_java) {
Some(jdk) => {
cfg.env.insert("JAVA_HOME".to_owned(), jdk.home.to_string_lossy().into_owned());
}
None => cfg.launch_error = Some(missing_runtime_message(jdks)),
None => cfg.launch_error = Some(missing_runtime_message(jdks, min_java)),
}
}
let mut runtimes = runtimes(jdks);
if let Some(project) = project_jdk {
let home = project.home.to_string_lossy();
for r in &mut runtimes {
if r["path"] == *home {
r["default"] = json!(true);
}
}
}
let runtimes = runtimes(jdks);
if !runtimes.is_empty() {
merge_init_options(cfg, json!({ "settings": { "java": { "configuration": { "runtimes": runtimes } } } }));
}
@@ -218,7 +332,7 @@ pub fn configure_jdtls(
}
}
fn missing_runtime_message(jdks: &[Jdk]) -> String {
fn missing_runtime_message(jdks: &[Jdk], min_java: u32) -> String {
let mut found: Vec<u32> = jdks.iter().map(|j| j.major).collect();
found.sort_unstable();
found.dedup();
@@ -229,7 +343,7 @@ fn missing_runtime_message(jdks: &[Jdk]) -> String {
format!("found JDK {}", list.join(", "))
};
format!(
"jdtls needs JDK {JDTLS_MIN_JAVA} or newer to run ({found}). Install one (or point JAVA_HOME at it) and \
"jdtls needs JDK {min_java} or newer to run ({found}). Install one (or point JAVA_HOME at it) and \
restart the server; the project can still target an older Java version."
)
}
@@ -290,7 +404,7 @@ pub fn project_java_version(module_dir: &Path) -> Option<u32> {
None
}
fn xml_value(text: &str, tag: &str) -> Option<String> {
pub(crate) fn xml_value(text: &str, tag: &str) -> Option<String> {
let open = format!("<{tag}>");
let start = text.find(&open)? + open.len();
let end = text[start..].find('<')?;
@@ -330,7 +444,16 @@ mod tests {
Jdk { major: 8, home: PathBuf::from("/jdk8") },
];
let bundles = [PathBuf::from("/tools/java-debug/bin/com.microsoft.java.debug.plugin.jar")];
configure_jdtls(&mut cfg, Path::new("/p/demo"), Path::new("/data"), &jdks, &bundles);
configure_jdtls(
&mut cfg,
Path::new("/p/demo"),
Path::new("/data"),
&jdks,
None,
JDTLS_MIN_JAVA,
&bundles,
None,
);
assert_eq!(cfg.args[0], "-data");
assert!(cfg.args[1].starts_with("/data/lsp/jdtls/"), "{}", cfg.args[1]);
assert_eq!(cfg.args[2], "--jvm-arg=-Djava.import.generatesMetadataFilesAtProjectRoot=false");
@@ -345,36 +468,126 @@ mod tests {
// Deterministic (reconfigure compares configs) and idempotent.
let before = cfg.clone();
configure_jdtls(&mut cfg, Path::new("/p/demo"), Path::new("/data"), &jdks, &bundles);
configure_jdtls(
&mut cfg,
Path::new("/p/demo"),
Path::new("/data"),
&jdks,
None,
JDTLS_MIN_JAVA,
&bundles,
None,
);
assert_eq!(cfg, before);
// The project JDK is the default runtime, and runs the server when new enough.
let project = Jdk { major: 21, home: PathBuf::from("/jdk21b") };
let mut cfg: LanguageServerConfig = toml::from_str("name = \"jdtls\"\ncommand = \"jdtls\"").unwrap();
configure_jdtls(
&mut cfg,
Path::new("/p"),
Path::new("/data"),
&jdks,
Some(&project),
JDTLS_MIN_JAVA,
&[],
None,
);
let opts = serde_json::to_value(cfg.initialization_options.clone().unwrap()).unwrap();
let rt = &opts["settings"]["java"]["configuration"]["runtimes"];
assert_eq!(rt[1], json!({ "name": "JavaSE-21", "path": "/jdk21b", "default": true }));
assert_eq!(cfg.env["JAVA_HOME"], "/jdk21b");
let mut other: LanguageServerConfig = toml::from_str("name = \"pyright\"\ncommand = \"x\"").unwrap();
configure_jdtls(&mut other, Path::new("/p"), Path::new("/data"), &jdks, &bundles);
configure_jdtls(&mut other, Path::new("/p"), Path::new("/data"), &jdks, None, JDTLS_MIN_JAVA, &bundles, None);
assert!(other.args.is_empty() && other.initialization_options.is_none());
}
#[test]
fn jdtls_needs_a_jdk_21_to_run() {
fn jdtls_lombok_agent() {
let jdtls = || -> LanguageServerConfig { toml::from_str("name = \"jdtls\"\ncommand = \"jdtls\"").unwrap() };
let jar = Path::new("/m2/lombok-1.18.48.jar");
let mut cfg = jdtls();
configure_jdtls(&mut cfg, Path::new("/p"), Path::new("/data"), &[], None, JDTLS_MIN_JAVA, &[], Some(jar));
let agent = format!("--jvm-arg=-javaagent:{}", jar.to_string_lossy());
assert!(cfg.args.contains(&agent), "{:?}", cfg.args);
let mut plain = jdtls();
configure_jdtls(&mut plain, Path::new("/p"), Path::new("/data"), &[], None, JDTLS_MIN_JAVA, &[], None);
assert_ne!(cfg.args[1], plain.args[1], "a separate workspace, so everything is rebuilt with the agent");
let before = cfg.clone();
configure_jdtls(&mut cfg, Path::new("/p"), Path::new("/data"), &[], None, JDTLS_MIN_JAVA, &[], Some(jar));
assert_eq!(cfg, before, "idempotent");
let mut cfg = jdtls();
cfg.args.push("--jvm-arg=-javaagent:/own/lombok.jar".into());
configure_jdtls(&mut cfg, Path::new("/p"), Path::new("/data"), &[], None, JDTLS_MIN_JAVA, &[], Some(jar));
assert!(!cfg.args.contains(&agent), "the user's agent wins");
let mut own = jdtls();
own.args.push("--jvm-arg=-javaagent:/own/lombok.jar".into());
configure_jdtls(&mut own, Path::new("/p"), Path::new("/data"), &[], None, JDTLS_MIN_JAVA, &[], None);
assert_eq!(cfg.args, own.args, "its workspace follows the agent in use");
}
#[test]
fn jdtls_needs_a_new_enough_jdk_to_run() {
let jdtls = || -> LanguageServerConfig { toml::from_str("name = \"jdtls\"\ncommand = \"jdtls\"").unwrap() };
let old = [Jdk { major: 17, home: PathBuf::from("/jdk17") }, Jdk { major: 8, home: PathBuf::from("/jdk8") }];
let mut cfg = jdtls();
configure_jdtls(&mut cfg, Path::new("/p"), Path::new("/data"), &old, &[]);
configure_jdtls(&mut cfg, Path::new("/p"), Path::new("/data"), &old, None, JDTLS_MIN_JAVA, &[], None);
assert!(!cfg.env.contains_key("JAVA_HOME"));
let err = cfg.launch_error.unwrap();
assert!(err.contains("JDK 21 or newer") && err.contains("found JDK 8, 17"), "{err}");
let mut cfg = jdtls();
configure_jdtls(&mut cfg, Path::new("/p"), Path::new("/data"), &[], &[]);
configure_jdtls(&mut cfg, Path::new("/p"), Path::new("/data"), &[], None, JDTLS_MIN_JAVA, &[], None);
assert!(cfg.launch_error.unwrap().contains("no JDK was found"));
// An explicit JAVA_HOME is the user's call.
let mut cfg = jdtls();
cfg.env.insert("JAVA_HOME".into(), "/custom".into());
configure_jdtls(&mut cfg, Path::new("/p"), Path::new("/data"), &old, &[]);
configure_jdtls(&mut cfg, Path::new("/p"), Path::new("/data"), &old, None, JDTLS_MIN_JAVA, &[], None);
assert_eq!((cfg.env["JAVA_HOME"].as_str(), cfg.launch_error), ("/custom", None));
let mixed = [old[0].clone(), Jdk { major: 21, home: PathBuf::from("/jdk21") }];
assert_eq!(jdtls_runtime(&mixed).unwrap().major, 21);
assert_eq!(jdtls_runtime(&mixed, 21).unwrap().major, 21);
// A jdtls whose bundles need 25 doesn't start on 21, and says what it needs.
let mut cfg = jdtls();
configure_jdtls(&mut cfg, Path::new("/p"), Path::new("/data"), &mixed, None, 25, &[], None);
let err = cfg.launch_error.unwrap();
assert!(err.contains("JDK 25 or newer") && err.contains("found JDK 17, 21"), "{err}");
}
#[test]
fn bundle_manifests_give_the_java_jdtls_needs() {
let ee = |m: &str| manifest_min_java(m);
assert_eq!(ee("Bundle-RequiredExecutionEnvironment: JavaSE-25\n"), Some(25));
assert_eq!(ee("Bundle-RequiredExecutionEnvironment: JavaSE-17, JavaSE-1.8\n"), Some(8));
// The capability wins, also when folded over continuation lines.
let folded = "Require-Capability: osgi.service;filter:=\"(x=1)\",osgi.ee;filter:=\"(&(osgi.ee=Ja\r\n \
vaSE)(version=21))\"\r\nBundle-RequiredExecutionEnvironment: JavaSE-17\r\n";
assert_eq!(ee(folded), Some(21));
assert_eq!(ee("Bundle-Name: x\n"), None);
let home = tempfile::tempdir().unwrap();
let plugins = home.path().join("plugins");
std::fs::create_dir(&plugins).unwrap();
let jar = |name: &str, manifest: &str| {
let mut zip = zip::ZipWriter::new(std::fs::File::create(plugins.join(name)).unwrap());
let opts = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored);
zip.start_file("META-INF/MANIFEST.MF", opts).unwrap();
std::io::Write::write_all(&mut zip, manifest.as_bytes()).unwrap();
zip.finish().unwrap();
};
jar(
"org.eclipse.jdt.ls.core_1.63.0.jar",
"Require-Capability: osgi.ee;filter:=\"(&(osgi.ee=JavaSE)(version=21))\"\n",
);
jar("org.eclipse.core.filesystem_1.12.0.jar", "Bundle-RequiredExecutionEnvironment: JavaSE-25\n");
jar("plain.jar", "Manifest-Version: 1.0\n");
std::fs::write(plugins.join("notes.txt"), "not a jar").unwrap();
assert_eq!(bundles_min_java(home.path()), Some(25));
assert_eq!(bundles_min_java(&home.path().join("missing")), None);
}
#[test]
+5
Переглянути файл
@@ -10,6 +10,7 @@ mod discover;
mod exec;
pub mod java;
pub mod locate;
pub mod lombok;
pub mod python;
use serde::{Deserialize, Serialize};
@@ -30,6 +31,10 @@ pub enum SdkKind {
Rust,
Go,
TypeScript,
/// JDK homes.
Jdk,
/// Maven homes.
Maven,
}
/// One installed interpreter / toolchain.
+278
Переглянути файл
@@ -0,0 +1,278 @@
//! Lombok for jdtls: ECJ only generates Lombok members when the language
//! server's JVM runs `-javaagent:lombok.jar`, so a project using Lombok gets the
//! newest jar available, managed (installed by the IDE) or in the Maven / Gradle caches.
use crate::home_dir;
use std::path::{Path, PathBuf};
/// Oldest Lombok whose ECJ handlers work in current jdtls builds (Eclipse 2024-06 support);
/// older ones throw `NoSuchMethodError` and drop every annotation of the compilation unit.
pub const LOMBOK_MIN: [u32; 3] = [1, 18, 34];
/// What a jdtls instance gets for Lombok.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum LombokAgent {
/// The project doesn't use Lombok.
Unused,
/// The project uses Lombok but no jar was found.
Missing,
Found {
jar: PathBuf,
/// `None` for the managed jar (the latest release when installed).
version: Option<String>,
},
}
impl LombokAgent {
pub fn jar(&self) -> Option<&Path> {
match self {
Self::Found { jar, .. } => Some(jar),
_ => None,
}
}
/// Too old for current jdtls.
pub fn outdated(&self) -> bool {
matches!(self, Self::Found { version: Some(v), .. } if parse_version(v).is_some_and(|v| v < LOMBOK_MIN))
}
/// Why Lombok-generated members may be missing, if they may be.
pub fn problem(&self) -> Option<String> {
const INSTALL: &str =
"Install Lombok in Settings › Languages & Frameworks › Language Servers (jdtls restarts with it)";
match self {
Self::Missing => Some(format!(
"The project uses Lombok, but no lombok.jar was found for the Java language server, so Lombok-generated \
members are missing. {INSTALL}."
)),
Self::Found { version: Some(v), .. } if self.outdated() => Some(format!(
"Lombok {v} is too old for the Java language server (needs {}.{}.{} or newer): classes using it may \
miss generated members. {INSTALL}.",
LOMBOK_MIN[0], LOMBOK_MIN[1], LOMBOK_MIN[2]
)),
_ => None,
}
}
}
/// The Lombok jar of a `-javaagent:` among JVM arguments (bare or as `--jvm-arg=`).
pub fn agent_in_args<'a>(args: impl IntoIterator<Item = &'a str>) -> Option<PathBuf> {
args.into_iter().find_map(|a| {
let jar = a.split_once("-javaagent:")?.1;
jar.to_ascii_lowercase().contains("lombok").then(|| PathBuf::from(jar))
})
}
/// The Lombok agent for the project at `root`: the user's own (`own`, from the JVM
/// options) wins, then `managed` (the IDE-installed jar), then the build caches
/// (`maven_repo`, the configured Maven local repository, else the default one).
pub fn lombok_agent(
root: &Path,
own: Option<PathBuf>,
managed: Option<PathBuf>,
maven_repo: Option<PathBuf>,
) -> LombokAgent {
if let Some(jar) = own {
let version = jar
.file_stem()
.and_then(|s| s.to_str()?.strip_prefix("lombok-"))
.filter(|v| parse_version(v).is_some())
.map(str::to_owned);
return LombokAgent::Found { jar, version };
}
if !uses_lombok(root) {
return LombokAgent::Unused;
}
if let Some(jar) = managed {
return LombokAgent::Found { jar, version: None };
}
let home = home_dir();
let mut dirs = Vec::new();
if let Some(repo) = maven_repo.or_else(|| maven_repository(home.as_deref())) {
dirs.push(repo.join("org").join("projectlombok").join("lombok"));
}
if let Some(gradle) =
std::env::var_os("GRADLE_USER_HOME").map(PathBuf::from).or_else(|| home.map(|h| h.join(".gradle")))
{
dirs.push(gradle.join("caches").join("modules-2").join("files-2.1").join("org.projectlombok").join("lombok"));
}
match newest_cached(&dirs) {
Some((version, jar)) => LombokAgent::Found { jar, version: Some(version) },
None => LombokAgent::Missing,
}
}
/// Build files under `root` (a few levels, for multi-module builds) mentioning Lombok.
pub fn uses_lombok(root: &Path) -> bool {
const FILES: [&str; 4] = ["pom.xml", "build.gradle", "build.gradle.kts", "libs.versions.toml"];
const SKIP: [&str; 7] = ["target", "build", "node_modules", "out", "bin", "src", ".gradle"];
fn walk(dir: &Path, depth: usize) -> bool {
if dir.join("lombok.config").is_file() {
return true;
}
let Ok(entries) = std::fs::read_dir(dir) else { return false };
let mut subdirs = Vec::new();
for e in entries.flatten() {
let name = e.file_name();
let name = name.to_string_lossy();
let Ok(ty) = e.file_type() else { continue };
if ty.is_dir() {
if depth > 0 && !name.starts_with('.') && !SKIP.contains(&name.as_ref()) {
subdirs.push(e.path());
}
} else if FILES.contains(&name.as_ref())
&& std::fs::read_to_string(e.path()).is_ok_and(|t| t.contains("lombok"))
{
return true;
}
}
subdirs.iter().any(|d| walk(d, depth - 1))
}
// `gradle/libs.versions.toml` sits one level down, modules usually no deeper than three.
walk(root, 3)
}
/// `<localRepository>` of `~/.m2/settings.xml`, else `~/.m2/repository`.
fn maven_repository(home: Option<&Path>) -> Option<PathBuf> {
let m2 = home?.join(".m2");
let custom = std::fs::read_to_string(m2.join("settings.xml"))
.ok()
.and_then(|s| crate::java::xml_value(&strip_xml_comments(&s), "localRepository"))
.filter(|v| !v.is_empty() && !v.contains("${"))
.map(PathBuf::from);
Some(custom.unwrap_or_else(|| m2.join("repository")))
}
pub(crate) fn strip_xml_comments(text: &str) -> String {
let mut out = String::with_capacity(text.len());
let mut rest = text;
while let Some(i) = rest.find("<!--") {
out.push_str(&rest[..i]);
rest = rest[i..].find("-->").map_or("", |j| &rest[i + j + 3..]);
}
out.push_str(rest);
out
}
/// Highest release `<dir>/<version>/…/lombok-<version>.jar` (Maven: directly in
/// the version directory; Gradle: one hash directory below it).
fn newest_cached(dirs: &[PathBuf]) -> Option<(String, PathBuf)> {
let mut best: Option<([u32; 3], String, PathBuf)> = None;
for dir in dirs {
let Ok(entries) = std::fs::read_dir(dir) else { continue };
for e in entries.flatten() {
let version = e.file_name().to_string_lossy().into_owned();
let Some(parsed) = parse_version(&version) else { continue };
if best.as_ref().is_some_and(|(b, ..)| *b >= parsed) {
continue;
}
let name = format!("lombok-{version}.jar");
let direct = e.path().join(&name);
let jar = if direct.is_file() {
Some(direct)
} else {
std::fs::read_dir(e.path())
.into_iter()
.flatten()
.flatten()
.map(|h| h.path().join(&name))
.find(|p| p.is_file())
};
if let Some(jar) = jar {
best = Some((parsed, version, jar));
}
}
}
best.map(|(_, v, jar)| (v, jar))
}
/// `1.18.34` → `[1, 18, 34]`; snapshots and other qualifiers don't count as releases.
fn parse_version(v: &str) -> Option<[u32; 3]> {
let mut parts = v.split('.').map(|p| p.parse::<u32>().ok());
let out = [parts.next()??, parts.next()??, parts.next().unwrap_or(Some(0))?];
parts.next().is_none().then_some(out)
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs;
#[test]
fn detects_lombok_in_build_files() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
fs::write(root.join("pom.xml"), "<project><modules><module>api</module></modules></project>").unwrap();
assert!(!uses_lombok(root));
fs::create_dir_all(root.join("api/src/main")).unwrap();
fs::write(root.join("api/src/main/pom.xml"), "<artifactId>lombok</artifactId>").unwrap();
assert!(!uses_lombok(root), "sources are not scanned");
fs::write(root.join("api/pom.xml"), "<artifactId>lombok</artifactId>").unwrap();
assert!(uses_lombok(root));
let gradle = tempfile::tempdir().unwrap();
fs::create_dir_all(gradle.path().join("gradle")).unwrap();
fs::write(gradle.path().join("gradle/libs.versions.toml"), "lombok = \"org.projectlombok:lombok:1.18.30\"")
.unwrap();
assert!(uses_lombok(gradle.path()));
}
#[test]
fn picks_the_newest_cached_release() {
let tmp = tempfile::tempdir().unwrap();
let m2 = tmp.path().join("m2");
let gradle = tmp.path().join("gradle");
for v in ["1.18.26", "1.18.36", "1.18.99-SNAPSHOT"] {
fs::create_dir_all(m2.join(v)).unwrap();
fs::write(m2.join(v).join(format!("lombok-{v}.jar")), b"PK").unwrap();
}
fs::create_dir_all(m2.join("1.18.40")).unwrap(); // only a .pom: not usable
fs::create_dir_all(gradle.join("1.18.38/abc123")).unwrap();
fs::write(gradle.join("1.18.38/abc123/lombok-1.18.38.jar"), b"PK").unwrap();
let (v, jar) = newest_cached(&[m2.clone(), gradle.clone()]).unwrap();
assert_eq!(v, "1.18.38");
assert_eq!(jar, gradle.join("1.18.38/abc123/lombok-1.18.38.jar"));
assert_eq!(newest_cached(std::slice::from_ref(&m2)).unwrap().0, "1.18.36");
assert_eq!(newest_cached(&[tmp.path().join("none")]), None);
}
#[test]
fn old_versions_are_reported() {
let found = |v: Option<&str>| LombokAgent::Found { jar: "/l.jar".into(), version: v.map(Into::into) };
assert!(found(Some("1.18.26")).outdated());
assert!(found(Some("1.18.26")).problem().unwrap().contains("1.18.26 is too old"));
assert!(!found(Some("1.18.34")).outdated());
assert_eq!(found(None).problem(), None);
assert!(LombokAgent::Missing.problem().is_some());
assert_eq!(LombokAgent::Unused.problem(), None);
assert_eq!(parse_version("1.18"), Some([1, 18, 0]));
assert_eq!(parse_version("edge-SNAPSHOT"), None);
}
#[test]
fn the_users_agent_wins() {
let tmp = tempfile::tempdir().unwrap();
let own = agent_in_args(["--jvm-arg=-Xmx2g", "--jvm-arg=-javaagent:/opt/lombok-1.18.26.jar"]);
assert_eq!(own.as_deref(), Some(Path::new("/opt/lombok-1.18.26.jar")));
assert_eq!(agent_in_args(["-javaagent:/opt/other.jar"]), None);
let agent = lombok_agent(tmp.path(), own, Some("/managed/lombok.jar".into()), None);
assert_eq!(agent.jar(), Some(Path::new("/opt/lombok-1.18.26.jar")));
assert!(agent.outdated(), "its version is read from the file name");
let plain = lombok_agent(tmp.path(), agent_in_args(["-javaagent:/opt/lombok.jar"]), None, None);
assert_eq!(plain.problem(), None, "a user agent is never reported missing");
}
#[test]
fn maven_settings_local_repository() {
let tmp = tempfile::tempdir().unwrap();
let home = tmp.path();
assert_eq!(maven_repository(Some(home)), Some(home.join(".m2/repository")));
fs::create_dir_all(home.join(".m2")).unwrap();
fs::write(
home.join(".m2/settings.xml"),
"<settings><!-- <localRepository>/old</localRepository> --><localRepository>/repo</localRepository></settings>",
)
.unwrap();
assert_eq!(maven_repository(Some(home)), Some(PathBuf::from("/repo")));
}
}
+76 -2
Переглянути файл
@@ -1,4 +1,7 @@
use crate::apply::{apply_to_run_configs, configure_server, python_interpreter, terminal_activation, tsdk};
use crate::apply::{
apply_to_run_configs, configure_server, maven_command, maven_options, project_jdk, python_interpreter,
terminal_activation, tsdk,
};
use crate::python::parse_pip_list;
use crate::{bin_dir, exe, venv_of};
use ide_core::settings::Settings;
@@ -74,6 +77,16 @@ fn pyright_gets_python_path_and_venv_env() {
assert!(cfg.env["PATH"].starts_with(&*tmp.path().join(".venv").join(bin_dir()).to_string_lossy()));
}
#[test]
fn jdtls_vm_args() {
let tmp = tempfile::tempdir().unwrap();
let mut s = Settings::default();
s.languages.java.jdtls_vm_args = " -Xmx2g -javaagent:/opt/lombok.jar ".into();
let mut cfg = server("jdtls");
configure_server(&mut cfg, tmp.path(), tmp.path(), &s);
assert_eq!(cfg.args, ["--jvm-arg=-Xmx2g", "--jvm-arg=-javaagent:/opt/lombok.jar"]);
}
#[test]
fn rust_analyzer_check_command_and_toolchain() {
if cfg!(windows) {
@@ -143,6 +156,52 @@ fn run_configs_use_selected_interpreter_and_package_manager() {
assert_eq!(configs[4].command, "python3", "shell configs are left alone");
}
fn fake_jdk(dir: &Path) {
std::fs::create_dir_all(dir.join("bin")).unwrap();
std::fs::write(dir.join("bin").join(exe("java")), "").unwrap();
std::fs::write(dir.join("release"), "JAVA_VERSION=\"17.0.9\"\n").unwrap();
}
#[test]
fn project_jdk_and_maven_settings() {
if cfg!(windows) {
return; // Unix paths and shells
}
let tmp = tempfile::tempdir().unwrap();
let jdk = tmp.path().join("jdk17");
fake_jdk(&jdk);
let maven = tmp.path().join("maven");
std::fs::create_dir_all(maven.join("bin")).unwrap();
std::fs::write(maven.join("bin/mvn"), "").unwrap();
let mut s = Settings::default();
assert_eq!(project_jdk(tmp.path(), &s), None);
assert_eq!(maven_command(tmp.path(), &s), None);
assert!(maven_options(tmp.path(), &s).is_empty());
// Project-relative paths, a JDK's `bin/java`, a Maven home.
s.languages.java.jdk = "jdk17/bin/java".into();
s.languages.java.maven.home = maven.to_string_lossy().into_owned();
s.languages.java.maven.user_settings = "/m2/settings.xml".into();
s.languages.java.maven.local_repository = "/m2/repo".into();
assert_eq!(project_jdk(tmp.path(), &s).map(|j| j.major), Some(17));
assert_eq!(maven_command(tmp.path(), &s), Some(maven.join("bin/mvn")));
assert_eq!(maven_options(tmp.path(), &s), ["-s", "/m2/settings.xml", "-Dmaven.repo.local=/m2/repo"]);
let mut configs = vec![run("maven", "./mvnw", &["package"]), run("gradle", "./gradlew", &["build"])];
apply_to_run_configs(&mut configs, tmp.path(), &s);
let home = project_jdk(tmp.path(), &s).unwrap().home.to_string_lossy().into_owned();
assert_eq!(configs[0].command, maven.join("bin/mvn").to_string_lossy());
assert_eq!(configs[0].args, ["-s", "/m2/settings.xml", "-Dmaven.repo.local=/m2/repo", "package"]);
assert_eq!(configs[0].env["JAVA_HOME"], home);
assert_eq!(configs[1].env["JAVA_HOME"], home);
apply_to_run_configs(&mut configs, tmp.path(), &s);
assert_eq!(configs[0].args.len(), 4, "applied once");
s.languages.java.jdk = "missing".into();
assert_eq!(project_jdk(tmp.path(), &s), None);
}
#[test]
fn terminal_activation_for_project_venv() {
if cfg!(windows) {
@@ -174,7 +233,7 @@ fn excluded_folders_become_anchored_globs() {
s.project_structure.excluded = vec!["build/".into(), " ".into()];
let globs = s.exclude_globs();
assert!(globs.contains(&"/build".to_owned()));
assert_eq!(globs.len(), s.files.exclude.len() + 1);
assert_eq!(globs.len(), s.file_excludes().len() + 1);
}
/// Prints what this machine has installed.
@@ -196,3 +255,18 @@ fn detect_on_this_machine() {
}
}
}
#[test]
fn custom_tool_path_replaces_the_command() {
let tmp = tempfile::tempdir().unwrap();
let mut s = Settings::default();
s.tools.insert("elixir-ls".into(), ide_core::settings::ToolSettings { path: "tools/ls/language_server.sh".into() });
s.tools.insert("zls".into(), ide_core::settings::ToolSettings { path: " ".into() });
let mut cfg = server("elixir-ls");
configure_server(&mut cfg, tmp.path(), tmp.path(), &s);
assert_eq!(Path::new(&cfg.command), tmp.path().join("tools/ls/language_server.sh"));
// A blank path keeps auto-detection.
let mut cfg = server("zls");
configure_server(&mut cfg, tmp.path(), tmp.path(), &s);
assert_eq!(cfg.command, "zls");
}
+21
Переглянути файл
@@ -177,6 +177,27 @@ pub fn locate(root: &Path, names: &[String]) -> Option<PathBuf> {
/// Creates `bin_dir/<command>` that runs `target`: a shell wrapper on Unix
/// (keeps the target's own directory layout intact), a `.cmd` shim on Windows.
/// Like [`link_executable`], with `env` set for `target`.
pub fn env_wrapper(bin_dir: &Path, command: &str, target: &Path, env: &[(&str, &Path)]) -> IdeResult<PathBuf> {
fs::create_dir_all(bin_dir)?;
#[cfg(unix)]
{
let quote = |p: &Path| format!("'{}'", p.to_string_lossy().replace('\'', r"'\''"));
let vars: String = env.iter().map(|(k, v)| format!("{k}={} ", quote(v))).collect();
let link = bin_dir.join(command);
fs::write(&link, format!("#!/bin/sh\n{vars}exec {} \"$@\"\n", quote(target)))?;
make_executable(&link)?;
Ok(link)
}
#[cfg(not(unix))]
{
let link = bin_dir.join(format!("{command}.cmd"));
let vars: String = env.iter().map(|(k, v)| format!("set \"{k}={}\"\r\n", v.display())).collect();
fs::write(&link, format!("@echo off\r\nsetlocal\r\n{vars}\"{}\" %*\r\n", target.display()))?;
Ok(link)
}
}
pub fn link_executable(bin_dir: &Path, command: &str, target: &Path) -> IdeResult<PathBuf> {
fs::create_dir_all(bin_dir)?;
#[cfg(unix)]
+170 -5
Переглянути файл
@@ -39,6 +39,8 @@ pub enum ToolStatus {
Installed,
/// Found on the system `PATH`.
OnPath,
/// The executable chosen in settings.
Custom,
Missing,
}
@@ -66,6 +68,8 @@ pub struct ToolInfo {
/// Manual install instructions from the language definition.
pub install_hint: Option<String>,
pub homepage: Option<String>,
/// Why the executable chosen in settings cannot be used (status is then `Missing`).
pub custom_error: Option<String>,
}
/// Streamed install progress.
@@ -116,7 +120,9 @@ fn bin_dirs_in(root: &Path, platform: Platform) -> Vec<PathBuf> {
fn managed_bin_dir(root: &Path, spec: &ToolSpec, platform: Platform) -> Option<PathBuf> {
match spec.method {
Method::Npm { .. } => Some(root.join("node_modules").join(".bin")),
Method::Go { .. } | Method::Release { .. } => Some(root.join(spec.name).join("bin")),
Method::Go { .. } | Method::Gem { .. } | Method::DotnetTool { .. } | Method::Release { .. } => {
Some(root.join(spec.name).join("bin"))
}
Method::PipVenv { .. } => {
Some(root.join(spec.name).join("venv").join(if platform.os == Os::Windows { "Scripts" } else { "bin" }))
}
@@ -212,10 +218,21 @@ fn usages(langs: &[LanguageConfig]) -> BTreeMap<String, Usage> {
for s in &l.language_servers {
add(&s.name, &s.command, ToolKind::LanguageServer, s.install_hint.as_ref(), &l.name);
}
}
let servers: HashSet<&str> = langs.iter().flat_map(|l| &l.language_servers).map(|s| s.name.as_str()).collect();
for l in langs {
if let Some(d) = &l.debugger {
add(&d.adapter, &d.command, ToolKind::Debugger, d.install_hint.as_ref(), &l.name);
// An adapter named like a server but launched differently (ElixirLS's
// `elixir-ls-debugger`) is a tool of its own, listed by its command.
let name =
if servers.contains(d.adapter.as_str()) && d.command != d.adapter { &d.command } else { &d.adapter };
add(name, &d.command, ToolKind::Debugger, d.install_hint.as_ref(), &l.name);
}
}
for (plugin, host) in registry::PLUGIN_HOSTS {
let languages = map.get(*host).map(|u| u.languages.clone()).unwrap_or_default();
map.entry(plugin.to_string()).or_default().languages = languages;
}
map
}
@@ -256,6 +273,8 @@ pub struct Tools {
/// `PATH` handed to installer child processes.
child_path: OsString,
platform: Platform,
/// Executables chosen in settings, by command.
custom: BTreeMap<String, PathBuf>,
}
impl Tools {
@@ -269,7 +288,13 @@ impl Tools {
let system: Vec<PathBuf> = std::env::split_paths(&search_path).filter(|d| !ours.contains(d)).collect();
let system_path = std::env::join_paths(&system).unwrap_or_default();
let child_path = std::env::join_paths(ours.iter().chain(system.iter())).unwrap_or_default();
Self { root, system_path, child_path, platform }
Self { root, system_path, child_path, platform, custom: BTreeMap::new() }
}
/// Reports the executables chosen in settings (command → path) as the tools' location.
pub fn with_custom_paths(mut self, custom: BTreeMap<String, PathBuf>) -> Self {
self.custom = custom;
self
}
pub fn root(&self) -> &Path {
@@ -339,6 +364,12 @@ impl Tools {
/// Requirement check for installing `spec` right now.
fn unavailable_reason(&self, spec: &ToolSpec) -> Option<String> {
self.installer_missing(spec)
.or_else(|| spec.needs.iter().find(|(cmd, _)| self.which(cmd).is_none()).map(|(_, why)| why.to_string()))
}
/// What the install method itself lacks (npm, a build for this platform, …).
fn installer_missing(&self, spec: &ToolSpec) -> Option<String> {
let need = |ok: bool, msg: &str| (!ok).then(|| msg.to_string());
match spec.method {
Method::Rustup { .. } => need(self.which("rustup").is_some(), "rustup is required (https://rustup.rs)"),
@@ -347,6 +378,10 @@ impl Tools {
"npm or pnpm is required: install Node.js (https://nodejs.org)",
),
Method::Go { .. } => need(self.which("go").is_some(), "Go is required (https://go.dev/dl)"),
Method::Gem { .. } => need(self.which("gem").is_some(), "Ruby is required (https://www.ruby-lang.org)"),
Method::DotnetTool { .. } => {
need(self.which("dotnet").is_some(), ".NET SDK is required (https://dotnet.microsoft.com/download)")
}
Method::PipVenv { .. } => need(
self.which("uv").is_some() || self.python().is_some(),
"Python 3 or uv is required (https://www.python.org)",
@@ -390,7 +425,9 @@ impl Tools {
can_uninstall: false,
install_hint,
homepage: None,
});
custom_error: None,
})
.map(|info| self.apply_custom(info, None));
};
let (status, path, version) = self.detect(spec);
let unavailable_reason = self.unavailable_reason(spec);
@@ -410,7 +447,34 @@ impl Tools {
can_uninstall,
install_hint,
homepage: Some(spec.homepage.to_string()),
custom_error: None,
})
.map(|info| self.apply_custom(info, Some(spec)))
}
/// Overrides the detected location with the executable chosen in settings.
fn apply_custom(&self, mut info: ToolInfo, spec: Option<&ToolSpec>) -> ToolInfo {
let Some(path) = self.custom.get(&info.command) else { return info };
if !path.is_file() {
info.status = ToolStatus::Missing;
info.custom_error = Some(format!("{} does not exist", path.display()));
info.path = None;
info.version = None;
return info;
}
info.version = spec.and_then(|spec| {
let (cmd, args) = spec.version?;
// The version command is the tool itself, whatever the chosen file is called.
let program =
if cmd == spec.commands[0] { path.clone() } else { path.parent().and_then(|d| self.exe_in(d, cmd))? };
let mut c = self.command(program);
c.args(args);
let (ok, out) = run_quiet(c, Duration::from_secs(4))?;
if ok { parse_version(&out) } else { None }
});
info.status = ToolStatus::Custom;
info.path = Some(path.clone().into());
info
}
fn detect(&self, spec: &ToolSpec) -> (ToolStatus, Option<PathBuf>, Option<String>) {
@@ -535,6 +599,8 @@ impl Tools {
}
Method::Npm { packages } => self.install_npm(packages, cancel, emit)?,
Method::Go { module } => self.install_go(spec, module, cancel, emit)?,
Method::Gem { gem } => self.install_gem(spec, gem, cancel, emit)?,
Method::DotnetTool { package } => self.install_dotnet_tool(spec, package, cancel, emit)?,
Method::PipVenv { package } => self.install_venv(spec, package, cancel, emit)?,
Method::PipUser { package, .. } => self.install_pip_user(package, cancel, emit)?,
Method::PipTarget { package, .. } => self.install_pip_target(spec, package, cancel, emit)?,
@@ -614,6 +680,96 @@ impl Tools {
self.write_manifest(spec.name, &Manifest { version, source: Some(module.to_string()) })
}
fn install_gem(&self, spec: &ToolSpec, gem: &str, cancel: &CancellationToken, emit: Emit) -> IdeResult<()> {
let dir = self.root.join(spec.name);
let _ = std::fs::remove_dir_all(&dir);
let home = dir.join("gems");
std::fs::create_dir_all(&home)?;
let mut c = self.command(self.which("gem").expect("checked"));
c.args(["install", "--no-document", "--install-dir"]).arg(&home).arg("--bindir").arg(home.join("bin")).arg(gem);
let result = run_streamed(c, cancel, emit).and_then(|_| {
// RubyGems' stubs only find their gems through GEM_HOME / GEM_PATH.
let env = [("GEM_HOME", home.as_path()), ("GEM_PATH", home.as_path())];
for cmd in spec.commands {
let stub = self
.exe_in(&home.join("bin"), cmd)
.ok_or_else(|| IdeError::new(ErrorKind::Io, format!("gem {gem} did not install `{cmd}`")))?;
archive::env_wrapper(&dir.join("bin"), cmd, &stub, &env)?;
}
Ok(())
});
if let Err(e) = result {
let _ = std::fs::remove_dir_all(&dir);
return Err(e);
}
// `gems/gems/<gem>-<version>/`
let version = std::fs::read_dir(home.join("gems")).ok().and_then(|entries| {
entries.flatten().find_map(|e| {
let name = e.file_name().to_string_lossy().into_owned();
name.strip_prefix(&format!("{gem}-"))
.filter(|v| v.starts_with(|c: char| c.is_ascii_digit()))
.map(String::from)
})
});
self.write_manifest(spec.name, &Manifest { version, source: Some(format!("rubygems:{gem}")) })
}
fn install_dotnet_tool(
&self,
spec: &ToolSpec,
package: &str,
cancel: &CancellationToken,
emit: Emit,
) -> IdeResult<()> {
let dir = self.root.join(spec.name);
let _ = std::fs::remove_dir_all(&dir);
let tool = dir.join("tool");
std::fs::create_dir_all(&tool)?;
let dotnet = self.which("dotnet").expect("checked");
let mut c = self.command(&dotnet);
c.args(["tool", "install", package, "--tool-path"]).arg(&tool);
let result = run_streamed(c, cancel, emit).and_then(|_| {
// The tool's apphost looks for .NET in the default location only; a
// Homebrew / user-local SDK must be named through DOTNET_ROOT.
let root = self.dotnet_root(&dotnet);
for cmd in spec.commands {
let exe = self
.exe_in(&tool, cmd)
.ok_or_else(|| IdeError::new(ErrorKind::Io, format!("{package} did not install `{cmd}`")))?;
match &root {
Some(root) => archive::env_wrapper(&dir.join("bin"), cmd, &exe, &[("DOTNET_ROOT", root)])?,
None => archive::link_executable(&dir.join("bin"), cmd, &exe)?,
};
}
Ok(())
});
if let Err(e) = result {
let _ = std::fs::remove_dir_all(&dir);
return Err(e);
}
// `Package Id Version Commands` table.
let mut c = self.command(&dotnet);
c.args(["tool", "list", "--tool-path"]).arg(&tool);
let version = run_quiet(c, Duration::from_secs(20)).and_then(|(_, out)| {
out.lines().find_map(|l| {
let mut cols = l.split_whitespace();
cols.next().filter(|id| id.eq_ignore_ascii_case(package))?;
cols.next().map(String::from)
})
});
self.write_manifest(spec.name, &Manifest { version, source: Some(format!("nuget:{package}")) })
}
/// The .NET install `dotnet` runs from: `Microsoft.NETCore.App 9.0.1 [<root>/shared/Microsoft.NETCore.App]`.
fn dotnet_root(&self, dotnet: &Path) -> Option<PathBuf> {
let mut c = self.command(dotnet);
c.arg("--list-runtimes");
let (_, out) = run_quiet(c, Duration::from_secs(20))?;
let line = out.lines().find(|l| l.starts_with("Microsoft.NETCore.App "))?;
let shared = line.rsplit_once('[')?.1.trim_end().strip_suffix(']')?;
Path::new(shared).parent()?.parent().map(Path::to_path_buf)
}
fn install_venv(&self, spec: &ToolSpec, package: &str, cancel: &CancellationToken, emit: Emit) -> IdeResult<()> {
let dir = self.root.join(spec.name);
let _ = std::fs::remove_dir_all(&dir);
@@ -734,6 +890,10 @@ impl Tools {
let json = http.get_text(&sources::openvsx_latest_url(namespace, extension), cancel)?;
sources::openvsx_pick(&json, assets, self.platform)
}
ReleaseSource::MavenCentral { group, artifact } => {
let xml = http.get_text(&sources::maven_metadata_url(group, artifact), cancel)?;
sources::maven_pick(group, artifact, &xml)
}
}
}
@@ -889,7 +1049,12 @@ impl Tools {
run_streamed(c, &cancel, &quiet)?;
}
}
Method::Go { .. } | Method::PipVenv { .. } | Method::PipTarget { .. } | Method::Release { .. } => {
Method::Go { .. }
| Method::Gem { .. }
| Method::DotnetTool { .. }
| Method::PipVenv { .. }
| Method::PipTarget { .. }
| Method::Release { .. } => {
let dir = self.root.join(spec.name);
if dir.exists() {
std::fs::remove_dir_all(&dir)?;
+354 -2
Переглянути файл
@@ -10,6 +10,8 @@ use specta::Type;
pub enum ToolKind {
LanguageServer,
Debugger,
/// Loaded into another tool's process, e.g. a jdtls agent.
Plugin,
}
/// Where release archives come from.
@@ -23,6 +25,8 @@ pub enum ReleaseSource {
EclipseJdtls,
/// Latest version of a VS Code extension (`.vsix`) on open-vsx.org.
OpenVsx { namespace: &'static str, extension: &'static str },
/// Latest release of a Maven Central artifact (the `.jar` itself).
MavenCentral { group: &'static str, artifact: &'static str },
}
#[derive(Clone, Copy, Debug)]
@@ -40,6 +44,11 @@ pub enum Method {
/// A pure-Python package unpacked into `<tools>/<name>/lib` (`pip install --target`,
/// universal wheel), put on `PYTHONPATH` of whichever interpreter runs it.
PipTarget { package: &'static str, module: &'static str },
/// `gem install` into `<tools>/<name>/gems`, launched through `GEM_HOME` wrappers in `bin/`.
Gem { gem: &'static str },
/// `dotnet tool install --tool-path <tools>/<name>/tool <package>`, launched
/// through `DOTNET_ROOT` wrappers in `bin/`.
DotnetTool { package: &'static str },
/// Platform archive download into `<tools>/<name>/`.
Release { source: ReleaseSource, assets: &'static [AssetRule], locate: &'static [&'static str] },
}
@@ -50,12 +59,15 @@ impl Method {
Method::Rustup { .. } => "rustup",
Method::Npm { .. } => "npm",
Method::Go { .. } => "go install",
Method::Gem { .. } => "gem",
Method::DotnetTool { .. } => "dotnet tool",
Method::PipVenv { .. } => "pip (virtualenv)",
Method::PipUser { .. } => "pip --user",
Method::PipTarget { .. } => "pip (private copy)",
Method::Release { source: ReleaseSource::HashiCorp { .. }, .. } => "HashiCorp release",
Method::Release { source: ReleaseSource::EclipseJdtls, .. } => "Eclipse download",
Method::Release { source: ReleaseSource::OpenVsx { .. }, .. } => "Open VSX",
Method::Release { source: ReleaseSource::MavenCentral { .. }, .. } => "Maven Central",
Method::Release { .. } => "GitHub release",
}
}
@@ -73,6 +85,8 @@ pub struct ToolSpec {
/// Version query: a command (looked up next to the main binary first) and its args.
pub version: Option<(&'static str, &'static [&'static str])>,
pub homepage: &'static str,
/// Runtimes the tool runs on, found on `PATH`: command and why it is needed.
pub needs: &'static [(&'static str, &'static str)],
}
impl ToolSpec {
@@ -86,9 +100,14 @@ impl ToolSpec {
use Arch::{Arm64, X64};
use Os::{Linux, Mac, Windows};
use ToolKind::{Debugger, LanguageServer};
use ToolKind::{Debugger, LanguageServer, Plugin};
const V: Option<(&str, &[&str])> = None;
const JAVA: &[(&str, &str)] = &[("java", "Java is required (https://adoptium.net)")];
const NODE: &[(&str, &str)] = &[("node", "Node.js is required (https://nodejs.org)")];
const ELIXIR: &[(&str, &str)] = &[("elixir", "Elixir is required (https://elixir-lang.org/install.html)")];
const ELIXIR_LS_ASSETS: &[AssetRule] =
&[any_arch(Mac, "elixir-ls-v*.zip"), any_arch(Linux, "elixir-ls-v*.zip"), any_arch(Windows, "elixir-ls-v*.zip")];
const fn ver(cmd: &'static str) -> Option<(&'static str, &'static [&'static str])> {
Some((cmd, &["--version"]))
}
@@ -102,6 +121,7 @@ pub static TOOLS: &[ToolSpec] = &[
method: Method::Rustup { component: "rust-analyzer" },
version: ver("rust-analyzer"),
homepage: "https://rust-analyzer.github.io",
needs: &[],
},
ToolSpec {
name: "vtsls",
@@ -111,6 +131,7 @@ pub static TOOLS: &[ToolSpec] = &[
method: Method::Npm { packages: &["@vtsls/language-server"] },
version: V,
homepage: "https://github.com/yioneko/vtsls",
needs: &[],
},
ToolSpec {
name: "typescript-language-server",
@@ -120,6 +141,7 @@ pub static TOOLS: &[ToolSpec] = &[
method: Method::Npm { packages: &["typescript-language-server", "typescript"] },
version: ver("typescript-language-server"),
homepage: "https://github.com/typescript-language-server/typescript-language-server",
needs: &[],
},
ToolSpec {
name: "pyright",
@@ -129,6 +151,7 @@ pub static TOOLS: &[ToolSpec] = &[
method: Method::Npm { packages: &["pyright"] },
version: ver("pyright"),
homepage: "https://github.com/microsoft/pyright",
needs: &[],
},
ToolSpec {
name: "basedpyright",
@@ -138,6 +161,7 @@ pub static TOOLS: &[ToolSpec] = &[
method: Method::PipVenv { package: "basedpyright" },
version: ver("basedpyright"),
homepage: "https://docs.basedpyright.com",
needs: &[],
},
ToolSpec {
name: "bash-language-server",
@@ -147,6 +171,7 @@ pub static TOOLS: &[ToolSpec] = &[
method: Method::Npm { packages: &["bash-language-server"] },
version: ver("bash-language-server"),
homepage: "https://github.com/bash-lsp/bash-language-server",
needs: &[],
},
ToolSpec {
name: "yaml-language-server",
@@ -156,6 +181,7 @@ pub static TOOLS: &[ToolSpec] = &[
method: Method::Npm { packages: &["yaml-language-server"] },
version: V,
homepage: "https://github.com/redhat-developer/yaml-language-server",
needs: &[],
},
ToolSpec {
name: "vscode-json-language-server",
@@ -165,6 +191,7 @@ pub static TOOLS: &[ToolSpec] = &[
method: Method::Npm { packages: &["vscode-langservers-extracted"] },
version: V,
homepage: "https://github.com/hrsh7th/vscode-langservers-extracted",
needs: &[],
},
ToolSpec {
name: "vscode-css-language-server",
@@ -174,6 +201,7 @@ pub static TOOLS: &[ToolSpec] = &[
method: Method::Npm { packages: &["vscode-langservers-extracted"] },
version: V,
homepage: "https://github.com/hrsh7th/vscode-langservers-extracted",
needs: &[],
},
ToolSpec {
name: "vscode-html-language-server",
@@ -183,6 +211,7 @@ pub static TOOLS: &[ToolSpec] = &[
method: Method::Npm { packages: &["vscode-langservers-extracted"] },
version: V,
homepage: "https://github.com/hrsh7th/vscode-langservers-extracted",
needs: &[],
},
ToolSpec {
name: "dockerfile-language-server",
@@ -192,6 +221,7 @@ pub static TOOLS: &[ToolSpec] = &[
method: Method::Npm { packages: &["dockerfile-language-server-nodejs"] },
version: V,
homepage: "https://github.com/rcjsuen/dockerfile-language-server",
needs: &[],
},
ToolSpec {
name: "svelte-language-server",
@@ -201,6 +231,7 @@ pub static TOOLS: &[ToolSpec] = &[
method: Method::Npm { packages: &["svelte-language-server"] },
version: V,
homepage: "https://github.com/sveltejs/language-tools",
needs: &[],
},
ToolSpec {
name: "vue-language-server",
@@ -210,6 +241,7 @@ pub static TOOLS: &[ToolSpec] = &[
method: Method::Npm { packages: &["@vue/language-server"] },
version: V,
homepage: "https://github.com/vuejs/language-tools",
needs: &[],
},
ToolSpec {
name: "graphql-lsp",
@@ -219,6 +251,7 @@ pub static TOOLS: &[ToolSpec] = &[
method: Method::Npm { packages: &["graphql-language-service-cli"] },
version: V,
homepage: "https://github.com/graphql/graphiql",
needs: &[],
},
ToolSpec {
name: "intelephense",
@@ -228,6 +261,7 @@ pub static TOOLS: &[ToolSpec] = &[
method: Method::Npm { packages: &["intelephense"] },
version: V,
homepage: "https://intelephense.com",
needs: &[],
},
ToolSpec {
name: "gopls",
@@ -237,6 +271,7 @@ pub static TOOLS: &[ToolSpec] = &[
method: Method::Go { module: "golang.org/x/tools/gopls@latest" },
version: Some(("gopls", &["version"])),
homepage: "https://pkg.go.dev/golang.org/x/tools/gopls",
needs: &[],
},
ToolSpec {
name: "sqls",
@@ -246,6 +281,7 @@ pub static TOOLS: &[ToolSpec] = &[
method: Method::Go { module: "github.com/sqls-server/sqls@latest" },
version: Some(("sqls", &["--version"])),
homepage: "https://github.com/sqls-server/sqls",
needs: &[],
},
ToolSpec {
name: "delve",
@@ -255,6 +291,7 @@ pub static TOOLS: &[ToolSpec] = &[
method: Method::Go { module: "github.com/go-delve/delve/cmd/dlv@latest" },
version: Some(("dlv", &["version"])),
homepage: "https://github.com/go-delve/delve",
needs: &[],
},
ToolSpec {
name: "debugpy",
@@ -264,6 +301,7 @@ pub static TOOLS: &[ToolSpec] = &[
method: Method::PipTarget { package: "debugpy", module: "debugpy" },
version: V,
homepage: "https://github.com/microsoft/debugpy",
needs: &[],
},
ToolSpec {
name: "clangd",
@@ -281,6 +319,7 @@ pub static TOOLS: &[ToolSpec] = &[
},
version: ver("clangd"),
homepage: "https://clangd.llvm.org",
needs: &[],
},
ToolSpec {
name: "lua-language-server",
@@ -300,6 +339,7 @@ pub static TOOLS: &[ToolSpec] = &[
},
version: ver("lua-language-server"),
homepage: "https://luals.github.io",
needs: &[],
},
ToolSpec {
name: "marksman",
@@ -318,6 +358,7 @@ pub static TOOLS: &[ToolSpec] = &[
},
version: ver("marksman"),
homepage: "https://github.com/artempyanykh/marksman",
needs: &[],
},
ToolSpec {
name: "taplo",
@@ -337,6 +378,7 @@ pub static TOOLS: &[ToolSpec] = &[
},
version: ver("taplo"),
homepage: "https://taplo.tamasfe.dev",
needs: &[],
},
ToolSpec {
name: "zls",
@@ -356,6 +398,7 @@ pub static TOOLS: &[ToolSpec] = &[
},
version: ver("zls"),
homepage: "https://github.com/zigtools/zls",
needs: &[],
},
ToolSpec {
name: "terraform-ls",
@@ -375,6 +418,7 @@ pub static TOOLS: &[ToolSpec] = &[
},
version: Some(("terraform-ls", &["version"])),
homepage: "https://github.com/hashicorp/terraform-ls",
needs: &[],
},
ToolSpec {
name: "codelldb",
@@ -399,6 +443,7 @@ pub static TOOLS: &[ToolSpec] = &[
},
version: V,
homepage: "https://github.com/vadimcn/codelldb",
needs: &[],
},
ToolSpec {
name: "js-debug",
@@ -417,6 +462,7 @@ pub static TOOLS: &[ToolSpec] = &[
},
version: V,
homepage: "https://github.com/microsoft/vscode-js-debug",
needs: &[],
},
ToolSpec {
name: "jdtls",
@@ -434,6 +480,7 @@ pub static TOOLS: &[ToolSpec] = &[
},
version: V,
homepage: "https://github.com/eclipse-jdtls/eclipse.jdt.ls",
needs: &[],
},
ToolSpec {
name: "java-debug",
@@ -452,6 +499,26 @@ pub static TOOLS: &[ToolSpec] = &[
},
version: V,
homepage: "https://github.com/microsoft/java-debug",
needs: &[],
},
ToolSpec {
name: "lombok",
display: "Lombok (jdtls agent)",
kind: Plugin,
commands: &["lombok.jar"],
// Newer than the Lombok a project pins: old ones fail inside current ECJ.
method: Method::Release {
source: ReleaseSource::MavenCentral { group: "org.projectlombok", artifact: "lombok" },
assets: &[
any_arch(Mac, "lombok-*.jar"),
any_arch(Linux, "lombok-*.jar"),
any_arch(Windows, "lombok-*.jar"),
],
locate: &["lombok.jar"],
},
version: V,
homepage: "https://projectlombok.org",
needs: &[],
},
ToolSpec {
name: "kotlin-lsp",
@@ -475,9 +542,286 @@ pub static TOOLS: &[ToolSpec] = &[
},
version: V,
homepage: "https://github.com/Kotlin/kotlin-lsp",
needs: &[],
},
// ElixirLS ships launcher scripts only: on first start they build the server
// with the Elixir / OTP found for the project (Mix.install, needs network).
ToolSpec {
name: "elixir-ls",
display: "ElixirLS",
kind: LanguageServer,
commands: &["elixir-ls"],
method: Method::Release {
source: ReleaseSource::GitHub { repo: "elixir-lsp/elixir-ls" },
assets: ELIXIR_LS_ASSETS,
locate: &["language_server.sh", "language_server.bat"],
},
version: V,
homepage: "https://github.com/elixir-lsp/elixir-ls",
needs: ELIXIR,
},
ToolSpec {
name: "elixir-ls-debugger",
display: "ElixirLS Debugger",
kind: Debugger,
commands: &["elixir-ls-debugger"],
method: Method::Release {
source: ReleaseSource::GitHub { repo: "elixir-lsp/elixir-ls" },
assets: ELIXIR_LS_ASSETS,
locate: &["debug_adapter.sh", "debug_adapter.bat"],
},
version: V,
homepage: "https://github.com/elixir-lsp/elixir-ls",
needs: ELIXIR,
},
ToolSpec {
name: "buf",
display: "Buf (Protocol Buffers)",
kind: LanguageServer,
commands: &["buf"],
method: Method::Release {
source: ReleaseSource::GitHub { repo: "bufbuild/buf" },
assets: &[
rule(Mac, Arm64, "buf-Darwin-arm64.tar.gz"),
rule(Mac, X64, "buf-Darwin-x86_64.tar.gz"),
rule(Linux, X64, "buf-Linux-x86_64.tar.gz"),
rule(Linux, Arm64, "buf-Linux-aarch64.tar.gz"),
rule(Windows, X64, "buf-Windows-x86_64.zip"),
rule(Windows, Arm64, "buf-Windows-arm64.zip"),
],
locate: &["buf"],
},
version: ver("buf"),
homepage: "https://buf.build",
needs: &[],
},
ToolSpec {
name: "clojure-lsp",
display: "clojure-lsp",
kind: LanguageServer,
commands: &["clojure-lsp"],
method: Method::Release {
source: ReleaseSource::GitHub { repo: "clojure-lsp/clojure-lsp" },
assets: &[
rule(Mac, Arm64, "clojure-lsp-native-macos-aarch64.zip"),
rule(Mac, X64, "clojure-lsp-native-macos-amd64.zip"),
rule(Linux, X64, "clojure-lsp-native-linux-amd64.zip"),
rule(Linux, Arm64, "clojure-lsp-native-linux-aarch64.zip"),
rule(Windows, X64, "clojure-lsp-native-windows-amd64.zip"),
],
locate: &["clojure-lsp"],
},
version: V,
homepage: "https://clojure-lsp.io",
needs: &[],
},
ToolSpec {
name: "texlab",
display: "TexLab (LaTeX)",
kind: LanguageServer,
commands: &["texlab"],
method: Method::Release {
source: ReleaseSource::GitHub { repo: "latex-lsp/texlab" },
assets: &[
rule(Mac, Arm64, "texlab-aarch64-macos.tar.gz"),
rule(Mac, X64, "texlab-x86_64-macos.tar.gz"),
rule(Linux, X64, "texlab-x86_64-linux.tar.gz"),
rule(Linux, Arm64, "texlab-aarch64-linux.tar.gz"),
rule(Windows, X64, "texlab-x86_64-windows.zip"),
rule(Windows, Arm64, "texlab-aarch64-windows.zip"),
],
locate: &["texlab"],
},
version: ver("texlab"),
homepage: "https://github.com/latex-lsp/texlab",
needs: &[],
},
ToolSpec {
name: "neocmakelsp",
display: "neocmakelsp (CMake)",
kind: LanguageServer,
commands: &["neocmakelsp"],
method: Method::Release {
source: ReleaseSource::GitHub { repo: "Decodetalkers/neocmakelsp" },
assets: &[
any_arch(Mac, "neocmakelsp-universal-apple-darwin.tar.gz"),
rule(Linux, X64, "neocmakelsp-x86_64-unknown-linux-gnu.tar.gz"),
rule(Linux, Arm64, "neocmakelsp-aarch64-unknown-linux-gnu.tar.gz"),
rule(Windows, X64, "neocmakelsp-x86_64-pc-windows-msvc.zip"),
rule(Windows, Arm64, "neocmakelsp-aarch64-pc-windows-msvc.zip"),
],
locate: &["neocmakelsp"],
},
version: ver("neocmakelsp"),
homepage: "https://github.com/Decodetalkers/neocmakelsp",
needs: &[],
},
ToolSpec {
name: "lemminx",
display: "LemMinX (XML)",
kind: LanguageServer,
commands: &["lemminx"],
method: Method::Release {
source: ReleaseSource::GitHub { repo: "redhat-developer/vscode-xml" },
assets: &[
rule(Mac, Arm64, "lemminx-osx-aarch_64.zip"),
rule(Mac, X64, "lemminx-osx-x86_64.zip"),
rule(Linux, X64, "lemminx-linux-x86_64.zip"),
rule(Linux, Arm64, "lemminx-linux-aarch_64.zip"),
rule(Windows, X64, "lemminx-win32.zip"),
],
locate: &["lemminx-*"],
},
version: V,
homepage: "https://github.com/eclipse/lemminx",
needs: &[],
},
ToolSpec {
name: "perlnavigator",
display: "Perl Navigator",
kind: LanguageServer,
commands: &["perlnavigator"],
method: Method::Release {
source: ReleaseSource::GitHub { repo: "bscan/PerlNavigator" },
assets: &[
any_arch(Mac, "perlnavigator-macos-x86_64.zip"),
rule(Linux, X64, "perlnavigator-linux-x86_64.zip"),
rule(Windows, X64, "perlnavigator-win-x86_64.zip"),
],
locate: &["perlnavigator"],
},
version: V,
homepage: "https://github.com/bscan/PerlNavigator",
needs: &[("perl", "Perl is required (https://www.perl.org/get.html)")],
},
ToolSpec {
name: "kotlin-language-server",
display: "Kotlin Language Server (fwcd)",
kind: LanguageServer,
commands: &["kotlin-language-server"],
method: Method::Release {
source: ReleaseSource::GitHub { repo: "fwcd/kotlin-language-server" },
assets: &[any_arch(Mac, "server.zip"), any_arch(Linux, "server.zip"), any_arch(Windows, "server.zip")],
locate: &["kotlin-language-server"],
},
version: V,
homepage: "https://github.com/fwcd/kotlin-language-server",
needs: JAVA,
},
ToolSpec {
name: "kotlin-debug-adapter",
display: "Kotlin Debug Adapter",
kind: Debugger,
commands: &["kotlin-debug-adapter"],
method: Method::Release {
source: ReleaseSource::GitHub { repo: "fwcd/kotlin-debug-adapter" },
assets: &[any_arch(Mac, "adapter.zip"), any_arch(Linux, "adapter.zip"), any_arch(Windows, "adapter.zip")],
locate: &["kotlin-debug-adapter"],
},
version: V,
homepage: "https://github.com/fwcd/kotlin-debug-adapter",
needs: JAVA,
},
ToolSpec {
name: "netcoredbg",
display: "netcoredbg (.NET debugger)",
kind: Debugger,
commands: &["netcoredbg"],
method: Method::Release {
source: ReleaseSource::GitHub { repo: "Samsung/netcoredbg" },
assets: &[
rule(Mac, Arm64, "netcoredbg-osx-arm64.zip"),
rule(Linux, X64, "netcoredbg-linux-amd64.tar.gz"),
rule(Linux, Arm64, "netcoredbg-linux-arm64.tar.gz"),
rule(Windows, X64, "netcoredbg-win64.zip"),
],
locate: &["netcoredbg"],
},
version: V,
homepage: "https://github.com/Samsung/netcoredbg",
needs: &[],
},
ToolSpec {
name: "bash-debug",
display: "Bash Debug",
kind: Debugger,
commands: &["bash-debug-adapter"],
method: Method::Release {
source: ReleaseSource::OpenVsx { namespace: "rogalmic", extension: "bash-debug" },
assets: &[
any_arch(Mac, "rogalmic.bash-debug-*.vsix"),
any_arch(Linux, "rogalmic.bash-debug-*.vsix"),
any_arch(Windows, "rogalmic.bash-debug-*.vsix"),
],
locate: &["bashDebug.js"],
},
version: V,
homepage: "https://github.com/rogalmic/vscode-bash-debug",
needs: NODE,
},
ToolSpec {
name: "php-debug",
display: "PHP Debug (Xdebug)",
kind: Debugger,
commands: &["php-debug-adapter"],
method: Method::Release {
source: ReleaseSource::OpenVsx { namespace: "xdebug", extension: "php-debug" },
assets: &[
any_arch(Mac, "xdebug.php-debug-*.vsix"),
any_arch(Linux, "xdebug.php-debug-*.vsix"),
any_arch(Windows, "xdebug.php-debug-*.vsix"),
],
locate: &["phpDebug.js"],
},
version: V,
homepage: "https://github.com/xdebug/vscode-php-debug",
needs: NODE,
},
ToolSpec {
name: "ruby-lsp",
display: "Ruby LSP (Shopify)",
kind: LanguageServer,
commands: &["ruby-lsp"],
method: Method::Gem { gem: "ruby-lsp" },
version: V,
homepage: "https://shopify.github.io/ruby-lsp",
needs: &[],
},
ToolSpec {
name: "solargraph",
display: "Solargraph (Ruby)",
kind: LanguageServer,
commands: &["solargraph"],
method: Method::Gem { gem: "solargraph" },
version: ver("solargraph"),
homepage: "https://solargraph.org",
needs: &[],
},
ToolSpec {
name: "csharp-ls",
display: "csharp-ls",
kind: LanguageServer,
commands: &["csharp-ls"],
method: Method::DotnetTool { package: "csharp-ls" },
version: V,
homepage: "https://github.com/razzmatazz/csharp-language-server",
needs: &[],
},
ToolSpec {
name: "fsautocomplete",
display: "FsAutoComplete (F#)",
kind: LanguageServer,
commands: &["fsautocomplete"],
method: Method::DotnetTool { package: "fsautocomplete" },
version: V,
homepage: "https://github.com/ionide/FsAutoComplete",
needs: &[],
},
];
/// Plugin tools and the tool that loads them.
pub const PLUGIN_HOSTS: &[(&str, &str)] = &[("lombok", "jdtls")];
pub fn find(name: &str) -> Option<&'static ToolSpec> {
TOOLS.iter().find(|t| t.name == name)
}
@@ -507,7 +851,7 @@ mod tests {
known.insert((d.adapter.clone(), d.command.clone()));
}
}
for t in TOOLS {
for t in TOOLS.iter().filter(|t| t.kind != Plugin) {
assert!(
known.contains(&(t.name.to_string(), t.commands[0].to_string())),
"{} / {} is not referenced by languages/*.toml",
@@ -517,6 +861,14 @@ mod tests {
}
}
#[test]
fn plugins_have_a_known_host() {
for t in TOOLS.iter().filter(|t| t.kind == Plugin) {
let host = PLUGIN_HOSTS.iter().find(|(p, _)| *p == t.name).map(|(_, h)| *h);
assert!(host.and_then(find).is_some(), "{} has no known host", t.name);
}
}
#[test]
fn every_release_tool_covers_mac_linux_windows() {
for t in TOOLS {
+50
Переглянути файл
@@ -209,6 +209,39 @@ pub fn openvsx_pick(json: &str, rules: &[AssetRule], platform: Platform) -> IdeR
})
}
const MAVEN_CENTRAL: &str = "https://repo1.maven.org/maven2";
fn maven_dir(group: &str, artifact: &str) -> String {
format!("{MAVEN_CENTRAL}/{}/{artifact}", group.replace('.', "/"))
}
pub fn maven_metadata_url(group: &str, artifact: &str) -> String {
format!("{}/maven-metadata.xml", maven_dir(group, artifact))
}
/// The `<release>` jar of a `maven-metadata.xml`. Central publishes only SHA-1
/// sums for most artifacts, so the download is not checksum-verified.
pub fn maven_pick(group: &str, artifact: &str, metadata: &str) -> IdeResult<Download> {
let tag = |t: &str| {
let start = metadata.find(&format!("<{t}>"))? + t.len() + 2;
let end = start + metadata[start..].find(&format!("</{t}>"))?;
Some(metadata[start..end].trim())
};
let version = tag("release")
.or_else(|| tag("latest"))
.filter(|v| !v.is_empty() && !v.contains(['/', '\\']))
.ok_or_else(|| proto(format!("no release in the Maven metadata of {group}:{artifact}")))?;
let name = format!("{artifact}-{version}.jar");
Ok(Download {
version: version.to_string(),
url: format!("{}/{version}/{name}", maven_dir(group, artifact)),
name,
size: None,
sha256: None,
checksum_url: None,
})
}
/// Finds the hash for `file_name` in a checksum file: either a bare hex digest
/// or `sha256sum` lines (`<hex> <name>`).
pub fn parse_checksum(text: &str, file_name: &str) -> Option<String> {
@@ -322,6 +355,23 @@ mod tests {
assert!(openvsx_pick(&other, rules, LINUX).is_err());
}
#[test]
fn maven_central() {
let xml =
"<metadata><versioning><latest>1.18.49-SNAPSHOT</latest><release>1.18.48</release></versioning></metadata>";
assert_eq!(
maven_metadata_url("org.projectlombok", "lombok"),
"https://repo1.maven.org/maven2/org/projectlombok/lombok/maven-metadata.xml"
);
let d = maven_pick("org.projectlombok", "lombok", xml).unwrap();
assert_eq!(d.version, "1.18.48");
assert_eq!(d.name, "lombok-1.18.48.jar");
assert_eq!(d.url, "https://repo1.maven.org/maven2/org/projectlombok/lombok/1.18.48/lombok-1.18.48.jar");
assert!(select_asset(&[d.name.as_str()], find("lombok").unwrap().asset_rules(), LINUX).is_some());
assert!(maven_pick("g", "a", "<metadata/>").is_err());
assert!(maven_pick("g", "a", "<release>../x</release>").is_err());
}
#[test]
fn checksums() {
let h = "a".repeat(64);
+101 -5
Переглянути файл
@@ -68,10 +68,12 @@ fn everything_missing_on_an_empty_system() {
assert!(vtsls.languages.iter().any(|l| l == "TypeScript"));
assert!(vtsls.unavailable_reason.as_deref().unwrap().contains("npm"));
// Servers without an installer are listed with their manual hint.
let ruby = find(&list, "solargraph");
assert_eq!(ruby.install_method, None);
assert!(!ruby.can_install);
assert_eq!(ruby.status, ToolStatus::Missing);
let hls = find(&list, "haskell-language-server");
assert_eq!(hls.install_method, None);
assert!(!hls.can_install);
assert_eq!(hls.status, ToolStatus::Missing);
// Gem tools need Ruby.
assert!(find(&list, "solargraph").unavailable_reason.as_deref().unwrap().contains("Ruby"));
// Shared npm package: each server is its own row.
assert_eq!(find(&list, "vscode-css-language-server").install_method.as_deref(), Some("npm"));
assert!(find(&list, "delve").kind == ToolKind::Debugger);
@@ -155,7 +157,7 @@ fn bin_dirs_cover_every_managed_layout() {
fn unknown_or_manual_tools_cannot_be_installed() {
let env = Env::new();
let tools = env.tools();
let err = tools.install("solargraph", &langs(), &CancellationToken::new(), &|_| {}).unwrap_err();
let err = tools.install("haskell-language-server", &langs(), &CancellationToken::new(), &|_| {}).unwrap_err();
assert_eq!(err.kind, ErrorKind::Unavailable);
assert!(err.message.contains("cannot be installed automatically"));
assert_eq!(tools.info("nope", &langs()).unwrap_err().kind, ErrorKind::NotFound);
@@ -286,3 +288,97 @@ fn installed_bundle_is_detected_and_resolvable() {
assert_eq!(managed_bundle(app_data, "java-debug"), Some(bin.join("com.microsoft.java.debug.plugin.jar")));
assert_eq!(managed_bundle(app_data, "jdtls"), None, "not a bundle");
}
#[cfg(unix)]
#[test]
fn custom_paths_win_and_report_their_version() {
let env = Env::new();
env.script(&env.sys, "gopls", "echo 'golang.org/x/tools/gopls v0.16.1'");
let elsewhere = env.sys.parent().unwrap().join("opt/go/bin");
env.script(&elsewhere, "my-gopls", "echo 'golang.org/x/tools/gopls v0.17.0'");
let custom =
BTreeMap::from([("gopls".to_string(), elsewhere.join("my-gopls")), ("zls".to_string(), elsewhere.join("zls"))]);
let list = env.tools().with_custom_paths(custom).list(&langs());
let gopls = find(&list, "gopls");
assert_eq!(gopls.status, ToolStatus::Custom);
assert_eq!(gopls.path.as_deref(), Some(elsewhere.join("my-gopls").as_path()));
assert_eq!(gopls.version.as_deref(), Some("0.17.0"));
assert_eq!(gopls.custom_error, None);
// A path that does not exist is reported, not silently replaced by detection.
let zls = find(&list, "zls");
assert_eq!(zls.status, ToolStatus::Missing);
assert!(zls.custom_error.as_deref().unwrap().contains("does not exist"));
}
#[test]
fn a_debugger_named_like_its_server_is_listed_by_its_command() {
let list = Env::new().tools().list(&langs());
let server = find(&list, "elixir-ls");
assert_eq!((server.kind, server.command.as_str()), (ToolKind::LanguageServer, "elixir-ls"));
let debugger = find(&list, "elixir-ls-debugger");
assert_eq!((debugger.kind, debugger.command.as_str()), (ToolKind::Debugger, "elixir-ls-debugger"));
assert_eq!(debugger.languages, vec!["Elixir".to_string()]);
}
#[cfg(unix)]
#[test]
fn elixir_ls_needs_elixir_and_lists_its_debugger() {
let env = Env::new();
env.script(&env.sys, "curl", "exit 0");
let list = env.tools().list(&langs());
let server = find(&list, "elixir-ls");
assert_eq!(server.install_method.as_deref(), Some("GitHub release"));
assert!(!server.can_install);
assert!(server.unavailable_reason.as_deref().unwrap().contains("Elixir is required"));
let debugger = find(&list, "elixir-ls-debugger");
assert_eq!((debugger.kind, debugger.languages.as_slice()), (ToolKind::Debugger, ["Elixir".to_string()].as_slice()));
env.script(&env.sys, "elixir", "exit 0");
let list = env.tools().list(&langs());
assert!(find(&list, "elixir-ls").can_install);
assert!(find(&list, "elixir-ls-debugger").can_install);
}
#[cfg(unix)]
#[test]
fn gem_install_wraps_stubs_with_gem_home() {
let env = Env::new();
// `gem install --no-document --install-dir <home> --bindir <bin> solargraph`
env.script(
&env.sys,
"gem",
r#"home="$4"; bin="$6"; /bin/mkdir -p "$home/gems/solargraph-0.50.0" "$bin"
printf '#!/bin/sh\necho "$GEM_HOME"\n' > "$bin/solargraph"; /bin/chmod +x "$bin/solargraph""#,
);
let tools = env.tools();
let info = tools.install("solargraph", &langs(), &CancellationToken::new(), &|_| {}).unwrap();
assert_eq!(info.status, ToolStatus::Installed);
assert_eq!(info.version.as_deref(), Some("0.50.0"));
let wrapper = env.root.join("solargraph/bin/solargraph");
assert_eq!(info.path.as_deref(), Some(wrapper.as_path()));
let out = std::process::Command::new(&wrapper).output().unwrap();
assert_eq!(String::from_utf8_lossy(&out.stdout).trim(), env.root.join("solargraph/gems").to_string_lossy());
}
#[cfg(unix)]
#[test]
fn dotnet_tool_install_into_tool_path() {
let env = Env::new();
env.script(
&env.sys,
"dotnet",
r#"case "$2" in
install) /bin/mkdir -p "$5"; printf '#!/bin/sh\necho "$DOTNET_ROOT"\n' > "$5/csharp-ls"; /bin/chmod +x "$5/csharp-ls" ;;
list) printf 'Package Id Version Commands\n----\ncsharp-ls 0.15.0 csharp-ls\n' ;;
esac
[ "$1" = --list-runtimes ] && echo 'Microsoft.NETCore.App 9.0.1 [/opt/dotnet/shared/Microsoft.NETCore.App]'
exit 0"#,
);
let info = env.tools().install("csharp-ls", &langs(), &CancellationToken::new(), &|_| {}).unwrap();
assert_eq!(info.status, ToolStatus::Installed);
assert_eq!(info.version.as_deref(), Some("0.15.0"));
let wrapper = env.root.join("csharp-ls/bin/csharp-ls");
assert_eq!(info.path.as_deref(), Some(wrapper.as_path()));
let out = std::process::Command::new(&wrapper).output().unwrap();
assert_eq!(String::from_utf8_lossy(&out.stdout).trim(), "/opt/dotnet");
}
+30 -1
Переглянути файл
@@ -2,6 +2,7 @@
//! writes (commit, checkout, push/pull, stash, merge) shell out to `git` so
//! hooks, credentials and signing behave exactly as on the command line.
use ide_core::ignored::IgnoredNames;
use ide_core::{CancellationToken, IdeResult};
use serde::{Deserialize, Serialize};
use specta::Type;
@@ -125,6 +126,18 @@ pub struct Branch {
pub commit: String,
}
/// Commit Options (IDEA's commit options popup).
#[derive(Clone, Debug, Default, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct CommitOptions {
pub amend: bool,
pub sign_off: bool,
/// `--author`, e.g. `Name <[email protected]>`; `None` or blank uses the configured user.
pub author: Option<String>,
/// False skips the pre-commit and commit-msg hooks (`--no-verify`).
pub run_hooks: bool,
}
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct ChangedFile {
@@ -255,6 +268,7 @@ mod patch;
mod refs;
mod remotes;
mod repo;
mod roots;
pub mod shelf;
mod status;
mod write;
@@ -262,6 +276,7 @@ mod write;
pub use cli::{detected_git_executable, git_version, set_git_executable};
pub use diff::build_partial_patch;
pub use remotes::Remote;
pub use roots::Repos;
/// Clones `url` into `dest` (which must not exist or be empty), streaming progress.
pub fn clone(url: &str, dest: &Path, cancel: &CancellationToken, on_output: &dyn Fn(String)) -> IdeResult<()> {
@@ -283,6 +298,7 @@ pub struct Repo {
root: PathBuf,
git_dir: PathBuf,
inner: std::sync::Mutex<repo::Cache>,
ignored: std::sync::RwLock<IgnoredNames>,
}
impl Repo {
@@ -294,6 +310,10 @@ impl Repo {
pub fn root(&self) -> &Path {
&self.root
}
/// Untracked files with one of these names (or under such a folder) are not reported.
pub fn set_ignored_names(&self, names: IgnoredNames) {
*self.ignored.write().unwrap_or_else(|p| p.into_inner()) = names;
}
/// Staged (HEAD↔index) and unstaged (index↔worktree, incl. untracked) changes,
/// sorted by path. Conflicted files report `unstaged: Conflicted` and no staged kind.
pub fn status(&self) -> IdeResult<Vec<FileStatus>> {
@@ -302,6 +322,10 @@ impl Repo {
pub fn branch_info(&self) -> IdeResult<BranchInfo> {
refs::branch_info(self)
}
/// Merge / rebase / cherry-pick… in progress (cheap: no ref walking).
pub fn operation(&self) -> IdeResult<Option<String>> {
Ok(refs::operation(&self.gix()?))
}
/// Content of `path` at `rev` (default HEAD); `None` if absent there.
/// `rev` may be any revision git understands, or `":"` / `":0"` for the index.
pub fn file_at(&self, path: &Path, rev: Option<&str>) -> IdeResult<Option<String>> {
@@ -392,7 +416,12 @@ impl Repo {
/// Commits the index; returns the new HEAD commit id. An empty message with
/// `amend` keeps the previous message.
pub fn commit(&self, message: &str, amend: bool, sign_off: bool) -> IdeResult<String> {
write::commit(self, message, amend, sign_off)
let options = CommitOptions { amend, sign_off, author: None, run_hooks: true };
write::commit(self, message, &options)
}
/// Commits with the Commit Options popup's choices.
pub fn commit_with(&self, message: &str, options: &CommitOptions) -> IdeResult<String> {
write::commit(self, message, options)
}
/// Switches to `branch`. With `create`, creates it at HEAD. Without, a remote branch
/// (`origin/x`) gets a local tracking branch and any other revision is checked out
+1 -1
Переглянути файл
@@ -30,7 +30,7 @@ pub(crate) fn branch_info(r: &Repo) -> IdeResult<BranchInfo> {
Ok(info)
}
fn operation(repo: &gix::Repository) -> Option<String> {
pub(crate) fn operation(repo: &gix::Repository) -> Option<String> {
use gix::state::InProgress::*;
let op = match repo.state()? {
ApplyMailbox | ApplyMailboxRebase => "am",
+1 -1
Переглянути файл
@@ -47,7 +47,7 @@ pub(crate) fn discover(path: &Path) -> IdeResult<Option<Repo>> {
let common_dir = absolute(repo.common_dir())?;
let files = config_files(&git_dir, &common_dir);
let cache = Cache { config_stamp: stamp(&files), config_files: files, repo: ts };
Ok(Some(Repo { root, git_dir, inner: std::sync::Mutex::new(cache) }))
Ok(Some(Repo { root, git_dir, inner: std::sync::Mutex::new(cache), ignored: Default::default() }))
}
fn absolute(p: &Path) -> IdeResult<PathBuf> {
+243
Переглянути файл
@@ -0,0 +1,243 @@
//! The repositories of a project (IDEA's VCS roots): the one containing the project
//! root plus those nested below it (separate clones side by side, submodules).
use crate::{FileStatus, Repo};
use ide_core::IdeResult;
use std::path::{Path, PathBuf};
use std::sync::Arc;
/// How deep below the project root nested repositories are looked for.
const MAX_DEPTH: usize = 4;
/// Folders never searched for nested repositories (dependencies, build output).
const SKIPPED: &[&str] = &["node_modules", "target", "build", "dist", "out", "vendor", "venv", "__pycache__"];
/// The repositories of a project, sorted by root; lookups pick the innermost one.
#[derive(Clone, Default)]
pub struct Repos {
repos: Vec<Arc<Repo>>,
primary: Option<usize>,
}
impl Repos {
/// The repository containing `project_root` and every repository whose worktree
/// root lies below it (up to [`MAX_DEPTH`] levels; hidden and dependency folders and
/// folders `skip` rejects are not searched).
pub fn discover(project_root: &Path, skip: &dyn Fn(&Path) -> bool) -> IdeResult<Self> {
let mut repos: Vec<Repo> = Vec::new();
if let Some(r) = Repo::discover(project_root)? {
repos.push(r);
}
let mut stack: Vec<(PathBuf, usize)> = vec![(project_root.to_path_buf(), 0)];
while let Some((dir, depth)) = stack.pop() {
let Ok(entries) = std::fs::read_dir(&dir) else { continue };
for entry in entries.flatten() {
if !entry.file_type().is_ok_and(|t| t.is_dir()) {
continue;
}
let name = entry.file_name();
let name = name.to_string_lossy();
let path = entry.path();
if name.starts_with('.') || SKIPPED.contains(&name.as_ref()) || skip(&path) {
continue;
}
if path.join(".git").exists()
&& let Ok(Some(r)) = Repo::discover(&path)
&& r.root() == path
&& !repos.iter().any(|x| x.root() == r.root())
{
repos.push(r);
}
if depth + 1 < MAX_DEPTH {
stack.push((path, depth + 1));
}
}
}
Ok(Self::new(repos, project_root))
}
/// Only the repository containing `project_root` (the quick lookup on project open).
pub fn enclosing(project_root: &Path) -> IdeResult<Self> {
Ok(Self::new(Repo::discover(project_root)?.into_iter().collect(), project_root))
}
/// Worktree roots, sorted.
pub fn roots(&self) -> Vec<PathBuf> {
self.repos.iter().map(|r| r.root().to_path_buf()).collect()
}
fn new(mut repos: Vec<Repo>, project_root: &Path) -> Self {
repos.sort_by(|a, b| a.root().cmp(b.root()));
let repos: Vec<Arc<Repo>> = repos.into_iter().map(Arc::new).collect();
let roots: Vec<&Path> = repos.iter().map(|r| r.root()).collect();
let primary = innermost(&roots, project_root, false).or((!repos.is_empty()).then_some(0));
Self { repos, primary }
}
pub fn is_empty(&self) -> bool {
self.repos.is_empty()
}
pub fn all(&self) -> &[Arc<Repo>] {
&self.repos
}
/// The repository of the project root, else the first one.
pub fn primary(&self) -> Option<&Arc<Repo>> {
self.primary.map(|i| &self.repos[i])
}
/// The innermost repository containing `path` (a file or folder). A nested repository's
/// root is an entry of the enclosing repository (a submodule or untracked folder there), so
/// it belongs to that one; to the repository itself only when nothing encloses it.
pub fn for_path(&self, path: &Path) -> Option<&Arc<Repo>> {
let roots: Vec<&Path> = self.repos.iter().map(|r| r.root()).collect();
let found = innermost(&roots, path, true).or_else(|| {
// Another spelling of the same location (symlinks, /var vs /private/var).
let canon = dunce::canonicalize(path).ok()?;
let roots: Vec<PathBuf> =
roots.iter().map(|r| dunce::canonicalize(r).unwrap_or_else(|_| r.to_path_buf())).collect();
innermost(&roots.iter().map(PathBuf::as_path).collect::<Vec<_>>(), &canon, true)
});
found.map(|i| &self.repos[i])
}
/// The repository whose worktree root is `root` (the repository a repository-scoped
/// command was given).
pub fn at_root(&self, root: &Path) -> Option<&Arc<Repo>> {
self.repos.iter().find(|r| r.root() == root).or_else(|| {
let canon = dunce::canonicalize(root).ok()?;
self.repos.iter().find(|r| dunce::canonicalize(r.root()).is_ok_and(|r| r == canon))
})
}
/// `paths` grouped by the repository each belongs to (paths outside every repository are dropped).
pub fn group(&self, paths: &[PathBuf]) -> Vec<(Arc<Repo>, Vec<PathBuf>)> {
let mut out: Vec<(Arc<Repo>, Vec<PathBuf>)> = Vec::new();
for p in paths {
let Some(repo) = self.for_path(p) else { continue };
match out.iter_mut().find(|(r, _)| Arc::ptr_eq(r, repo)) {
Some((_, list)) => list.push(p.clone()),
None => out.push((repo.clone(), vec![p.clone()])),
}
}
out
}
/// Changes of every repository. A nested repository reports its own files, so the
/// enclosing one's "untracked folder" entry for it is dropped. A repository that cannot
/// be read (e.g. deleted since the last scan) is left out; fails only when all fail.
pub fn status(&self) -> IdeResult<Vec<FileStatus>> {
let mut out = Vec::new();
let mut first_error = None;
let mut read = 0;
for repo in &self.repos {
let nested: Vec<&Path> = self
.repos
.iter()
.map(|r| r.root())
.filter(|r| *r != repo.root() && r.starts_with(repo.root()))
.collect();
let status = match repo.status() {
Ok(status) => {
read += 1;
status
}
Err(e) => {
tracing::warn!("git status of {}: {e}", repo.root().display());
first_error.get_or_insert(e);
continue;
}
};
out.extend(status.into_iter().filter(|f| {
let untracked_root =
f.unstaged == Some(crate::ChangeKind::Untracked) && nested.iter().any(|n| f.path.0 == *n);
!untracked_root
}));
}
match first_error {
Some(e) if read == 0 => Err(e),
_ => Ok(out),
}
}
}
/// Index of the innermost of `roots` containing `path`. With `strict`, a root equal to
/// `path` counts only when no other root contains it.
fn innermost(roots: &[&Path], path: &Path, strict: bool) -> Option<usize> {
let best = |strict: bool| {
roots
.iter()
.enumerate()
.filter(|(_, r)| path.starts_with(r) && !(strict && **r == path))
.max_by_key(|(_, r)| r.as_os_str().len())
.map(|(i, _)| i)
};
best(strict).or_else(|| best(false))
}
#[cfg(test)]
mod tests {
use super::*;
use std::process::Command;
fn git_init(dir: &Path) {
std::fs::create_dir_all(dir).unwrap();
let ok = Command::new("git").args(["init", "-q"]).current_dir(dir).status().is_ok_and(|s| s.success());
assert!(ok, "git init in {}", dir.display());
}
#[test]
fn finds_nested_repositories_and_routes_paths() {
let tmp = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(tmp.path()).unwrap();
git_init(&root);
git_init(&root.join("services/api"));
git_init(&root.join("web"));
git_init(&root.join("node_modules/dep"));
git_init(&root.join(".cache/repo"));
std::fs::write(root.join("services/api/main.rs"), "fn main() {}").unwrap();
std::fs::write(root.join("README.md"), "x").unwrap();
let repos = Repos::discover(&root, &|_| false).unwrap();
let roots: Vec<&Path> = repos.all().iter().map(|r| r.root()).collect();
assert_eq!(roots, [root.as_path(), &root.join("services/api"), &root.join("web")]);
assert_eq!(repos.primary().unwrap().root(), root);
assert_eq!(repos.for_path(&root.join("services/api/main.rs")).unwrap().root(), root.join("services/api"));
assert_eq!(repos.for_path(&root.join("services/other.txt")).unwrap().root(), root);
// A nested root is the enclosing repository's entry (submodule / untracked folder).
assert_eq!(repos.for_path(&root.join("services/api")).unwrap().root(), root);
assert_eq!(repos.for_path(&root).unwrap().root(), root);
assert_eq!(repos.at_root(&root.join("services/api")).unwrap().root(), root.join("services/api"));
assert!(repos.at_root(&root.join("services")).is_none());
let status = repos.status().unwrap();
let paths: Vec<String> =
status.iter().map(|f| f.path.0.strip_prefix(&root).unwrap().to_string_lossy().replace('\\', "/")).collect();
assert!(paths.contains(&"README.md".to_owned()), "{paths:?}");
assert!(paths.contains(&"services/api/main.rs".to_owned()), "{paths:?}");
assert!(
!paths.iter().any(|p| p.trim_end_matches('/') == "web"),
"nested root is not an untracked folder: {paths:?}"
);
let groups = repos.group(&[root.join("README.md"), root.join("services/api/main.rs"), root.join("web/x")]);
assert_eq!(groups.len(), 3);
assert_eq!(groups[1].1, [root.join("services/api/main.rs")]);
let skipped = Repos::discover(&root, &|p| p.ends_with("services")).unwrap();
assert_eq!(skipped.all().len(), 2);
}
#[test]
fn side_by_side_repositories_without_an_enclosing_one() {
let tmp = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(tmp.path()).unwrap();
git_init(&root.join("a"));
git_init(&root.join("b"));
let repos = Repos::discover(&root, &|_| false).unwrap();
assert_eq!(repos.all().len(), 2);
assert_eq!(repos.primary().unwrap().root(), root.join("a"), "the first when none contains the project root");
assert!(repos.for_path(&root.join("c.txt")).is_none());
}
}
+7
Переглянути файл
@@ -18,6 +18,7 @@ pub(crate) fn status(r: &Repo) -> IdeResult<Vec<FileStatus>> {
let repo = r.gix()?;
let mut map: BTreeMap<String, Entry> = BTreeMap::new();
let mut conflicts: HashSet<String> = HashSet::new();
let ignored = r.ignored.read().unwrap_or_else(|p| p.into_inner()).clone();
let platform = repo
.status(gix::progress::Discard)
@@ -50,6 +51,9 @@ pub(crate) fn status(r: &Repo) -> IdeResult<Vec<FileStatus>> {
continue;
}
let mut path = to_string(entry.rela_path.as_ref());
if ignored.is_ignored_path(&path) {
continue;
}
if entry.disk_kind.is_some_and(|k| k.is_dir()) && !path.ends_with('/') {
path.push('/');
}
@@ -87,7 +91,10 @@ pub(crate) fn status(r: &Repo) -> IdeResult<Vec<FileStatus>> {
}
}
// Persist refreshed stat info so the next status is cheaper (like `git status` does).
// Only when something changed: `write_changes` writes even an empty change set, and
// the rewritten `.git/index` comes back as a VCS change that triggers the next status.
if let Some(mut outcome) = iter.into_outcome()
&& outcome.has_changes()
&& let Some(Err(e)) = outcome.write_changes()
{
tracing::debug!("could not write refreshed index: {e}");
+12 -5
Переглянути файл
@@ -2,7 +2,7 @@
use crate::cli::{self, run};
use crate::repo::{gx, resolve};
use crate::{BlameLine, Repo};
use crate::{BlameLine, CommitOptions, Repo};
use gix::bstr::{BStr, ByteSlice};
use ide_core::{CancellationToken, IdeError, IdeResult};
use std::path::{Path, PathBuf};
@@ -222,15 +222,22 @@ pub(crate) fn discard(r: &Repo, paths: &[PathBuf]) -> IdeResult<()> {
Ok(())
}
pub(crate) fn commit(r: &Repo, message: &str, amend: bool, sign_off: bool) -> IdeResult<String> {
pub(crate) fn commit(r: &Repo, message: &str, options: &CommitOptions) -> IdeResult<String> {
let mut args = vec!["commit", "-q", "--cleanup=whitespace"];
if amend {
if options.amend {
args.push("--amend");
}
if sign_off {
if options.sign_off {
args.push("--signoff");
}
let stdin = if amend && message.trim().is_empty() {
if !options.run_hooks {
args.push("--no-verify");
}
let author = options.author.as_deref().map(str::trim).filter(|a| !a.is_empty()).map(|a| format!("--author={a}"));
if let Some(a) = &author {
args.push(a.as_str());
}
let stdin = if options.amend && message.trim().is_empty() {
args.push("--no-edit");
None
} else {
+47
Переглянути файл
@@ -145,6 +145,26 @@ fn repository_without_commits() {
assert!(repo.status().unwrap().is_empty());
}
#[test]
fn status_leaves_an_up_to_date_index_alone() {
// The watcher reports `.git/index` writes as VCS changes, which refresh the
// status: rewriting it unconditionally made that a loop.
let fx = Fixture::new();
fx.write("a.txt", "a\n");
// Older than the index, so it isn't racily clean (that settles after a write or two).
let past = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
std::fs::File::options().write(true).open(fx.path("a.txt")).unwrap().set_modified(past).unwrap();
fx.commit_all("init");
let repo = fx.repo();
repo.status().unwrap(); // may persist refreshed stat info once
let index = fx.path(".git/index");
let before = std::fs::metadata(&index).unwrap().modified().unwrap();
for _ in 0..3 {
assert!(repo.status().unwrap().is_empty());
}
assert_eq!(std::fs::metadata(&index).unwrap().modified().unwrap(), before);
}
#[test]
fn status_matrix() {
let fx = Fixture::new();
@@ -172,8 +192,12 @@ fn status_matrix() {
fx.write("dir/nested/untracked2.txt", "u\n");
fx.write("debug.log", "ignored\n");
fx.write("build/out.bin", "ignored\n");
fx.write(".DS_Store", "junk");
fx.write("dir/.DS_Store", "junk");
fx.write("pkg/__pycache__/m.pyc", "junk");
let repo = fx.repo();
repo.set_ignored_names(ide_core::settings::Settings::default().ignored_names());
let st = repo.status().unwrap();
let check = |rel: &str, staged: Option<ChangeKind>, unstaged: Option<ChangeKind>| {
let s = status_of(&st, rel);
@@ -193,6 +217,7 @@ fn status_matrix() {
assert_eq!(status_of(&st, "renamed.txt").renamed_from.as_deref(), Some("rename_me.txt"));
assert!(!st.iter().any(|s| s.rel_path == "rename_me.txt"), "rename source listed: {st:#?}");
assert!(!st.iter().any(|s| s.rel_path.contains("debug.log") || s.rel_path.contains("build")));
assert!(!st.iter().any(|s| s.rel_path.contains(".DS_Store") || s.rel_path.contains("pkg")), "{st:#?}");
// Sorted by path.
let paths: Vec<_> = st.iter().map(|s| s.rel_path.clone()).collect();
let mut sorted = paths.clone();
@@ -682,6 +707,28 @@ fn commit_amend_and_signoff() {
assert!(repo.commit("nothing", false, false).is_err());
}
#[test]
fn commit_with_author_and_without_hooks() {
let fx = Fixture::new();
fx.write("a", "1\n");
fx.commit_all("init");
let hook = fx.path(".git/hooks/pre-commit");
std::fs::write(&hook, "#!/bin/sh\nexit 1\n").unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&hook, std::fs::Permissions::from_mode(0o755)).unwrap();
}
let repo = fx.repo();
fx.write("a", "2\n");
repo.stage(&[fx.path("a")]).unwrap();
let hooked = CommitOptions { run_hooks: true, ..Default::default() };
assert!(repo.commit_with("blocked", &hooked).is_err(), "the failing pre-commit hook runs");
let options = CommitOptions { author: Some(" Other <[email protected]> ".into()), ..Default::default() };
repo.commit_with("by other", &options).unwrap();
assert_eq!(fx.git(&["log", "-1", "--format=%an <%ae>"]), "Other <[email protected]>");
}
#[test]
fn checkout_create_detached_delete_rebase() {
let fx = Fixture::new();
+3
Переглянути файл
@@ -0,0 +1,3 @@
# Per-user IDE state
/shelf/
/changelists.json
+10
Переглянути файл
@@ -5,9 +5,19 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>OpenIDEA</title>
<script src="/boot.js"></script>
<link rel="stylesheet" href="/splash.css" />
</head>
<body>
<div id="root"></div>
<div id="splash" class="splash" data-tauri-drag-region>
<svg viewBox="0 0 64 64" aria-hidden="true">
<rect width="64" height="64" rx="15" fill="#0E0E10" />
<circle cx="26" cy="32" r="11" fill="none" stroke="#FFFFFF" stroke-width="8" />
<rect x="43" y="18" width="8" height="28" rx="1.5" fill="#FF4F1A" />
</svg>
<span>OpenIDEA</span>
<div class="splash-bar" role="progressbar" aria-label="Loading"><i></i></div>
</div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
+1 -1
Переглянути файл
@@ -14,6 +14,6 @@ root-markers = ["mix.exs"]
install-hint = "Install ElixirLS (https://github.com/elixir-lsp/elixir-ls/releases) and expose language_server.sh as `elixir-ls`"
[debugger]
adapter = "elixir-ls"
adapter = "elixir-ls-debugger"
command = "elixir-ls-debugger"
install-hint = "Install ElixirLS and expose debug_adapter.sh as `elixir-ls-debugger`"
+1 -1
Переглянути файл
@@ -2,7 +2,7 @@
"name": "openidea",
"private": true,
"description": "An open-source IDE inspired by IntelliJ IDEA",
"version": "0.1.2",
"version": "0.1.7",
"license": "Apache-2.0",
"type": "module",
"scripts": {
+2
Переглянути файл
@@ -0,0 +1,2 @@
results/
__pycache__/
+51
Переглянути файл
@@ -0,0 +1,51 @@
# IDE comparison
`pnpm perf` measures OpenIDEA from inside its webview. This measures any IDE
from the outside, the same way for each, so OpenIDEA can be compared with
IntelliJ IDEA (or anything else listed in `apps.toml`).
```sh
pip install -r perf/compare/requirements.txt
python perf/compare/bench.py ~/src/spring-petclinic --runs 10
python perf/compare/bench.py ~/src/spring-petclinic --runs 5 --wipe-caches # cold index
```
Each run launches the app on the project, waits until it is ready, idles,
closes it, and records:
| Metric | How |
|---|---|
| `window_s` | first visible window whose title matches `window_title` (the project name) |
| `ready_s` | the process tree's CPU stays under `--quiet-cores` for `--quiet-secs`, after the window and any `ready_after` markers |
| markers | first/last time a log line matches, e.g. OpenIDEA `indexed`, IDEA `exit dumb mode` |
| `peak_rss_mb`, `rss_mb`, `uss_mb`, `pss_mb` | summed over every process the app started (WebView2/WebKit, jdtls, language servers, the JVM) |
| `total_cpu_s`, `idle_cpu_pct` | CPU time until ready; CPU while idle for `--idle-secs` |
| `exit_s` | until every process has exited |
| `cache_mb`, install size | `cache_dirs`, `install_dir` |
Apps run interleaved, rotating the order, after `--warmup` discarded runs.
Output goes to `results/<time>-<project>/`: `report.md` (median, min–max),
`results.json`, and each run's stdout.
## Fair runs
- Release builds only; a running instance of the same executable (a
`pnpm tauri dev` build too) would take over the launch, so the script refuses.
- IDEA: open the project once by hand and trust it; turn off *Reopen projects
on startup* and *Confirm before exiting*; note the version, `-Xmx` and whether
Shared Indexes were on.
- Same machine, power plan and plugged in; exclude the project and caches from
antivirus scanning, or neither.
- `--drop-os-cache` runs a command before each launch for a cold OS cache:
`sync; echo 3 | sudo tee /proc/sys/vm/drop_caches` (Linux), `sudo purge`
(macOS), `RAMMap64.exe -Et` (Windows, admin).
- Typing latency is not covered: measure it on screen with Typometer for both.
## Platform notes
- Windows: windows via `user32`, closed with `WM_CLOSE`.
- macOS: windows via Quartz (`pyobjc-framework-Quartz`; titles need Screen
Recording permission). WebKit helpers are children of launchd and are
attributed through `responsibility_get_pid_responsible_for_pid`.
- Linux: windows via `wmctrl` (X11). Without it `window_s` is skipped and
readiness counts from launch.
+43
Переглянути файл
@@ -0,0 +1,43 @@
# Apps compared by bench.py. Any value can be a { windows, macos, linux } table.
# Placeholders: {project} (absolute path), {project_name} (its directory name);
# ~ and environment variables are expanded.
#
# command executable, launched directly (not through a shell or `open`)
# args default ["{project}"]
# window_title regex; the first visible window whose title matches marks "window_s"
# logs globs of log files to watch, besides the app's stdout
# markers name → regex; the first and last matching log line time is recorded
# ready_after markers that must have appeared before "ready" can be declared
# cache_dirs globs deleted by --wipe-caches, and measured for "cache_mb"
# install_dir measured once for the install size
# quit_command instead of WM_CLOSE (Windows) / SIGTERM (macOS, Linux)
# daemons process names meant to outlive the app (not waited for or killed on exit)
# single_instance default true: refuse to start while a process with the same
# executable name runs (it would take over the launch)
[apps.openidea]
name = "OpenIDEA"
command = { windows = "%LOCALAPPDATA%/OpenIDEA/openidea.exe", macos = "/Applications/OpenIDEA.app/Contents/MacOS/openidea", linux = "/usr/bin/openidea" }
install_dir = { windows = "%LOCALAPPDATA%/OpenIDEA", macos = "/Applications/OpenIDEA.app" }
logs = { windows = "%LOCALAPPDATA%/ai.l0ng.openidea/logs/openidea*.log", macos = "~/Library/Logs/ai.l0ng.openidea/openidea*.log", linux = "~/.local/share/ai.l0ng.openidea/logs/openidea*.log" }
# The index and build caches. jdtls keeps its own workspace under lsp/jdtls,
# next to the jdtls install, so a cold Java run still reuses jdtls's build state.
cache_dirs = { windows = ["%APPDATA%/ai.l0ng.openidea/index", "%APPDATA%/ai.l0ng.openidea/cache"], macos = ["~/Library/Application Support/ai.l0ng.openidea/index", "~/Library/Application Support/ai.l0ng.openidea/cache"], linux = ["~/.local/share/ai.l0ng.openidea/index", "~/.local/share/ai.l0ng.openidea/cache"] }
[apps.openidea.markers]
project_opened = 'opened .* in window'
indexed = 'indexed \d+ files'
lsp_initialized = 'initialized: \{'
[apps.idea]
name = "IntelliJ IDEA"
command = { windows = "C:/Program Files/JetBrains/IntelliJ IDEA 2026.2.3/bin/idea64.exe", macos = "/Applications/IntelliJ IDEA.app/Contents/MacOS/idea", linux = "~/idea/bin/idea" }
daemons = ["jetbrainsd.exe", "jetbrainsd"]
install_dir = { windows = "C:/Program Files/JetBrains/IntelliJ IDEA 2026.2.3", macos = "/Applications/IntelliJ IDEA.app", linux = "~/idea" }
logs = { windows = "%LOCALAPPDATA%/JetBrains/IntelliJIdea2026.2/log/idea.log", macos = "~/Library/Logs/JetBrains/IntelliJIdea2026.2/idea.log", linux = "~/.cache/JetBrains/IntelliJIdea2026.2/log/idea.log" }
# The VFS and the indexes (the whole "system" dir also holds logs and local history).
cache_dirs = { windows = ["%LOCALAPPDATA%/JetBrains/IntelliJIdea2026.2/caches", "%LOCALAPPDATA%/JetBrains/IntelliJIdea2026.2/index"], macos = ["~/Library/Caches/JetBrains/IntelliJIdea2026.2/caches", "~/Library/Caches/JetBrains/IntelliJIdea2026.2/index"], linux = ["~/.cache/JetBrains/IntelliJIdea2026.2/caches", "~/.cache/JetBrains/IntelliJIdea2026.2/index"] }
[apps.idea.markers]
# Indexing done: IDEA leaves dumb mode, possibly several times; compare "last".
smart = 'exit dumb mode \[{project_name}\]'
+614
Переглянути файл
@@ -0,0 +1,614 @@
#!/usr/bin/env python3
"""Black-box IDE comparison: startup, readiness, memory, idle CPU, disk.
Launches each app from apps.toml on the same project, measures it from the
outside (process tree, window list, log lines), closes it, and repeats with
the apps interleaved. Runs on Windows, macOS and Linux; see README.md.
"""
from __future__ import annotations
import argparse
import collections
import ctypes
import datetime as dt
import glob
import json
import os
import platform
import re
import shutil
import signal
import statistics
import subprocess
import sys
import time
import tomllib
from pathlib import Path
try:
import psutil
except ImportError:
sys.exit("psutil is required: pip install -r perf/compare/requirements.txt")
OS = {"Windows": "windows", "Darwin": "macos", "Linux": "linux"}[platform.system()]
HERE = Path(__file__).resolve().parent
ANSI = re.compile(r"\x1b\[[0-9;?]*[A-Za-z]")
GONE = (psutil.NoSuchProcess, psutil.ZombieProcess, psutil.AccessDenied)
MB = 1024 * 1024
POLL_S = 0.2
# ── config ──────────────────────────────────────────────────────────────────
def per_os(value):
"""A value, or a {windows, macos, linux} table of per-platform values."""
if isinstance(value, dict) and value and value.keys() <= {"windows", "macos", "linux"}:
return value.get(OS)
return value
def as_list(value) -> list:
return [] if value is None else [value] if isinstance(value, str) else list(value)
def expand(s: str, project: Path) -> str:
s = s.replace("{project}", str(project)).replace("{project_name}", project.name)
return os.path.expandvars(os.path.expanduser(s))
def pattern(s: str, project: Path) -> re.Pattern:
return re.compile(s.replace("{project_name}", re.escape(project.name)))
class App:
def __init__(self, key: str, raw: dict, project: Path):
self.key = key
self.name = raw.get("name", key)
command = per_os(raw.get("command"))
if not command:
raise SystemExit(f"apps.{key}: no command for {OS}")
args = per_os(raw.get("args", ["{project}"]))
self.command = [expand(command, project), *(expand(a, project) for a in args)]
self.logs = [expand(g, project) for g in as_list(per_os(raw.get("logs")))]
self.markers = {k: pattern(v, project) for k, v in raw.get("markers", {}).items()}
self.ready_after = as_list(raw.get("ready_after"))
self.window_title = pattern(raw.get("window_title", "{project_name}"), project)
self.cache_dirs = [expand(d, project) for d in as_list(per_os(raw.get("cache_dirs")))]
self.install_dir = per_os(raw.get("install_dir"))
self.install_dir = expand(self.install_dir, project) if self.install_dir else None
self.quit_command = as_list(per_os(raw.get("quit_command")))
self.single_instance = raw.get("single_instance", True)
self.daemons = {n.lower() for n in as_list(raw.get("daemons"))}
unknown = set(self.ready_after) - self.markers.keys()
if unknown:
raise SystemExit(f"apps.{key}.ready_after names unknown markers: {sorted(unknown)}")
def cache_paths(self) -> list[Path]:
return [Path(p) for d in self.cache_dirs for p in sorted(glob.glob(d))]
# ── windows ─────────────────────────────────────────────────────────────────
if OS == "windows":
from ctypes import wintypes
_user32 = ctypes.WinDLL("user32")
_ENUM = ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.HWND, wintypes.LPARAM)
_user32.EnumWindows.argtypes = [_ENUM, wintypes.LPARAM]
_user32.IsWindowVisible.argtypes = [wintypes.HWND]
_user32.GetWindowThreadProcessId.argtypes = [wintypes.HWND, ctypes.POINTER(wintypes.DWORD)]
_user32.GetWindowTextLengthW.argtypes = [wintypes.HWND]
_user32.GetWindowTextW.argtypes = [wintypes.HWND, wintypes.LPWSTR, ctypes.c_int]
_user32.PostMessageW.argtypes = [wintypes.HWND, wintypes.UINT, wintypes.WPARAM, wintypes.LPARAM]
def _win_windows(pids: set[int]) -> list[tuple[object, str]]:
found = []
def visit(hwnd, _):
if _user32.IsWindowVisible(hwnd):
pid = wintypes.DWORD()
_user32.GetWindowThreadProcessId(hwnd, ctypes.byref(pid))
if pid.value in pids:
buf = ctypes.create_unicode_buffer(_user32.GetWindowTextLengthW(hwnd) + 1)
_user32.GetWindowTextW(hwnd, buf, len(buf))
found.append((hwnd, buf.value))
return True
_user32.EnumWindows(_ENUM(visit), 0)
return found
def _mac_windows(pids: set[int]) -> list[tuple[object, str]] | None:
try:
import Quartz
except ImportError:
return None
infos = Quartz.CGWindowListCopyWindowInfo(
Quartz.kCGWindowListOptionOnScreenOnly | Quartz.kCGWindowListExcludeDesktopElements, Quartz.kCGNullWindowID
)
# Titles need the Screen Recording permission; without it they come back empty.
return [
(None, str(w.get("kCGWindowName") or ""))
for w in infos
if w.get("kCGWindowOwnerPID") in pids and w.get("kCGWindowLayer") == 0
]
def _x11_windows(pids: set[int]) -> list[tuple[object, str]] | None:
if not shutil.which("wmctrl"):
return None
try:
out = subprocess.run(["wmctrl", "-lp"], capture_output=True, text=True, timeout=2).stdout
except (OSError, subprocess.TimeoutExpired):
return None
found = []
for line in out.splitlines():
parts = line.split(None, 4)
if len(parts) >= 4 and parts[2].isdigit() and int(parts[2]) in pids:
found.append((parts[0], parts[4] if len(parts) > 4 else ""))
return found
def visible_windows(pids: set[int]) -> list[tuple[object, str]] | None:
"""(handle, title) of the visible top-level windows owned by `pids`; None when this platform can't tell."""
if OS == "windows":
return _win_windows(pids)
if OS == "macos":
return _mac_windows(pids)
return _x11_windows(pids)
# ── process tree ────────────────────────────────────────────────────────────
_responsible = None
if OS == "macos":
try:
_responsible = ctypes.CDLL("/usr/lib/libSystem.B.dylib").responsibility_get_pid_responsible_for_pid
_responsible.argtypes = [ctypes.c_int]
_responsible.restype = ctypes.c_int
except (OSError, AttributeError):
_responsible = None
class Tree:
"""Every process the app started, including ones whose parent already exited.
On macOS, WKWebView's helper processes are children of launchd, so they are
attributed through the responsible-pid API (or, failing that, by name and
start time).
"""
def __init__(self, root: psutil.Process, started: float):
self.root = root
self.started = started
self.procs: dict[tuple[int, float], psutil.Process] = {}
self.cpu: dict[tuple[int, float], float] = {}
self.cpu_exited = 0.0
def _discover(self):
found = [self.root]
for p in list(self.procs.values()):
try:
found += p.children(recursive=True)
except GONE:
pass
if OS == "macos":
found += self._webkit()
for p in found:
try:
self.procs.setdefault((p.pid, p.create_time()), p)
except GONE:
pass
def _webkit(self) -> list[psutil.Process]:
out = []
for p in psutil.process_iter(["name", "create_time"]):
if not (p.info["name"] or "").startswith("com.apple.WebKit"):
continue
if _responsible:
if _responsible(p.pid) == self.root.pid:
out.append(p)
elif (p.info["create_time"] or 0) >= self.started - 1:
out.append(p)
return out
def sample(self) -> tuple[float, int]:
"""(total CPU seconds ever used by the tree, current summed RSS bytes)."""
self._discover()
rss = 0
for key, p in list(self.procs.items()):
try:
with p.oneshot():
t = p.cpu_times()
self.cpu[key] = t.user + t.system
rss += p.memory_info().rss
except GONE:
self.cpu_exited += self.cpu.pop(key, 0.0)
del self.procs[key]
return self.cpu_exited + sum(self.cpu.values()), rss
def pids(self) -> set[int]:
return {pid for pid, _ in self.procs}
def alive(self) -> list[psutil.Process]:
return [p for p in self.procs.values() if p.is_running()]
def memory(self) -> dict:
"""Summed memory of the live tree. RSS double-counts shared pages, USS leaves them out."""
rss = uss = pss = 0
by_name: dict[str, int] = collections.Counter()
count = 0
for p in self.alive():
try:
full = p.memory_full_info()
except GONE:
continue
count += 1
rss += full.rss
uss += full.uss
pss += getattr(full, "pss", 0)
by_name[p.name()] += full.uss
out = {"rss_mb": rss / MB, "uss_mb": uss / MB, "procs": count}
if OS == "linux":
out["pss_mb"] = pss / MB
out["uss_by_process_mb"] = {k: round(v / MB, 1) for k, v in by_name.most_common()}
return out
# ── logs ────────────────────────────────────────────────────────────────────
class LogTail:
"""New lines appended to the files matching some globs since construction."""
def __init__(self, globs: list[str], extra: list[Path]):
self.globs = globs
self.extra = extra
self.offsets: dict[str, int] = {}
self.partial: dict[str, str] = {}
for path in self._paths():
self.offsets[path] = os.path.getsize(path)
def _paths(self) -> list[str]:
paths = [p for g in self.globs for p in glob.glob(g)]
return paths + [str(p) for p in self.extra if p.exists()]
def lines(self) -> list[str]:
out = []
for path in self._paths():
try:
with open(path, "rb") as f:
f.seek(self.offsets.get(path, 0))
chunk = f.read()
self.offsets[path] = f.tell()
except OSError:
continue
if not chunk:
continue
text = self.partial.pop(path, "") + chunk.decode("utf-8", "replace")
*complete, rest = text.split("\n")
if rest:
self.partial[path] = rest
out += [ANSI.sub("", line) for line in complete]
return out
# ── one run ─────────────────────────────────────────────────────────────────
def running_instances(app: App) -> list[psutil.Process]:
"""Processes with the app's executable name, from any install or build: a
single-instance app hands the launch to them even when the paths differ."""
name = os.path.normcase(Path(app.command[0]).name)
return [p for p in psutil.process_iter(["name"]) if os.path.normcase(p.info["name"] or "") == name]
def dir_size(path: Path) -> int:
if path.is_file():
return path.stat().st_size
total = 0
for root, _, files in os.walk(path):
for f in files:
try:
total += os.lstat(os.path.join(root, f)).st_size
except OSError:
pass
return total
def close(app: App, tree: Tree, proc: subprocess.Popen, timeout: float) -> tuple[float | None, list[str]]:
"""Asks the app to quit, waits for the whole tree, kills what's left.
Returns (seconds until every process exited, or None if it had to kill; names of killed leftovers).
"""
t0 = time.perf_counter()
if app.quit_command:
subprocess.run(app.quit_command, check=False)
elif OS == "windows":
# Only the project windows: closing a framework's hidden message windows
# (Tauri's single-instance and event-target ones) stalls the real shutdown.
for hwnd, title in _win_windows(tree.pids()):
if app.window_title.search(title):
_user32.PostMessageW(hwnd, 0x0010, 0, 0) # WM_CLOSE
else:
proc.send_signal(signal.SIGTERM)
def remaining() -> list[psutil.Process]:
out = []
for p in tree.alive():
try:
if p.name().lower() not in app.daemons:
out.append(p)
except GONE:
pass
return out
while time.perf_counter() - t0 < timeout:
tree.sample()
if not remaining():
return time.perf_counter() - t0, []
time.sleep(POLL_S)
leftovers = remaining()
names = []
for p in leftovers:
try:
names.append(p.name())
p.kill()
except GONE:
pass
psutil.wait_procs(leftovers, timeout=10)
return None, names
def run_once(app: App, args, out_dir: Path, label: str) -> dict:
running = running_instances(app) if app.single_instance else []
if running:
pids = ", ".join(str(p.pid) for p in running)
raise SystemExit(f"{app.name} is already running (pid {pids}); close it first, it would take over the launch.")
if args.wipe_caches:
for path in app.cache_paths():
shutil.rmtree(path, ignore_errors=True) if path.is_dir() else path.unlink(missing_ok=True)
if args.drop_os_cache:
subprocess.run(args.drop_os_cache, shell=True, check=True)
if args.cooldown:
time.sleep(args.cooldown)
stdout_path = out_dir / f"{label}.stdout.log"
tail = LogTail(app.logs, [stdout_path])
started_wall = time.time()
with open(stdout_path, "wb") as stdout:
t0 = time.perf_counter()
proc = subprocess.Popen(app.command, stdout=stdout, stderr=subprocess.STDOUT, stdin=subprocess.DEVNULL)
tree = Tree(psutil.Process(proc.pid), started_wall)
result: dict = {"app": app.key, "label": label, "markers_first_s": {}, "markers_last_s": {}}
window_supported = True
window_s = None
history: collections.deque[tuple[float, float]] = collections.deque()
peak_rss = 0
ready_s = None
while True:
now = time.perf_counter() - t0
cpu, rss = tree.sample()
peak_rss = max(peak_rss, rss)
history.append((now, cpu))
while history and now - history[0][0] > args.quiet_secs:
history.popleft()
for line in tail.lines():
for name, rx in app.markers.items():
if rx.search(line):
result["markers_first_s"].setdefault(name, now)
result["markers_last_s"][name] = now
if window_s is None and window_supported:
windows = visible_windows(tree.pids())
if windows is None:
window_supported = False
elif any(app.window_title.search(title) for _, title in windows):
window_s = now
if not tree.alive():
raise SystemExit(
f"{app.name} exited during startup (code {proc.poll()}); an instance started elsewhere may have "
f"taken the launch. Output: {stdout_path}"
)
waited = (window_s is not None or not window_supported) and all(
m in result["markers_first_s"] for m in app.ready_after
)
span = now - history[0][0]
if waited and span >= args.quiet_secs * 0.95:
busy = (cpu - history[0][1]) / span
if busy < args.quiet_cores:
# Never before what it waited for (the quiet span can start earlier).
ready_s = max(now - span, window_s or 0, *(result["markers_first_s"][m] for m in app.ready_after))
break
if now > args.timeout:
result["timed_out"] = True
break
time.sleep(POLL_S)
result["window_s"] = window_s
result["ready_s"] = ready_s
result["peak_rss_mb"] = peak_rss / MB
# Idle: what it costs to just sit there with the project open.
idle_cpu0, _ = tree.sample()
i0 = time.perf_counter()
while time.perf_counter() - i0 < args.idle_secs:
time.sleep(POLL_S * 5)
_, rss = tree.sample()
peak_rss = max(peak_rss, rss)
idle_cpu1, _ = tree.sample()
result["idle_cpu_pct"] = 100 * (idle_cpu1 - idle_cpu0) / (time.perf_counter() - i0)
result["peak_rss_mb"] = peak_rss / MB
result.update(tree.memory())
result["total_cpu_s"] = idle_cpu0
exit_s, killed = close(app, tree, proc, args.close_timeout)
result["exit_s"] = exit_s
if killed:
result["killed_on_exit"] = killed
result["cache_mb"] = sum(dir_size(p) for p in app.cache_paths()) / MB
return result
# ── report ──────────────────────────────────────────────────────────────────
METRICS = [
("window_s", "Window with project title (s)"),
("ready_s", "Ready: CPU settled (s)"),
("peak_rss_mb", "Peak RSS, startup + idle (MB)"),
("rss_mb", "RSS after idle (MB)"),
("uss_mb", "USS after idle (MB)"),
("pss_mb", "PSS after idle (MB)"),
("procs", "Processes"),
("total_cpu_s", "CPU used until ready (s)"),
("idle_cpu_pct", "Idle CPU (% of a core)"),
("exit_s", "Exit (s)"),
("cache_mb", "Cache dirs on disk (MB)"),
]
def fmt(value: float | None) -> str:
return "–" if value is None else f"{value:.2f}"
def summarize(values: list[float]) -> str:
if not values:
return "–"
med = statistics.median(values)
if len(values) == 1:
return f"{med:.2f}"
return f"{med:.2f} ({min(values):.2f}–{max(values):.2f})"
def report(apps: list[App], runs: list[dict], meta: dict) -> str:
def column(app: App, getter) -> str:
vals = [v for r in runs if r["app"] == app.key and (v := getter(r)) is not None]
return summarize(vals)
rows = [(title, lambda r, k=key: r.get(k)) for key, title in METRICS]
for app in apps:
for m in app.markers:
rows.append((f"{app.name}: log `{m}` first (s)", lambda r, m=m: r["markers_first_s"].get(m)))
rows.append((f"{app.name}: log `{m}` last (s)", lambda r, m=m: r["markers_last_s"].get(m)))
lines = [
f"# IDE benchmark: {meta['project']}",
"",
f"{meta['os']} · {meta['cpu']} · {meta['cores']} cores · {meta['ram_gb']:.0f} GB RAM · "
f"mode **{meta['mode']}** · {meta['runs']} runs · {meta['date']}",
"",
"Median (min–max). Times are seconds from launch.",
"",
"| Metric | " + " | ".join(a.name for a in apps) + " |",
"|---|" + "---|" * len(apps),
]
for title, getter in rows:
cells = [column(a, getter) for a in apps]
if any(c != "–" for c in cells):
lines.append(f"| {title} | " + " | ".join(cells) + " |")
for app in apps:
if app.install_dir and Path(app.install_dir).exists():
lines.append(f"\n{app.name} install size: {dir_size(Path(app.install_dir)) / MB:.0f} MB")
timeouts = [r["label"] for r in runs if r.get("timed_out")]
if timeouts:
lines.append(f"\n⚠ CPU never settled within the timeout: {', '.join(timeouts)}")
killed = [f"{r['label']}: {', '.join(r['killed_on_exit'])}" for r in runs if r.get("killed_on_exit")]
if killed:
lines.append("\n⚠ Killed after the exit timeout: " + "; ".join(killed))
return "\n".join(lines) + "\n"
# ── main ────────────────────────────────────────────────────────────────────
def main():
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("project", type=Path, help="project directory every app opens")
ap.add_argument("--config", type=Path, default=HERE / "apps.toml")
ap.add_argument("--apps", help="comma-separated keys from the config (default: all)")
ap.add_argument("--runs", type=int, default=5, help="measured runs per app (default 5)")
ap.add_argument("--warmup", type=int, default=1, help="discarded runs per app first (default 1)")
ap.add_argument("--wipe-caches", action="store_true", help="delete each app's cache_dirs before every run (cold index)")
ap.add_argument("--drop-os-cache", metavar="CMD", help="shell command run before every run to drop the OS file cache")
ap.add_argument("--quiet-secs", type=float, default=5, help="CPU must stay low this long to count as ready")
ap.add_argument("--quiet-cores", type=float, default=0.1, help="'low' = below this many cores busy (default 0.1)")
ap.add_argument("--idle-secs", type=float, default=30, help="idle period measured after ready")
ap.add_argument("--timeout", type=float, default=900, help="give up waiting for ready after this many seconds")
ap.add_argument("--close-timeout", type=float, default=60)
ap.add_argument("--cooldown", type=float, default=5, help="pause before each launch")
ap.add_argument("--out", type=Path, default=HERE / "results")
ap.add_argument("--yes", action="store_true", help="don't ask before wiping caches")
args = ap.parse_args()
if hasattr(sys.stdout, "reconfigure"):
sys.stdout.reconfigure(encoding="utf-8")
project = args.project.resolve()
if not project.is_dir():
raise SystemExit(f"not a directory: {project}")
config = tomllib.loads(args.config.read_text(encoding="utf-8"))
keys = args.apps.split(",") if args.apps else list(config["apps"])
apps = [App(k, config["apps"][k], project) for k in keys]
if args.wipe_caches:
targets = [p for a in apps for p in a.cache_paths()]
for p in targets:
if len(p.resolve().parts) < 4 or p.resolve() == Path.home():
raise SystemExit(f"refusing to wipe a top-level path: {p}")
print("Before every run these will be deleted:\n " + "\n ".join(map(str, targets)))
if targets and not args.yes and input("Continue? [y/N] ").strip().lower() != "y":
return
stamp = dt.datetime.now().strftime("%Y%m%d-%H%M%S")
out_dir = args.out / f"{stamp}-{project.name}"
out_dir.mkdir(parents=True)
mode = "cold index" if args.wipe_caches else "warm"
if args.drop_os_cache:
mode += " + cold OS cache"
meta = {
"project": str(project),
"os": f"{platform.system()} {platform.release()}",
"cpu": platform.processor() or platform.machine(),
"cores": psutil.cpu_count(logical=True),
"ram_gb": psutil.virtual_memory().total / 1024**3,
"mode": mode,
"runs": args.runs,
"date": stamp,
"commands": {a.key: a.command for a in apps},
"args": {k: str(v) for k, v in vars(args).items()},
}
runs: list[dict] = []
total = args.warmup + args.runs
for i in range(total):
# Rotate the order so neither app always runs right after the other.
order = apps[i % len(apps) :] + apps[: i % len(apps)]
for app in order:
warm = i < args.warmup
label = f"{app.key}-{'warmup' if warm else 'run'}{i + 1 if warm else i - args.warmup + 1}"
print(f"[{label}] launching…", flush=True)
r = run_once(app, args, out_dir, label)
print(
f"[{label}] window {fmt(r['window_s'])} s · ready {fmt(r['ready_s'])} s · "
f"USS {r['uss_mb']:.0f} MB · idle CPU {r['idle_cpu_pct']:.1f}%",
flush=True,
)
if not warm:
runs.append(r)
(out_dir / "results.json").write_text(json.dumps({"meta": meta, "runs": runs}, indent=2), encoding="utf-8")
text = report(apps, runs, meta)
(out_dir / "report.md").write_text(text, encoding="utf-8")
print("\n" + text)
print(f"Raw results: {out_dir / 'results.json'}")
if __name__ == "__main__":
main()
+2
Переглянути файл
@@ -0,0 +1,2 @@
psutil>=6
pyobjc-framework-Quartz>=10; sys_platform == "darwin"
+5 -1
Переглянути файл
@@ -1,4 +1,4 @@
/* global document, localStorage */
/* global document, localStorage, window */
// Runs before the app's CSS loads: restores the last theme (theme.ts stores it)
// so a new window starts in it instead of flashing the light default.
// An external file because the CSP forbids inline scripts.
@@ -9,3 +9,7 @@ try {
} catch {
/* storage unavailable */
}
// Settings windows (`settings-<parent>`) load this page too: splash.css drops the logo for them.
if (window.__TAURI_INTERNALS__?.metadata?.currentWindow?.label?.startsWith("settings-")) {
document.documentElement.dataset.window = "settings";
}
+48
Переглянути файл
@@ -0,0 +1,48 @@
/* Linked, not inlined in index.html: release builds hash inline <style> blocks into the CSP,
which voids style-src 'unsafe-inline' and blocks the editor's runtime-injected styles. */
/* Start-up splash over the page until the window's launch project is open (platform/splash.ts).
Tokens aren't loaded yet, so the colours mirror --bg-frame / --fg-muted / --accent. */
/* Not on html: the canvas then takes body's (themed) background, which a fast resize shows before relayout. */
body, .splash { background: #e9eaee; }
:root[data-theme="dark"] :is(body, .splash) { background: #26282c; }
:root:is([data-theme="dark-hc"], [data-theme="dark"][data-contrast="high"]) :is(body, .splash) { background: #1a1b1e; }
.splash {
position: fixed;
inset: 0;
z-index: 2147483647;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 14px;
padding-bottom: 38px;
box-sizing: border-box;
font: 500 15px/1.2 "Inter Variable", Inter, system-ui, -apple-system, sans-serif;
color: #6c707e;
-webkit-user-select: none;
user-select: none;
cursor: default;
animation: splash-in 240ms ease-out 120ms both;
transition: opacity 160ms ease-out;
}
.splash.splash-out { opacity: 0; pointer-events: none; }
:root[data-theme^="dark"] .splash { color: #8c8f95; }
.splash svg { width: 56px; height: 56px; }
.splash-bar { width: 120px; height: 2px; border-radius: 1px; overflow: hidden; background: rgb(127 127 127 / 0.18); }
/* Fake progress: eases towards ~90% over the 4 s cap; hideSplash() fills it before fading out. */
.splash-bar > i {
display: block;
height: 100%;
background: #3871e1;
transform-origin: left;
animation: splash-fill 4s cubic-bezier(0.1, 0.7, 0.3, 1) both;
}
/* Settings window: a dialog, not a launch. Only the bar, and only if loading takes a while. */
:root[data-window="settings"] .splash { animation-delay: 400ms; }
:root[data-window="settings"] .splash > :not(.splash-bar) { display: none; }
@keyframes splash-in { from { opacity: 0; } }
@keyframes splash-fill { from { transform: scaleX(0.04); } to { transform: scaleX(0.92); } }
/* The fill stays: it grows in place, which reduced motion allows. */
@media (prefers-reduced-motion: reduce) {
.splash { animation: none; }
}
+1
Переглянути файл
@@ -16,6 +16,7 @@
"core:window:allow-set-title",
"core:window:allow-set-background-color",
"core:webview:allow-set-webview-zoom",
"core:webview:allow-set-webview-background-color",
"opener:default",
"opener:allow-reveal-item-in-dir",
"dialog:default",
+2 -4
Переглянути файл
@@ -23,11 +23,9 @@ use std::time::Instant;
use tauri::ipc::Channel;
use tauri::{State, Window};
/// Files of `scope`, minus excluded roots.
/// Files of `scope`, minus excluded roots and ignored names.
fn files_in_scope(project: &Project, scope: &SearchScope, cancel: &CancellationToken) -> IdeResult<Vec<SourceFile>> {
let excluded: Vec<String> =
project.roots().excluded_globs().iter().map(|d| format!("{}/**", d.trim_start_matches('/'))).collect();
let mask = FileMask::new(&[], &excluded)?;
let mask = FileMask::new(&[], &project.search_excludes())?;
Ok(ide_search::scope_files(&project.root, scope, &mask, None, cancel)?
.into_iter()
.map(|f| SourceFile { path: f.path, rel_path: f.rel_path })
+3 -3
Переглянути файл
@@ -71,7 +71,7 @@ pub async fn open_project(window: Window, path: PathBuf) -> IdeResult<ProjectInf
fn project_info(project: &crate::state::Project) -> ProjectInfo {
ProjectInfo {
name: project.root.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(),
is_git: project.repo.lock().is_some(),
is_git: !project.repos.read().is_empty(),
settings: project.settings.effective(),
root: project.root.clone().into(),
}
@@ -148,8 +148,8 @@ pub fn settings_set(
.set_file_defaults(ide_workspace::FileDefaults::from_settings(&effective, Some(&project.root)));
}
}
// A new interpreter / toolchain restarts the language servers it affects.
if key == "languages" || key.starts_with("languages.") {
// A new interpreter / toolchain / server executable restarts the language servers it affects.
if ["languages", "tools"].iter().any(|k| key == *k || key.starts_with(&format!("{k}."))) {
let affected = if project_scope { current.iter().cloned().collect() } else { state.projects() };
for project in affected {
let lsp = project.lsp.clone();
+32 -14
Переглянути файл
@@ -4,6 +4,7 @@
use crate::state::AppState;
use ide_build::compile::{self, BuildEvent, BuildKind, BuildResult};
use ide_build::{BuildModel, BuildTool, SyncOptions, SyncProgress};
use ide_core::settings::Settings;
use ide_core::{IdeError, IdeEvent, IdeResult, RequestId};
use std::collections::BTreeMap;
use std::path::Path;
@@ -14,22 +15,32 @@ fn join_err(e: tauri::Error) -> IdeError {
IdeError::internal(e.to_string())
}
/// `JAVA_HOME` of the installed JDK matching `release` (none when the project names no version).
fn java_env(release: Option<u32>) -> BTreeMap<String, String> {
/// `JAVA_HOME`: the project JDK, else the installed JDK matching `release` (none
/// when the project names no version).
fn java_env(project_jdk: Option<&ide_sdk::java::Jdk>, release: Option<u32>) -> BTreeMap<String, String> {
let jdks = ide_sdk::java::installed_jdks();
let jdk = release.and_then(|r| ide_sdk::java::pick_jdk(&jdks, Some(r)));
let jdk = project_jdk.or_else(|| release.and_then(|r| ide_sdk::java::pick_jdk(&jdks, Some(r))));
jdk.map(|j| BTreeMap::from([("JAVA_HOME".to_owned(), j.home.to_string_lossy().into_owned())])).unwrap_or_default()
}
pub(crate) fn load(root: &Path, cache: &Path) -> BuildModel {
let mut model = ide_build::load(root, cache);
/// The build model with the launch settings applied: the JDK (`JAVA_HOME`), and
/// the Maven home and options from Settings › Maven.
pub(crate) fn load(root: &Path, cache: &Path, settings: &Settings) -> BuildModel {
let mut model = ide_build::load(root, cache, ide_sdk::apply::maven_local_repository(root, settings));
let jdk = ide_sdk::apply::project_jdk(root, settings);
if let Some(m) = &mut model.maven {
let mvn = ide_sdk::apply::maven_command(root, settings);
let options = ide_sdk::apply::maven_options(root, settings);
for p in &mut m.projects {
p.env = java_env(p.java_version);
p.env = java_env(jdk.as_ref(), p.java_version);
if let Some(mvn) = &mvn {
p.command = mvn.to_string_lossy().into_owned();
}
p.options = options.clone();
}
}
if let Some(g) = &mut model.gradle {
g.env = java_env(g.java_version);
g.env = java_env(jdk.as_ref(), g.java_version);
}
model
}
@@ -39,8 +50,8 @@ pub(crate) fn load(root: &Path, cache: &Path) -> BuildModel {
#[specta::specta]
pub async fn build_model(window: Window, state: State<'_, AppState>) -> IdeResult<BuildModel> {
let project = state.project(window.label())?;
let (root, cache) = (project.root.clone(), project.build_cache_dir());
tauri::async_runtime::spawn_blocking(move || load(&root, &cache)).await.map_err(join_err)
let (root, cache, settings) = (project.root.clone(), project.build_cache_dir(), project.settings.effective());
tauri::async_runtime::spawn_blocking(move || load(&root, &cache, &settings)).await.map_err(join_err)
}
/// Runs Maven (`help:effective-pom dependency:tree`) or Gradle (`tasks --all`) in the
@@ -58,10 +69,10 @@ pub async fn build_sync(
on_progress: Channel<SyncProgress>,
) -> IdeResult<BuildModel> {
let project = state.project(window.label())?;
let (root, cache) = (project.root.clone(), project.build_cache_dir());
let (root, cache, settings) = (project.root.clone(), project.build_cache_dir(), project.settings.effective());
let token = state.begin_request(request);
let result = tauri::async_runtime::spawn_blocking(move || {
let current = load(&root, &cache);
let current = load(&root, &cache, &settings);
let env = match tool {
BuildTool::Maven => current
.maven
@@ -71,7 +82,13 @@ pub async fn build_sync(
.unwrap_or_default(),
BuildTool::Gradle => current.gradle.as_ref().map(|g| g.env.clone()).unwrap_or_default(),
};
let options = SyncOptions { offline, profiles, env };
let options = SyncOptions {
offline,
profiles,
env,
maven_command: ide_sdk::apply::maven_command(&root, &settings).map(|p| p.to_string_lossy().into_owned()),
maven_options: ide_sdk::apply::maven_options(&root, &settings),
};
let progress = |p: SyncProgress| {
let _ = on_progress.send(p);
};
@@ -79,7 +96,7 @@ pub async fn build_sync(
BuildTool::Maven => ide_build::sync_maven(&root, &cache, &options, &token, &progress)?,
BuildTool::Gradle => ide_build::sync_gradle(&root, &cache, &options, &token, &progress)?,
}
Ok(load(&root, &cache))
Ok(load(&root, &cache, &settings))
})
.await
.map_err(join_err);
@@ -104,6 +121,7 @@ pub async fn build_run(
) -> IdeResult<BuildResult> {
let project = state.project(window.label())?;
let (root, cache, sink) = (project.root.clone(), project.build_cache_dir(), project.sink.clone());
let settings = project.settings.effective();
let token = state.begin_request(request);
let result = tauri::async_runtime::spawn_blocking(move || {
for path in clear {
@@ -113,7 +131,7 @@ pub async fn build_run(
items: Vec::new(),
});
}
let plan = compile::plan(&root, &load(&root, &cache), kind, file.as_deref())?;
let plan = compile::plan(&root, &load(&root, &cache, &settings), kind, file.as_deref())?;
let result = compile::run(&root, &plan, &token, &|e| {
let _ = on_event.send(e);
})?;
+10 -1
Переглянути файл
@@ -14,7 +14,16 @@ pub async fn debug_start(
) -> IdeResult<DebugSessionId> {
let label = window.label();
let owner = SessionOwner::new(AppState::owner_window(label), state.window_sink(label));
state.debugger.start(config, owner).await
let settings = match state.project(label) {
Ok(project) => project.settings.effective(),
Err(_) => state.global_settings.effective(),
};
let root = config.cwd.clone().map(PathBuf::from).unwrap_or_default();
let custom = |command: &str| {
let path = ide_sdk::apply::setting_path(&root, settings.tool_path(command)?)?;
Some(path.to_string_lossy().into_owned())
};
state.debugger.start_with(config, owner, custom).await
}
#[tauri::command]
+17 -1
Переглянути файл
@@ -1,6 +1,6 @@
use crate::state::AppState;
use ide_core::{ChangeSet, DocId, IdeError, IdeResult, OutlineItem, Range};
use ide_language::FoldRange;
use ide_language::{FoldRange, SyntaxHighlights};
use ide_text::LineEnding;
use ide_workspace::{DocumentInfo, HistoryEntry};
use std::path::PathBuf;
@@ -136,6 +136,22 @@ pub async fn doc_folding(window: Window, state: State<'_, AppState>, doc: DocId)
.await
}
/// Tree-sitter highlighting for languages the UI has no CodeMirror mode for;
/// empty when the grammar has no highlights query or the document is large.
#[tauri::command]
#[specta::specta]
pub async fn doc_highlights(window: Window, state: State<'_, AppState>, doc: DocId) -> IdeResult<SyntaxHighlights> {
let project = state.project(window.label())?;
blocking(move || {
let snap = project.documents.text_snapshot(doc)?;
if snap.large {
return Ok(SyntaxHighlights::default());
}
Ok(project.syntax.highlights(doc, &snap.language, snap.version, &snap.text))
})
.await
}
/// Extend Selection (⌥↑): syntax ranges around `offset`, innermost first.
/// Large documents fall back to word / line / document ranges.
#[tauri::command]
+17 -3
Переглянути файл
@@ -22,10 +22,12 @@ pub async fn java_resolve_launch(
) -> IdeResult<JavaLaunchInfo> {
let project = state.project(window.label())?;
let module = project.root.join(module);
let settings = project.settings.effective();
let built = if build && compile::has_non_java_sources(&module) {
let (root, cache, module) = (project.root.clone(), project.build_cache_dir(), module.clone());
let (root, cache, module, settings) =
(project.root.clone(), project.build_cache_dir(), module.clone(), settings.clone());
tauri::async_runtime::spawn_blocking(move || {
compile::build_for_launch(&root, &load(&root, &cache), &module, test, &CancellationToken::new())
compile::build_for_launch(&root, &load(&root, &cache, &settings), &module, test, &CancellationToken::new())
})
.await
.map_err(|e| IdeError::internal(e.to_string()))??
@@ -40,13 +42,25 @@ pub async fn java_resolve_launch(
}
}
info.class_paths = class_paths;
// The project JDK, else the JDK jdtls compiles the module against, else one matching its Java version.
let project_jdk = ide_sdk::apply::project_jdk(&project.root, &settings);
let from_jdtls = info.java_home.as_deref().map(ide_sdk::java::java_executable).filter(|p| p.is_file());
let java = from_jdtls.or_else(|| {
let java = project_jdk.map(|j| ide_sdk::java::java_executable(&j.home)).or(from_jdtls).or_else(|| {
let release = ide_sdk::java::project_java_version(&module);
let jdks = ide_sdk::java::installed_jdks();
ide_sdk::java::pick_jdk(&jdks, release).map(|j| ide_sdk::java::java_executable(&j.home))
});
info.java_exec = Some(java.map(|p| p.to_string_lossy().into_owned()).unwrap_or_else(|| "java".to_owned()));
if info.error_count > 0 {
let vm_args = &settings.languages.java.jdtls_vm_args;
let lombok = ide_sdk::lombok::lombok_agent(
&project.root,
ide_sdk::lombok::agent_in_args(vm_args.split_whitespace()),
ide_tools::managed_bundle(&state.data_dir, "lombok"),
ide_sdk::apply::maven_local_repository(&project.root, &settings),
);
info.hints.extend(lombok.problem());
}
Ok(info)
}
+3
Переглянути файл
@@ -74,6 +74,7 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
doc::doc_set_line_ending,
doc::doc_outline,
doc::doc_folding,
doc::doc_highlights,
doc::doc_selection_ranges,
syntax::syntax_support,
syntax::syntax_node_at,
@@ -129,6 +130,7 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
lsp::apply_workspace_edit,
lsp::lsp_execute_command,
vcs::vcs_status,
vcs::vcs_roots,
vcs::vcs_branch_info,
vcs::vcs_line_hunks,
vcs::vcs_file_at,
@@ -227,6 +229,7 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
window::window_toggle_fullscreen,
window::window_take_launch,
window::window_close_context,
window::window_open_projects,
window::app_quit,
window::app_cancel_quit,
window::menu_configure,
+3 -2
Переглянути файл
@@ -29,9 +29,10 @@ pub async fn search_start(
on_event: Channel<SearchEvent>,
) -> IdeResult<()> {
let project = state.project(window.label())?;
// Excluded roots (Project Structure marks and detected `target`, `node_modules`, …) are never searched.
// Excluded roots (Project Structure marks and detected `target`, `node_modules`, …) and
// ignored names are never searched.
query.exclude.extend(project.search_excludes());
let roots = project.roots();
query.exclude.extend(roots.excluded_globs().iter().map(|d| format!("{}/**", d.trim_start_matches('/'))));
let set = match query.scope {
ide_search::SearchScope::FileSet { set } => Some(set),
_ => None,
+24 -8
Переглянути файл
@@ -4,11 +4,21 @@ use crate::state::AppState;
use ide_core::{IdeError, IdeResult, RequestId};
use ide_tools::{InstallEvent, ToolInfo, Tools};
use tauri::ipc::Channel;
use tauri::{AppHandle, Manager, State};
use tauri::{AppHandle, Manager, State, Window};
fn tools(app: &AppHandle) -> IdeResult<Tools> {
/// The installer, reporting the executables chosen in the window's settings.
fn tools(app: &AppHandle, state: &AppState, window: &Window) -> IdeResult<Tools> {
let data = app.path().app_data_dir().map_err(|e| IdeError::internal(e.to_string()))?;
Ok(Tools::new(&data))
let (settings, root) = match state.project(window.label()) {
Ok(project) => (project.settings.effective(), project.root.clone()),
Err(_) => (state.global_settings.effective(), Default::default()),
};
let custom = settings
.tools
.iter()
.filter_map(|(command, t)| Some((command.clone(), ide_sdk::apply::setting_path(&root, &t.path)?)))
.collect();
Ok(Tools::new(&data).with_custom_paths(custom))
}
fn join_err(e: impl std::fmt::Display) -> IdeError {
@@ -18,8 +28,8 @@ fn join_err(e: impl std::fmt::Display) -> IdeError {
/// Status of every known language server / debug adapter and the languages using it.
#[tauri::command]
#[specta::specta]
pub async fn tools_list(app: AppHandle, state: State<'_, AppState>) -> IdeResult<Vec<ToolInfo>> {
let tools = tools(&app)?;
pub async fn tools_list(app: AppHandle, window: Window, state: State<'_, AppState>) -> IdeResult<Vec<ToolInfo>> {
let tools = tools(&app, &state, &window)?;
let langs = state.languages.all();
tauri::async_runtime::spawn_blocking(move || tools.list(&langs)).await.map_err(join_err)
}
@@ -30,12 +40,13 @@ pub async fn tools_list(app: AppHandle, state: State<'_, AppState>) -> IdeResult
#[specta::specta]
pub async fn tools_install(
app: AppHandle,
window: Window,
state: State<'_, AppState>,
name: String,
request: RequestId,
on_event: Channel<InstallEvent>,
) -> IdeResult<ToolInfo> {
let tools = tools(&app)?;
let tools = tools(&app, &state, &window)?;
let langs = state.languages.all();
let cancel = state.begin_request(request);
let result = tauri::async_runtime::spawn_blocking(move || {
@@ -56,8 +67,13 @@ pub async fn tools_install(
/// Removes a tool the IDE installed.
#[tauri::command]
#[specta::specta]
pub async fn tools_uninstall(app: AppHandle, state: State<'_, AppState>, name: String) -> IdeResult<ToolInfo> {
let tools = tools(&app)?;
pub async fn tools_uninstall(
app: AppHandle,
window: Window,
state: State<'_, AppState>,
name: String,
) -> IdeResult<ToolInfo> {
let tools = tools(&app, &state, &window)?;
let langs = state.languages.all();
let info =
tauri::async_runtime::spawn_blocking(move || tools.uninstall(&name, &langs)).await.map_err(join_err)??;
+188 -50
Переглянути файл
@@ -1,4 +1,4 @@
use crate::state::AppState;
use crate::state::{AppState, Project};
use ide_core::{IdeResult, RequestId};
use ide_vcs::*;
use serde::{Deserialize, Serialize};
@@ -13,18 +13,59 @@ pub(crate) fn apply_git_executable(settings: &ide_core::settings::Settings) {
ide_vcs::set_git_executable((!exe.is_empty()).then(|| Path::new(exe)));
}
/// Changes of every repository of the project.
#[tauri::command]
#[specta::specta]
pub async fn vcs_status(window: Window, state: State<'_, AppState>) -> IdeResult<Vec<FileStatus>> {
let project = state.project(window.label())?;
blocking(move || project.with_repo(|r| r.status())).await
blocking(move || {
let settings = project.settings.effective();
apply_git_executable(&settings);
let repos = project.repos();
if repos.is_empty() {
return Err(ide_core::IdeError::unavailable("project is not a git repository"));
}
for r in repos.all() {
r.set_ignored_names(settings.ignored_names());
}
repos.status()
})
.await
}
/// A repository of the project (IDEA's VCS root).
#[derive(Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct VcsRoot {
/// Worktree root.
pub root: ide_core::IpcPath,
/// Merge / rebase / cherry-pick / revert in progress.
pub operation: Option<String>,
}
/// The project's repositories, the primary one first.
#[tauri::command]
#[specta::specta]
pub fn vcs_roots(window: Window, state: State<'_, AppState>) -> IdeResult<Vec<VcsRoot>> {
let repos = state.project(window.label())?.repos();
let primary = repos.primary().map(|r| r.root().to_path_buf());
let mut all: Vec<&std::sync::Arc<Repo>> = repos.all().iter().collect();
all.sort_by_key(|r| Some(r.root()) != primary.as_deref());
Ok(all
.into_iter()
.map(|r| VcsRoot { root: r.root().to_path_buf().into(), operation: r.operation().ok().flatten() })
.collect())
}
#[tauri::command]
#[specta::specta]
pub async fn vcs_branch_info(window: Window, state: State<'_, AppState>) -> IdeResult<BranchInfo> {
pub async fn vcs_branch_info(
window: Window,
state: State<'_, AppState>,
repo: Option<PathBuf>,
) -> IdeResult<BranchInfo> {
let project = state.project(window.label())?;
blocking(move || project.with_repo(|r| r.branch_info())).await
blocking(move || project.with_repo_at(repo.as_deref(), |r| r.branch_info())).await
}
/// Gutter change markers for a file, computed against its current (unsaved) text.
@@ -33,7 +74,7 @@ pub async fn vcs_branch_info(window: Window, state: State<'_, AppState>) -> IdeR
pub fn vcs_line_hunks(window: Window, state: State<'_, AppState>, path: PathBuf) -> IdeResult<Vec<LineHunk>> {
let project = state.project(window.label())?;
let text = project.text_of(&path)?;
project.with_repo(|r| r.line_hunks(&path, &text, false))
project.with_repo_of(&path, |r| r.line_hunks(&path, &text, false))
}
#[tauri::command]
@@ -45,7 +86,7 @@ pub async fn vcs_file_at(
rev: Option<String>,
) -> IdeResult<Option<String>> {
let project = state.project(window.label())?;
blocking(move || project.with_repo(|r| r.file_at(&path, rev.as_deref()))).await
blocking(move || project.with_repo_of(&path, |r| r.file_at(&path, rev.as_deref()))).await
}
#[tauri::command]
@@ -53,14 +94,19 @@ pub async fn vcs_file_at(
pub async fn vcs_blame(window: Window, state: State<'_, AppState>, path: PathBuf) -> IdeResult<Vec<BlameLine>> {
let project = state.project(window.label())?;
let text = project.documents.text_of(&path);
blocking(move || project.with_repo(|r| r.blame(&path, text.as_deref()))).await
blocking(move || project.with_repo_of(&path, |r| r.blame(&path, text.as_deref()))).await
}
#[tauri::command]
#[specta::specta]
pub async fn vcs_log(window: Window, state: State<'_, AppState>, query: LogQuery) -> IdeResult<Vec<Commit>> {
pub async fn vcs_log(
window: Window,
state: State<'_, AppState>,
repo: Option<PathBuf>,
query: LogQuery,
) -> IdeResult<Vec<Commit>> {
let project = state.project(window.label())?;
blocking(move || project.with_repo(|r| r.log(&query))).await
blocking(move || project.with_repo_at(repo.as_deref(), |r| r.log(&query))).await
}
#[tauri::command]
@@ -68,38 +114,39 @@ pub async fn vcs_log(window: Window, state: State<'_, AppState>, query: LogQuery
pub async fn vcs_commit_files(
window: Window,
state: State<'_, AppState>,
repo: Option<PathBuf>,
commit: String,
) -> IdeResult<Vec<ChangedFile>> {
let project = state.project(window.label())?;
blocking(move || project.with_repo(|r| r.commit_files(&commit))).await
blocking(move || project.with_repo_at(repo.as_deref(), |r| r.commit_files(&commit))).await
}
#[tauri::command]
#[specta::specta]
pub async fn vcs_branches(window: Window, state: State<'_, AppState>) -> IdeResult<Vec<Branch>> {
pub async fn vcs_branches(window: Window, state: State<'_, AppState>, repo: Option<PathBuf>) -> IdeResult<Vec<Branch>> {
let project = state.project(window.label())?;
blocking(move || project.with_repo(|r| r.branches())).await
blocking(move || project.with_repo_at(repo.as_deref(), |r| r.branches())).await
}
#[tauri::command]
#[specta::specta]
pub async fn vcs_stashes(window: Window, state: State<'_, AppState>) -> IdeResult<Vec<Stash>> {
pub async fn vcs_stashes(window: Window, state: State<'_, AppState>, repo: Option<PathBuf>) -> IdeResult<Vec<Stash>> {
let project = state.project(window.label())?;
blocking(move || project.with_repo(|r| r.stashes())).await
blocking(move || project.with_repo_at(repo.as_deref(), |r| r.stashes())).await
}
#[tauri::command]
#[specta::specta]
pub async fn vcs_stage(window: Window, state: State<'_, AppState>, paths: Vec<PathBuf>) -> IdeResult<()> {
let project = state.project(window.label())?;
blocking(move || project.with_repo(|r| r.stage(&paths))).await
blocking(move || per_repo(&project, &paths, None, |r, paths| r.stage(paths))).await
}
#[tauri::command]
#[specta::specta]
pub async fn vcs_unstage(window: Window, state: State<'_, AppState>, paths: Vec<PathBuf>) -> IdeResult<()> {
let project = state.project(window.label())?;
blocking(move || project.with_repo(|r| r.unstage(&paths))).await
blocking(move || per_repo(&project, &paths, None, |r, paths| r.unstage(paths))).await
}
#[tauri::command]
@@ -113,7 +160,7 @@ pub async fn vcs_stage_patch(window: Window, state: State<'_, AppState>, patch:
#[specta::specta]
pub async fn vcs_discard(window: Window, state: State<'_, AppState>, paths: Vec<PathBuf>) -> IdeResult<()> {
let project = state.project(window.label())?;
blocking(move || project.with_repo_recorded(Some("Rollback"), |r| r.discard(&paths))).await
blocking(move || per_repo(&project, &paths, Some("Rollback"), |r, paths| r.discard(paths))).await
}
#[tauri::command]
@@ -121,20 +168,27 @@ pub async fn vcs_discard(window: Window, state: State<'_, AppState>, paths: Vec<
pub async fn vcs_commit(
window: Window,
state: State<'_, AppState>,
repo: Option<PathBuf>,
message: String,
amend: bool,
sign_off: bool,
options: CommitOptions,
) -> IdeResult<String> {
// Commit hooks may run for a long time.
let project = state.project(window.label())?;
blocking(move || project.with_repo(|r| r.commit(&message, amend, sign_off))).await
blocking(move || project.with_repo_at(repo.as_deref(), |r| r.commit_with(&message, &options))).await
}
#[tauri::command]
#[specta::specta]
pub async fn vcs_checkout(window: Window, state: State<'_, AppState>, branch: String, create: bool) -> IdeResult<()> {
pub async fn vcs_checkout(
window: Window,
state: State<'_, AppState>,
repo: Option<PathBuf>,
branch: String,
create: bool,
) -> IdeResult<()> {
let project = state.project(window.label())?;
blocking(move || project.with_repo_recorded(Some("Git checkout"), |r| r.checkout(&branch, create))).await
blocking(move || project.with_repo_recorded(repo.as_deref(), Some("Git checkout"), |r| r.checkout(&branch, create)))
.await
}
/// New Branch: creates `name` at `start` (HEAD when absent), optionally checking it out.
@@ -143,22 +197,31 @@ pub async fn vcs_checkout(window: Window, state: State<'_, AppState>, branch: St
pub async fn vcs_create_branch(
window: Window,
state: State<'_, AppState>,
repo: Option<PathBuf>,
name: String,
start: Option<String>,
checkout: bool,
) -> IdeResult<()> {
let project = state.project(window.label())?;
let recorded = checkout.then_some("Git checkout");
blocking(move || project.with_repo_recorded(recorded, |r| r.create_branch(&name, start.as_deref(), checkout))).await
blocking(move || {
project.with_repo_recorded(repo.as_deref(), recorded, |r| r.create_branch(&name, start.as_deref(), checkout))
})
.await
}
/// Undo Commit: moves HEAD back to the commit's parent, keeping its changes staged.
/// Returns the undone commit's message.
#[tauri::command]
#[specta::specta]
pub async fn vcs_undo_commit(window: Window, state: State<'_, AppState>, commit: String) -> IdeResult<String> {
pub async fn vcs_undo_commit(
window: Window,
state: State<'_, AppState>,
repo: Option<PathBuf>,
commit: String,
) -> IdeResult<String> {
let project = state.project(window.label())?;
blocking(move || project.with_repo(|r| r.undo_commit(&commit))).await
blocking(move || project.with_repo_at(repo.as_deref(), |r| r.undo_commit(&commit))).await
}
#[tauri::command]
@@ -166,32 +229,49 @@ pub async fn vcs_undo_commit(window: Window, state: State<'_, AppState>, commit:
pub async fn vcs_delete_branch(
window: Window,
state: State<'_, AppState>,
repo: Option<PathBuf>,
branch: String,
force: bool,
) -> IdeResult<()> {
let project = state.project(window.label())?;
blocking(move || project.with_repo(|r| r.delete_branch(&branch, force))).await
blocking(move || project.with_repo_at(repo.as_deref(), |r| r.delete_branch(&branch, force))).await
}
#[tauri::command]
#[specta::specta]
pub async fn vcs_rename_branch(window: Window, state: State<'_, AppState>, from: String, to: String) -> IdeResult<()> {
pub async fn vcs_rename_branch(
window: Window,
state: State<'_, AppState>,
repo: Option<PathBuf>,
from: String,
to: String,
) -> IdeResult<()> {
let project = state.project(window.label())?;
blocking(move || project.with_repo(|r| r.rename_branch(&from, &to))).await
blocking(move || project.with_repo_at(repo.as_deref(), |r| r.rename_branch(&from, &to))).await
}
#[tauri::command]
#[specta::specta]
pub async fn vcs_merge(window: Window, state: State<'_, AppState>, branch: String) -> IdeResult<()> {
pub async fn vcs_merge(
window: Window,
state: State<'_, AppState>,
repo: Option<PathBuf>,
branch: String,
) -> IdeResult<()> {
let project = state.project(window.label())?;
blocking(move || project.with_repo_recorded(Some("Git merge"), |r| r.merge(&branch))).await
blocking(move || project.with_repo_recorded(repo.as_deref(), Some("Git merge"), |r| r.merge(&branch))).await
}
#[tauri::command]
#[specta::specta]
pub async fn vcs_rebase(window: Window, state: State<'_, AppState>, onto: String) -> IdeResult<()> {
pub async fn vcs_rebase(
window: Window,
state: State<'_, AppState>,
repo: Option<PathBuf>,
onto: String,
) -> IdeResult<()> {
let project = state.project(window.label())?;
blocking(move || project.with_repo_recorded(Some("Git rebase"), |r| r.rebase(&onto))).await
blocking(move || project.with_repo_recorded(repo.as_deref(), Some("Git rebase"), |r| r.rebase(&onto))).await
}
#[tauri::command]
@@ -199,28 +279,43 @@ pub async fn vcs_rebase(window: Window, state: State<'_, AppState>, onto: String
pub async fn vcs_stash_push(
window: Window,
state: State<'_, AppState>,
repo: Option<PathBuf>,
message: Option<String>,
include_untracked: bool,
) -> IdeResult<()> {
let project = state.project(window.label())?;
blocking(move || {
project.with_repo_recorded(Some("Git stash"), |r| r.stash_push(message.as_deref(), include_untracked))
project.with_repo_recorded(repo.as_deref(), Some("Git stash"), |r| {
r.stash_push(message.as_deref(), include_untracked)
})
})
.await
}
#[tauri::command]
#[specta::specta]
pub async fn vcs_stash_apply(window: Window, state: State<'_, AppState>, index: u32, pop: bool) -> IdeResult<()> {
pub async fn vcs_stash_apply(
window: Window,
state: State<'_, AppState>,
repo: Option<PathBuf>,
index: u32,
pop: bool,
) -> IdeResult<()> {
let project = state.project(window.label())?;
blocking(move || project.with_repo_recorded(Some("Git unstash"), |r| r.stash_apply(index, pop))).await
blocking(move || project.with_repo_recorded(repo.as_deref(), Some("Git unstash"), |r| r.stash_apply(index, pop)))
.await
}
#[tauri::command]
#[specta::specta]
pub async fn vcs_stash_drop(window: Window, state: State<'_, AppState>, index: u32) -> IdeResult<()> {
pub async fn vcs_stash_drop(
window: Window,
state: State<'_, AppState>,
repo: Option<PathBuf>,
index: u32,
) -> IdeResult<()> {
let project = state.project(window.label())?;
blocking(move || project.with_repo(|r| r.stash_drop(index))).await
blocking(move || project.with_repo_at(repo.as_deref(), |r| r.stash_drop(index))).await
}
#[derive(Clone, Serialize, Deserialize, Type)]
@@ -259,6 +354,7 @@ pub enum RemoteOp {
pub async fn vcs_remote(
window: Window,
state: State<'_, AppState>,
repo: Option<PathBuf>,
request: RequestId,
op: RemoteOp,
on_output: Channel<String>,
@@ -270,7 +366,7 @@ pub async fn vcs_remote(
let _ = on_output.send(line);
};
let recorded = matches!(op, RemoteOp::Pull { .. }).then_some("Git pull");
project.with_repo_recorded(recorded, |r| match op {
project.with_repo_recorded(repo.as_deref(), recorded, |r| match op {
RemoteOp::Fetch => r.fetch(&cancel, &out),
RemoteOp::Pull { rebase } => r.pull(rebase, &cancel, &out),
RemoteOp::Push { force_with_lease, set_upstream, tags } => {
@@ -305,7 +401,7 @@ pub async fn vcs_conflict_versions(
) -> IdeResult<ConflictVersions> {
let project = state.project(window.label())?;
blocking(move || {
project.with_repo(|r| {
project.with_repo_of(&path, |r| {
r.conflict_versions(&path).map(|(base, ours, theirs)| ConflictVersions { base, ours, theirs })
})
})
@@ -321,7 +417,7 @@ pub async fn vcs_diff_text(
staged: bool,
) -> IdeResult<String> {
let project = state.project(window.label())?;
blocking(move || project.with_repo(|r| r.diff_text(&path, staged))).await
blocking(move || project.with_repo_of(&path, |r| r.diff_text(&path, staged))).await
}
/// Line hunks between two arbitrary texts (diff viewer, commit dialog).
@@ -338,7 +434,7 @@ pub fn vcs_diff_hunks(old_text: String, new_text: String) -> Vec<LineHunk> {
pub fn vcs_stage_hunks(window: Window, state: State<'_, AppState>, path: PathBuf, hunks: Vec<u32>) -> IdeResult<()> {
let project = state.project(window.label())?;
let current = ide_vfs::load_text(&path)?.text;
project.with_repo(|r| {
project.with_repo_of(&path, |r| {
let index_text = r.file_at(&path, Some(":0"))?.unwrap_or_default();
let rel = path.strip_prefix(r.root()).unwrap_or(&path).to_string_lossy().replace('\\', "/");
let selected: Vec<usize> = hunks.iter().map(|&h| h as usize).collect();
@@ -409,9 +505,14 @@ pub fn vcs_detected_git() -> Option<String> {
/// `git config --get <key>` in the project repository; `None` when unset.
#[tauri::command]
#[specta::specta]
pub async fn vcs_config_get(window: Window, state: State<'_, AppState>, key: String) -> IdeResult<Option<String>> {
pub async fn vcs_config_get(
window: Window,
state: State<'_, AppState>,
repo: Option<PathBuf>,
key: String,
) -> IdeResult<Option<String>> {
let project = state.project(window.label())?;
blocking(move || project.with_repo(|r| r.config_get(&key))).await
blocking(move || project.with_repo_at(repo.as_deref(), |r| r.config_get(&key))).await
}
// ---- in-progress operations, history rewriting (Git Log actions) ----
@@ -449,6 +550,7 @@ pub enum GitOperation {
pub async fn vcs_operation(
window: Window,
state: State<'_, AppState>,
repo: Option<PathBuf>,
request: RequestId,
op: GitOperation,
on_output: Channel<String>,
@@ -466,7 +568,7 @@ pub async fn vcs_operation(
GitOperation::InteractiveRebase { .. } => Some("Git rebase"),
_ => None,
};
project.with_repo_recorded(recorded, |r| match op {
project.with_repo_recorded(repo.as_deref(), recorded, |r| match op {
GitOperation::Continue => r.continue_operation(&cancel, &out),
GitOperation::Abort => r.abort_operation(&cancel, &out),
GitOperation::Skip => r.skip_operation(&cancel, &out),
@@ -489,20 +591,22 @@ pub async fn vcs_operation(
pub async fn vcs_create_tag(
window: Window,
state: State<'_, AppState>,
repo: Option<PathBuf>,
name: String,
commit: String,
message: Option<String>,
force: bool,
) -> IdeResult<()> {
let project = state.project(window.label())?;
blocking(move || project.with_repo(|r| r.create_tag(&name, &commit, message.as_deref(), force))).await
blocking(move || project.with_repo_at(repo.as_deref(), |r| r.create_tag(&name, &commit, message.as_deref(), force)))
.await
}
#[tauri::command]
#[specta::specta]
pub async fn vcs_tags(window: Window, state: State<'_, AppState>) -> IdeResult<Vec<String>> {
pub async fn vcs_tags(window: Window, state: State<'_, AppState>, repo: Option<PathBuf>) -> IdeResult<Vec<String>> {
let project = state.project(window.label())?;
blocking(move || project.with_repo(|r| r.tags())).await
blocking(move || project.with_repo_at(repo.as_deref(), |r| r.tags())).await
}
/// Compare with Local: tracked files that differ between `rev` and the working tree.
@@ -511,10 +615,42 @@ pub async fn vcs_tags(window: Window, state: State<'_, AppState>) -> IdeResult<V
pub async fn vcs_diff_with_worktree(
window: Window,
state: State<'_, AppState>,
repo: Option<PathBuf>,
rev: String,
) -> IdeResult<Vec<ChangedFile>> {
let project = state.project(window.label())?;
blocking(move || project.with_repo(|r| r.diff_with_worktree(&rev))).await
blocking(move || project.with_repo_at(repo.as_deref(), |r| r.diff_with_worktree(&rev))).await
}
/// Runs `f` once per repository with the `paths` that belong to it.
fn per_repo(
project: &Project,
paths: &[PathBuf],
recorded: Option<&str>,
f: impl Fn(&Repo, &[PathBuf]) -> IdeResult<()>,
) -> IdeResult<()> {
let groups = project.repos().group(paths);
if groups.is_empty() {
return project.with_repo_recorded(None, recorded, |r| f(r, paths));
}
for (repo, paths) in groups {
project.with_repo_recorded(Some(repo.root()), recorded, |r| f(r, &paths))?;
}
Ok(())
}
/// Shelf and patches work in the primary repository only: changes of a nested one
/// fail instead of being left out silently.
fn in_primary_repo(project: &Project, paths: &[PathBuf]) -> IdeResult<()> {
let repos = project.repos();
let primary = repos.primary().map(|r| r.root());
match paths.iter().find(|p| repos.for_path(p).map(|r| r.root()) != primary) {
Some(p) => Err(ide_core::IdeError::invalid(format!(
"{} is in another git repository; shelving and patches support the project's main repository only",
p.display()
))),
None => Ok(()),
}
}
async fn blocking<T: Send + 'static>(f: impl FnOnce() -> IdeResult<T> + Send + 'static) -> IdeResult<T> {
@@ -540,6 +676,7 @@ pub async fn vcs_create_patch(window: Window, state: State<'_, AppState>, source
project.with_repo(|r| match source {
PatchSource::Changes { paths, reverse } => {
let paths: Vec<PathBuf> = paths.into_iter().map(Into::into).collect();
in_primary_repo(&project, &paths)?;
r.create_patch(&paths, reverse)
}
PatchSource::Commits { commits, reverse } => r.create_commits_patch(&commits, reverse),
@@ -587,8 +724,9 @@ pub async fn vcs_shelve(
) -> IdeResult<ShelvedChangeList> {
let project = state.project(window.label())?;
blocking(move || {
in_primary_repo(&project, &paths)?;
keep_private(&project.root);
project.with_repo_recorded(Some("Shelve"), |r| r.shelve(&shelf_dir(&project.root), &name, &paths))
project.with_repo_recorded(None, Some("Shelve"), |r| r.shelve(&shelf_dir(&project.root), &name, &paths))
})
.await
}
@@ -612,7 +750,7 @@ pub async fn vcs_unshelve(
) -> IdeResult<ApplyOutcome> {
let project = state.project(window.label())?;
blocking(move || {
project.with_repo_recorded(Some("Unshelve"), |r| r.unshelve(&shelf_dir(&project.root), &id, remove))
project.with_repo_recorded(None, Some("Unshelve"), |r| r.unshelve(&shelf_dir(&project.root), &id, remove))
})
.await
}
+30
Переглянути файл
@@ -59,6 +59,36 @@ pub fn window_take_launch(window: WebviewWindow, windows: State<'_, WindowsState
windows.take_launch(window.label())
}
#[derive(Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct OpenProject {
pub name: String,
pub root: PathBuf,
/// Open in the calling window.
pub current: bool,
}
/// Projects open in project windows, in window order (title bar project widget).
#[tauri::command]
#[specta::specta]
pub fn window_open_projects(
app: AppHandle,
window: WebviewWindow,
state: State<'_, AppState>,
) -> IdeResult<Vec<OpenProject>> {
Ok(windows::project_window_labels(&app)
.into_iter()
.filter_map(|label| {
let project = state.project(&label).ok()?;
Some(OpenProject {
name: project.root.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(),
root: project.root.clone(),
current: label == window.label(),
})
})
.collect())
}
#[derive(Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct CloseContext {
+6 -2
Переглянути файл
@@ -50,9 +50,12 @@ pub fn run() {
#[cfg(debug_assertions)]
export_bindings(&builder);
let app = tauri::Builder::default();
// Single instance first: a second launch focuses this one and opens its path argument.
let app = tauri::Builder::default()
.plugin(tauri_plugin_single_instance::init(windows::on_second_instance))
// Release only, so a dev build can run beside an installed release (same identifier).
#[cfg(not(debug_assertions))]
let app = app.plugin(tauri_plugin_single_instance::init(windows::on_second_instance));
let app = app
.plugin(tauri_plugin_opener::init())
.plugin(tauri_plugin_dialog::init())
.plugin(
@@ -84,6 +87,7 @@ pub fn run() {
app.manage(windows);
app.manage(menu_state);
app.on_menu_event(on_menu_event);
windows::create_main_window(app.handle())?;
Ok(())
})
.on_window_event(|window, event| match event {
+129 -20
Переглянути файл
@@ -8,7 +8,7 @@ use ide_run::ProcessManager;
use ide_syntax::StructureService;
use ide_terminal::TerminalManager;
use ide_text::{AppliedChange, ByteEdit};
use ide_vcs::Repo;
use ide_vcs::{Repo, Repos};
use ide_vfs::Watcher;
use ide_workspace::documents::DocumentObserver;
use ide_workspace::{
@@ -56,7 +56,8 @@ pub struct Project {
pub moves: FileMoves,
pub index: Arc<ProjectIndex>,
pub lsp: Arc<LspManager>,
pub repo: Mutex<Option<Repo>>,
/// Git repositories: the one containing the project root and those nested below it.
pub repos: Arc<RwLock<Repos>>,
/// Incrementally maintained syntax trees of the open documents.
pub syntax: Arc<SyntaxCache>,
/// Tree-sitter structure queries (LSP fallback) over `syntax`.
@@ -242,12 +243,32 @@ impl AppState {
let root = root.clone();
let data_dir = self.data_dir.clone();
lsp.set_config_hook(Box::new(move |cfg, server_root| {
ide_sdk::apply::configure_server(cfg, &root, server_root, &settings.effective());
let effective = settings.effective();
ide_sdk::apply::configure_server(cfg, &root, server_root, &effective);
if cfg.name == "jdtls" {
let bundles: Vec<PathBuf> =
ide_tools::managed_bundle(&data_dir, "java-debug").into_iter().collect();
let jdks = ide_sdk::java::jdtls_jdks();
ide_sdk::java::configure_jdtls(cfg, server_root, &data_dir, &jdks, &bundles);
let min_java = ide_sdk::java::jdtls_min_java(cfg);
let jdks = ide_sdk::java::jdtls_jdks(min_java);
let lombok = ide_sdk::lombok::lombok_agent(
server_root,
ide_sdk::lombok::agent_in_args(cfg.args.iter().map(String::as_str)),
ide_tools::managed_bundle(&data_dir, "lombok"),
ide_sdk::apply::maven_local_repository(&root, &effective),
);
if let Some(problem) = lombok.problem() {
tracing::warn!("{problem}");
}
ide_sdk::java::configure_jdtls(
cfg,
server_root,
&data_dir,
&jdks,
ide_sdk::apply::project_jdk(&root, &effective).as_ref(),
min_java,
&bundles,
lombok.jar(),
);
}
}));
}
@@ -260,7 +281,10 @@ impl AppState {
documents.add_observer(Arc::new(LspObserver(lsp.clone())));
documents.add_observer(Arc::new(HistoryObserver(history.clone())));
let repos = Arc::new(RwLock::new(Repos::enclosing(&root)?));
let watcher = {
let repos = repos.clone();
let settings = settings.clone();
let index = index.clone();
let documents = documents.clone();
let sink = sink.clone();
@@ -286,6 +310,19 @@ impl AppState {
sink.emit(IdeEvent::ProjectRootsChanged { root: root.clone().into() });
}
}
// A repository was cloned / initialised / removed below the project: its
// `.git/HEAD` (the watcher reports nothing else of `.git`) appeared or went.
let known = repos.read().roots();
let git_dirs = changed.iter().chain(&batch.removed).any(|p| {
let Some(dir) = p.ends_with(".git/HEAD").then(|| p.parent().and_then(Path::parent)).flatten()
else {
return false;
};
known.iter().any(|r| r == dir) != p.is_file()
});
if git_dirs {
scan_repositories(&root, &repos, &settings, &sink);
}
sink.emit(IdeEvent::VcsChanged { root: root.clone().into() });
}),
)?
@@ -312,8 +349,13 @@ impl AppState {
};
mark("watcher");
let repo = Repo::discover(&root)?;
let branch = repo.as_ref().and_then(|r| r.branch_info().ok()).and_then(|b| b.head);
let branch = repos.read().primary().and_then(|r| r.branch_info().ok()).and_then(|b| b.head);
{
let (root, repos, settings, sink) = (root.clone(), repos.clone(), settings.clone(), sink.clone());
std::thread::Builder::new()
.name("openidea-vcs-roots".into())
.spawn(move || scan_repositories(&root, &repos, &settings, &sink))?;
}
mark("git");
self.recent.touch(&root, branch)?;
mark("recent");
@@ -330,7 +372,7 @@ impl AppState {
moves: FileMoves::new(),
index,
lsp,
repo: Mutex::new(repo),
repos,
structure: Arc::new(StructureService::new(syntax.clone())),
syntax,
detected_roots,
@@ -372,14 +414,65 @@ impl AppState {
}
}
impl Project {
/// Runs `f` with the git repository, or fails when the project is not under git.
pub fn with_repo<T>(&self, f: impl FnOnce(&Repo) -> IdeResult<T>) -> IdeResult<T> {
crate::commands::vcs::apply_git_executable(&self.settings.effective());
match self.repo.lock().as_ref() {
Some(repo) => f(repo),
None => Err(IdeError::unavailable("project is not a git repository")),
/// Looks for repositories nested below the project (and the one containing it);
/// emits `VcsChanged` when the set of roots changed.
fn scan_repositories(root: &Path, repos: &RwLock<Repos>, settings: &SettingsStore, sink: &SharedSink) {
let ignored = settings.effective().ignored_names();
let skip = |p: &Path| p.file_name().is_some_and(|n| ignored.is_ignored_name(&n.to_string_lossy()));
match Repos::discover(root, &skip) {
Ok(found) => {
if found.roots() != repos.read().roots() {
*repos.write() = found;
sink.emit(IdeEvent::VcsChanged { root: root.to_path_buf().into() });
}
}
Err(e) => tracing::warn!("looking for git repositories: {e}"),
}
}
impl Project {
/// The project's git repositories.
pub fn repos(&self) -> Repos {
self.repos.read().clone()
}
/// Runs `f` with the repository whose root is `at`, the project's primary repository
/// when `None`; fails when there is none (a repository-scoped command never falls back
/// to another repository).
pub fn with_repo_at<T>(&self, at: Option<&Path>, f: impl FnOnce(&Repo) -> IdeResult<T>) -> IdeResult<T> {
let repos = self.repos();
match at {
Some(root) => match repos.at_root(root) {
Some(repo) => self.run_in(repo, f),
None => {
Err(IdeError::unavailable(format!("{} is not a git repository of the project", root.display())))
}
},
None => match repos.primary() {
Some(repo) => self.run_in(repo, f),
None => Err(IdeError::unavailable("project is not a git repository")),
},
}
}
/// Runs `f` with the repository `path` (a file or folder) belongs to.
pub fn with_repo_of<T>(&self, path: &Path, f: impl FnOnce(&Repo) -> IdeResult<T>) -> IdeResult<T> {
match self.repos().for_path(path) {
Some(repo) => self.run_in(repo, f),
None => Err(IdeError::unavailable(format!("{} is not in a git repository", path.display()))),
}
}
fn run_in<T>(&self, repo: &Repo, f: impl FnOnce(&Repo) -> IdeResult<T>) -> IdeResult<T> {
let settings = self.settings.effective();
crate::commands::vcs::apply_git_executable(&settings);
repo.set_ignored_names(settings.ignored_names());
f(repo)
}
/// Runs `f` with the project's primary git repository, or fails when the project is not under git.
pub fn with_repo<T>(&self, f: impl FnOnce(&Repo) -> IdeResult<T>) -> IdeResult<T> {
self.with_repo_at(None, f)
}
/// Runs a VCS operation that rewrites the working tree (checkout, merge,
@@ -388,19 +481,20 @@ impl Project {
/// `None` runs `f` like [`with_repo`](Self::with_repo) (operations that keep the working tree).
pub fn with_repo_recorded<T>(
&self,
at: Option<&Path>,
operation: Option<&str>,
f: impl FnOnce(&Repo) -> IdeResult<T>,
) -> IdeResult<T> {
let Some(name) = operation else { return self.with_repo(f) };
let Some(name) = operation else { return self.with_repo_at(at, f) };
self.history_label(&format!("Before {name}"));
if let Ok(changed) = self.with_repo(|r| r.status()) {
if let Ok(changed) = self.with_repo_at(at, |r| r.status()) {
for file in changed.iter().take(HISTORY_BATCH_LIMIT) {
if let Err(e) = self.history.record_file(&file.path, &format!("Before {name}"), false) {
tracing::debug!("local history: {e}");
}
}
}
let result = self.with_repo(f);
let result = self.with_repo_at(at, f);
self.history_label(&format!("After {name}"));
result
}
@@ -435,7 +529,22 @@ impl Project {
self.cache_dir.join("build")
}
/// `files.exclude` plus the effective excluded roots (user-marked and detected).
/// File masks (`ide_search::FileMask`) for Find in Files and inspections: the
/// excluded roots and the ignored names (files, and everything under such folders).
pub fn search_excludes(&self) -> Vec<String> {
let mut out: Vec<String> =
self.roots().excluded_globs().iter().map(|d| format!("{}/**", d.trim_start_matches('/'))).collect();
for name in &self.settings.effective().files.ignored_names {
let name = name.trim();
if !name.is_empty() && !name.contains(['/', ',']) {
out.push(name.to_owned());
out.push(format!("**/{name}/**"));
}
}
out
}
/// `files.exclude`, the ignored names and the effective excluded roots (user-marked and detected).
pub fn exclude_globs(&self) -> Vec<String> {
exclude_globs(&self.settings.effective(), &self.detected_roots.read())
}
@@ -508,7 +617,7 @@ pub fn history_retention(settings: &ide_core::settings::Settings) -> ide_workspa
}
fn exclude_globs(settings: &ide_core::settings::Settings, detected: &[SourceFolder]) -> Vec<String> {
let mut globs = settings.files.exclude.clone();
let mut globs = settings.file_excludes();
globs.extend(ProjectRoots::compute(detected.to_vec(), &settings.project_structure).excluded_globs());
globs
}
+71 -20
Переглянути файл
@@ -11,6 +11,7 @@
//! [`Launch::settings_page`] tells it which page to show.
use crate::state::AppState;
use ide_core::settings::AppearanceSettings;
use ide_core::{IdeError, IdeResult};
use parking_lot::Mutex;
use serde::{Deserialize, Serialize};
@@ -18,7 +19,8 @@ use specta::Type;
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use tauri::{AppHandle, Emitter, Manager, WebviewWindow, WebviewWindowBuilder};
use tauri::utils::config::{Color, WindowConfig};
use tauri::{AppHandle, Emitter, Manager, Theme, WebviewWindow, WebviewWindowBuilder};
/// Tells a window that a pending launch is waiting for it.
pub const LAUNCH_EVENT: &str = "openidea://launch";
@@ -195,19 +197,66 @@ pub fn target_window(app: &AppHandle) -> Option<WebviewWindow> {
sorted_labels(windows.keys().map(String::as_str)).first().and_then(|l| windows.get(l)).cloned()
}
/// Creates a new project window; `project` is opened by its frontend on load.
pub fn create_window(app: &AppHandle, project: Option<PathBuf>) -> IdeResult<WebviewWindow> {
let windows = app.webview_windows();
let label = next_label(windows.keys().map(String::as_str));
let mut config = app
.config()
fn window_config(app: &AppHandle) -> IdeResult<WindowConfig> {
app.config()
.app
.windows
.iter()
.find(|w| w.label == MAIN)
.or_else(|| app.config().app.windows.first())
.cloned()
.ok_or_else(|| IdeError::internal("no window configuration"))?;
.ok_or_else(|| IdeError::internal("no window configuration"))
}
/// The theme's `--bg-frame` (tokens.css), mirroring `resolveThemeId` in theme.ts.
pub fn frame_color(appearance: &AppearanceSettings, os_dark: bool) -> Color {
const LIGHT: Color = Color(0xe9, 0xea, 0xee, 0xff);
const DARK: Color = Color(0x26, 0x28, 0x2c, 0xff);
const DARK_HC: Color = Color(0x1a, 0x1b, 0x1e, 0xff);
let sync = appearance.sync_with_os || appearance.theme == "system";
let theme = match (sync, os_dark) {
(false, _) => &appearance.theme,
(true, true) => &appearance.preferred_dark_theme,
(true, false) => &appearance.preferred_light_theme,
};
match theme.as_str() {
"dark-hc" => DARK_HC,
"dark" => DARK,
"light" => LIGHT,
_ if sync && os_dark => DARK,
_ => LIGHT,
}
}
/// Builds a project window painted in the saved theme's frame colour, so it
/// doesn't flash the light default before its page (and splash) loads.
fn build_project_window(app: &AppHandle, mut config: WindowConfig) -> IdeResult<WebviewWindow> {
let appearance = app.try_state::<AppState>().map(|s| s.global_settings.effective().appearance);
if let Some(a) = &appearance {
config.background_color = Some(frame_color(a, false));
}
let window = WebviewWindowBuilder::from_config(app, &config)
.and_then(|b| b.build())
.map_err(|e| IdeError::internal(format!("cannot create window: {e}")))?;
// "Sync with OS" needs the OS mode, known once the window exists.
if let Some(a) = appearance.filter(|a| a.sync_with_os || a.theme == "system")
&& window.theme().is_ok_and(|t| t == Theme::Dark)
{
let _ = window.set_background_color(Some(frame_color(&a, true)));
}
Ok(window)
}
/// The first window (`create: false` in tauri.conf.json so it can take the theme's colour).
pub fn create_main_window(app: &AppHandle) -> IdeResult<WebviewWindow> {
build_project_window(app, window_config(app)?)
}
/// Creates a new project window; `project` is opened by its frontend on load.
pub fn create_window(app: &AppHandle, project: Option<PathBuf>) -> IdeResult<WebviewWindow> {
let windows = app.webview_windows();
let label = next_label(windows.keys().map(String::as_str));
let mut config = window_config(app)?;
config.label = label.clone();
if let Some(name) = project.as_deref().and_then(Path::file_name) {
config.title = name.to_string_lossy().into_owned();
@@ -223,9 +272,7 @@ pub fn create_window(app: &AppHandle, project: Option<PathBuf>) -> IdeResult<Web
config.center = false;
}
app.state::<WindowsState>().set_launch(&label, Launch { project: project.map(Into::into), settings_page: None });
let window = WebviewWindowBuilder::from_config(app, &config)
.and_then(|b| b.build())
.map_err(|e| IdeError::internal(format!("cannot create window: {e}")))?;
let window = build_project_window(app, config)?;
focus(&window);
Ok(window)
}
@@ -300,6 +347,7 @@ pub fn open_path(app: &AppHandle, path: &Path) {
}
/// Second instance launched: focus this one and open its path argument.
#[cfg_attr(debug_assertions, allow(dead_code))]
pub fn on_second_instance(app: &AppHandle, args: Vec<String>, cwd: String) {
match cli_path(&args, Path::new(&cwd)) {
Some(path) => open_path(app, &path),
@@ -342,15 +390,7 @@ pub fn open_settings_window(
return Ok(());
}
let parent = app.get_webview_window(&parent_label).ok_or_else(|| IdeError::not_found("no parent window"))?;
let mut config = app
.config()
.app
.windows
.iter()
.find(|w| w.label == MAIN)
.or_else(|| app.config().app.windows.first())
.cloned()
.ok_or_else(|| IdeError::internal("no window configuration"))?;
let mut config = window_config(app)?;
config.label = label.clone();
config.title = "Settings".into();
// Frameless on Windows like project windows (tauri.windows.conf.json): the page draws
@@ -398,6 +438,17 @@ mod tests {
v.iter().map(|x| x.to_string()).collect()
}
#[test]
fn frame_color_follows_theme_and_os_mode() {
let mut a = AppearanceSettings::default();
assert_eq!(frame_color(&a, true), Color(0xe9, 0xea, 0xee, 0xff));
a.theme = "dark-hc".into();
assert_eq!(frame_color(&a, false), Color(0x1a, 0x1b, 0x1e, 0xff));
a.sync_with_os = true;
assert_eq!(frame_color(&a, false), Color(0xe9, 0xea, 0xee, 0xff));
assert_eq!(frame_color(&a, true), Color(0x26, 0x28, 0x2c, 0xff));
}
#[test]
fn labels_sort_main_first_then_numerically() {
assert_eq!(
+2 -1
Переглянути файл
@@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "OpenIDEA",
"version": "0.1.2",
"version": "0.1.7",
"identifier": "ai.l0ng.openidea",
"build": {
"beforeDevCommand": "pnpm dev",
@@ -13,6 +13,7 @@
"windows": [
{
"label": "main",
"create": false,
"title": "OpenIDEA",
"width": 1440,
"height": 900,
+1
Переглянути файл
@@ -3,6 +3,7 @@
"windows": [
{
"label": "main",
"create": false,
"title": "OpenIDEA",
"width": 1440,
"height": 900,
+140 -25
Переглянути файл
@@ -92,6 +92,11 @@ export const commands = {
*/
docOutline: (doc: DocId) => typedError<OutlineItem[], IdeError>(__TAURI_INVOKE("doc_outline", { doc })),
docFolding: (doc: DocId) => typedError<FoldRange[], IdeError>(__TAURI_INVOKE("doc_folding", { doc })),
/**
* Tree-sitter highlighting for languages the UI has no CodeMirror mode for;
* empty when the grammar has no highlights query or the document is large.
*/
docHighlights: (doc: DocId) => typedError<SyntaxHighlights, IdeError>(__TAURI_INVOKE("doc_highlights", { doc })),
/**
* Extend Selection (⌥↑): syntax ranges around `offset`, innermost first.
* Large documents fall back to word / line / document ranges.
@@ -249,38 +254,41 @@ export const commands = {
* follow-up command. Edits the server requests arrive via `workspace/applyEdit`.
*/
lspExecuteCommand: (doc: DocId, command: Command) => typedError<null, IdeError>(__TAURI_INVOKE("lsp_execute_command", { doc, command })),
/** Changes of every repository of the project. */
vcsStatus: () => typedError<FileStatus[], IdeError>(__TAURI_INVOKE("vcs_status")),
vcsBranchInfo: () => typedError<BranchInfo, IdeError>(__TAURI_INVOKE("vcs_branch_info")),
/** The project's repositories, the primary one first. */
vcsRoots: () => typedError<VcsRoot[], IdeError>(__TAURI_INVOKE("vcs_roots")),
vcsBranchInfo: (repo: string | null) => typedError<BranchInfo, IdeError>(__TAURI_INVOKE("vcs_branch_info", { repo })),
/** Gutter change markers for a file, computed against its current (unsaved) text. */
vcsLineHunks: (path: string) => typedError<LineHunk[], IdeError>(__TAURI_INVOKE("vcs_line_hunks", { path })),
vcsFileAt: (path: string, rev: string | null) => typedError<string | null, IdeError>(__TAURI_INVOKE("vcs_file_at", { path, rev })),
vcsBlame: (path: string) => typedError<BlameLine[], IdeError>(__TAURI_INVOKE("vcs_blame", { path })),
vcsLog: (query: LogQuery) => typedError<Commit[], IdeError>(__TAURI_INVOKE("vcs_log", { query })),
vcsCommitFiles: (commit: string) => typedError<ChangedFile[], IdeError>(__TAURI_INVOKE("vcs_commit_files", { commit })),
vcsBranches: () => typedError<Branch[], IdeError>(__TAURI_INVOKE("vcs_branches")),
vcsStashes: () => typedError<Stash[], IdeError>(__TAURI_INVOKE("vcs_stashes")),
vcsLog: (repo: string | null, query: LogQuery) => typedError<Commit[], IdeError>(__TAURI_INVOKE("vcs_log", { repo, query })),
vcsCommitFiles: (repo: string | null, commit: string) => typedError<ChangedFile[], IdeError>(__TAURI_INVOKE("vcs_commit_files", { repo, commit })),
vcsBranches: (repo: string | null) => typedError<Branch[], IdeError>(__TAURI_INVOKE("vcs_branches", { repo })),
vcsStashes: (repo: string | null) => typedError<Stash[], IdeError>(__TAURI_INVOKE("vcs_stashes", { repo })),
vcsStage: (paths: string[]) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_stage", { paths })),
vcsUnstage: (paths: string[]) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_unstage", { paths })),
vcsStagePatch: (patch: string) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_stage_patch", { patch })),
vcsDiscard: (paths: string[]) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_discard", { paths })),
vcsCommit: (message: string, amend: boolean, signOff: boolean) => typedError<string, IdeError>(__TAURI_INVOKE("vcs_commit", { message, amend, signOff })),
vcsCheckout: (branch: string, create: boolean) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_checkout", { branch, create })),
vcsDeleteBranch: (branch: string, force: boolean) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_delete_branch", { branch, force })),
vcsCommit: (repo: string | null, message: string, options: CommitOptions) => typedError<string, IdeError>(__TAURI_INVOKE("vcs_commit", { repo, message, options })),
vcsCheckout: (repo: string | null, branch: string, create: boolean) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_checkout", { repo, branch, create })),
vcsDeleteBranch: (repo: string | null, branch: string, force: boolean) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_delete_branch", { repo, branch, force })),
/** New Branch: creates `name` at `start` (HEAD when absent), optionally checking it out. */
vcsCreateBranch: (name: string, start: string | null, checkout: boolean) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_create_branch", { name, start, checkout })),
vcsCreateBranch: (repo: string | null, name: string, start: string | null, checkout: boolean) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_create_branch", { repo, name, start, checkout })),
/**
* Undo Commit: moves HEAD back to the commit's parent, keeping its changes staged.
* Returns the undone commit's message.
*/
vcsUndoCommit: (commit: string) => typedError<string, IdeError>(__TAURI_INVOKE("vcs_undo_commit", { commit })),
vcsRenameBranch: (from: string, to: string) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_rename_branch", { from, to })),
vcsMerge: (branch: string) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_merge", { branch })),
vcsRebase: (onto: string) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_rebase", { onto })),
vcsStashPush: (message: string | null, includeUntracked: boolean) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_stash_push", { message, includeUntracked })),
vcsStashApply: (index: number, pop: boolean) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_stash_apply", { index, pop })),
vcsStashDrop: (index: number) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_stash_drop", { index })),
vcsUndoCommit: (repo: string | null, commit: string) => typedError<string, IdeError>(__TAURI_INVOKE("vcs_undo_commit", { repo, commit })),
vcsRenameBranch: (repo: string | null, from: string, to: string) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_rename_branch", { repo, from, to })),
vcsMerge: (repo: string | null, branch: string) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_merge", { repo, branch })),
vcsRebase: (repo: string | null, onto: string) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_rebase", { repo, onto })),
vcsStashPush: (repo: string | null, message: string | null, includeUntracked: boolean) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_stash_push", { repo, message, includeUntracked })),
vcsStashApply: (repo: string | null, index: number, pop: boolean) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_stash_apply", { repo, index, pop })),
vcsStashDrop: (repo: string | null, index: number) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_stash_drop", { repo, index })),
/** Network operation; progress lines stream through `on_output`. Cancellable. */
vcsRemote: (request: RequestId, op: RemoteOp, onOutput: Channel<string>) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_remote", { request, op, onOutput })),
vcsRemote: (repo: string | null, request: RequestId, op: RemoteOp, onOutput: Channel<string>) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_remote", { repo, request, op, onOutput })),
vcsConflictVersions: (path: string) => typedError<ConflictVersions, IdeError>(__TAURI_INVOKE("vcs_conflict_versions", { path })),
vcsDiffText: (path: string, staged: boolean) => typedError<string, IdeError>(__TAURI_INVOKE("vcs_diff_text", { path, staged })),
/** Line hunks between two arbitrary texts (diff viewer, commit dialog). */
@@ -300,16 +308,16 @@ export const commands = {
/** The auto-detected git executable (shown as the field's placeholder). */
vcsDetectedGit: () => __TAURI_INVOKE<string | null>("vcs_detected_git"),
/** `git config --get <key>` in the project repository; `None` when unset. */
vcsConfigGet: (key: string) => typedError<string | null, IdeError>(__TAURI_INVOKE("vcs_config_get", { key })),
vcsConfigGet: (repo: string | null, key: string) => typedError<string | null, IdeError>(__TAURI_INVOKE("vcs_config_get", { repo, key })),
/**
* Local history operation that may take a while (hooks, large checkouts); git's
* output streams through `on_output`. Cancellable.
*/
vcsOperation: (request: RequestId, op: GitOperation, onOutput: Channel<string>) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_operation", { request, op, onOutput })),
vcsCreateTag: (name: string, commit: string, message: string | null, force: boolean) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_create_tag", { name, commit, message, force })),
vcsTags: () => typedError<string[], IdeError>(__TAURI_INVOKE("vcs_tags")),
vcsOperation: (repo: string | null, request: RequestId, op: GitOperation, onOutput: Channel<string>) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_operation", { repo, request, op, onOutput })),
vcsCreateTag: (repo: string | null, name: string, commit: string, message: string | null, force: boolean) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_create_tag", { repo, name, commit, message, force })),
vcsTags: (repo: string | null) => typedError<string[], IdeError>(__TAURI_INVOKE("vcs_tags", { repo })),
/** Compare with Local: tracked files that differ between `rev` and the working tree. */
vcsDiffWithWorktree: (rev: string) => typedError<ChangedFile[], IdeError>(__TAURI_INVOKE("vcs_diff_with_worktree", { rev })),
vcsDiffWithWorktree: (repo: string | null, rev: string) => typedError<ChangedFile[], IdeError>(__TAURI_INVOKE("vcs_diff_with_worktree", { repo, rev })),
vcsCreatePatch: (source: PatchSource) => typedError<string, IdeError>(__TAURI_INVOKE("vcs_create_patch", { source })),
vcsPatchPreview: (patch: string) => typedError<PatchFile[], IdeError>(__TAURI_INVOKE("vcs_patch_preview", { patch })),
vcsApplyPatch: (patch: string) => typedError<ApplyOutcome, IdeError>(__TAURI_INVOKE("vcs_apply_patch", { patch })),
@@ -434,6 +442,8 @@ export const commands = {
settingsPage: string | null,
} | null>("window_take_launch"),
windowCloseContext: () => __TAURI_INVOKE<CloseContext>("window_close_context"),
/** Projects open in project windows, in window order (title bar project widget). */
windowOpenProjects: () => typedError<OpenProject[], IdeError>(__TAURI_INVOKE("window_open_projects")),
/** Quits: closes every window, each of which runs its own unsaved-changes check. */
appQuit: () => __TAURI_INVOKE<void>("app_quit"),
/** A window vetoed the quit (user cancelled its unsaved-changes prompt). */
@@ -1027,6 +1037,16 @@ export type Commit = {
refs: string[],
};
/** Commit Options (IDEA's commit options popup). */
export type CommitOptions = {
amend: boolean,
signOff: boolean,
/** `--author`, e.g. `Name <[email protected]>`; `None` or blank uses the configured user. */
author: string | null,
/** False skips the pre-commit and commit-msg hooks (`--no-verify`). */
runHooks: boolean,
};
/** Version Control › Commit: commit checks and commit-message inspections. */
export type CommitSettings = {
analyzeCode?: boolean,
@@ -1854,6 +1874,8 @@ export type FileSettings = {
/** Save on focus loss / tab switch, like IDEA. */
autoSave?: boolean,
exclude?: string[],
/** Ignored Files and Folders: name patterns hidden everywhere; see [`crate::ignored`]. */
ignoredNames?: string[],
trimTrailingWhitespace?: boolean,
ensureFinalNewline?: boolean,
/** Local History keeps changes from this many working days (days with changes), like IDEA. */
@@ -2299,6 +2321,14 @@ export type JavaBuildStatus = "failed" | "succeeded" |
/** Compiled, but some project has compile errors. */
"withErrors" | "cancelled";
/** One error diagnostic; `line` / `column` are 1-based for display. */
export type JavaCompileError = {
path: IpcPath,
line: number,
column: number,
message: string,
};
/** Everything needed to launch a class of a module: build outcome, classpath and JDK. */
export type JavaLaunchInfo = {
/** `None` when no build was requested. */
@@ -2310,6 +2340,27 @@ export type JavaLaunchInfo = {
javaHome: IpcPath | null,
/** The `java` launcher to use (filled in by the caller from the installed JDKs). */
javaExec: string | null,
/** First compile errors of the workspace when the build had errors. */
errors: JavaCompileError[],
/** All compile errors (`errors` is capped). */
errorCount: number,
/** Likely causes of the errors worth telling the user (e.g. a missing Lombok agent). */
hints: string[],
};
export type JavaSettings = {
/**
* Project JDK home; empty = per module, the installed JDK matching the
* Java version it targets.
*/
jdk?: string,
/**
* Extra JVM options for the Java language server (jdtls), space-separated
* (VS Code's `java.jdt.ls.vmargs`).
*/
jdtlsVmArgs?: string,
/** Build Tools › Maven. */
maven?: MavenSettings,
};
/** Editor › Code Style › <Language> › Tabs and Indents (unset fields inherit). */
@@ -2369,6 +2420,7 @@ export type LanguagesSettings = {
rust?: RustSettings,
go?: GoSettings,
typescript?: TypeScriptSettings,
java?: JavaSettings,
};
/** What a freshly opened window should do once its frontend is up. */
@@ -2598,10 +2650,22 @@ export type MavenProject = {
javaVersion: number | null,
/** Maven launcher: the nearest `mvnw` up to the project root (absolute), else `mvn`. */
command: string,
/** Options before the goals (`-s`, `-Dmaven.repo.local=`); filled in by the shell from settings. */
options: string[],
/** Environment for runs (`JAVA_HOME` of the matching JDK); filled in by the shell. */
env: { [key in string]: string },
};
/** Build Tools › Maven. */
export type MavenSettings = {
/** Maven home (or its `mvn` executable); empty = the project's `mvnw`, else `mvn` on `PATH`. */
home?: string,
/** User `settings.xml` (`-s`); empty = `~/.m2/settings.xml`. */
userSettings?: string,
/** Local repository (`-Dmaven.repo.local`); empty = from `settings.xml`. */
localRepository?: string,
};
export type MemoryCategory =
/** The backend and its WebView processes. */
"app" | "languageServer" |
@@ -2691,6 +2755,13 @@ export type OpenOutcome =
/** The caller should open the project in its own window. */
{ kind: "current" };
export type OpenProject = {
name: string,
root: string,
/** Open in the calling window. */
current: boolean,
};
/** A node of a document outline (Structure tool window, breadcrumbs). */
export type OutlineItem = {
name: string,
@@ -3237,7 +3308,11 @@ export type Sdk = {
/** What [`detect`] looks for. */
export type SdkKind = "python" | "node" |
/** npm / pnpm / yarn executables. */
"packageManager" | "rust" | "go" | "typeScript";
"packageManager" | "rust" | "go" | "typeScript" |
/** JDK homes. */
"jdk" |
/** Maven homes. */
"maven";
export type SearchEvent = { type: "file"; file: FileMatches } | { type: "done"; summary: SearchSummary };
@@ -3346,6 +3421,11 @@ export type Settings_Deserialize = {
terminal?: TerminalSettings,
actionsOnSave?: ActionsOnSaveSettings,
externalTools?: ExternalTool[],
/**
* Language servers / debug adapters at a user-chosen location, by the
* command the language definition launches (`elixir-ls`, `codelldb`).
*/
tools?: { [key in string]: ToolSettings },
};
export type Settings_Serialize = {
@@ -3379,6 +3459,11 @@ export type Settings_Serialize = {
terminal: TerminalSettings,
actionsOnSave: ActionsOnSaveSettings,
externalTools: ExternalTool[],
/**
* Language servers / debug adapters at a user-chosen location, by the
* command the language definition launches (`elixir-ls`, `codelldb`).
*/
tools: { [key in string]: ToolSettings },
};
export type Severity = "error" | "warning" | "info" | "hint";
@@ -3613,6 +3698,17 @@ export type SyntaxErrors = {
truncated: boolean,
};
/** Highlight classes sent to the UI, which maps each onto a Lezer tag. */
export type SyntaxHighlightKind = "keyword" | "string" | "stringSpecial" | "escape" | "regexp" | "atom" | "number" | "constant" | "comment" | "docComment" | "function" | "functionCall" | "builtin" | "type" | "namespace" | "variable" | "selfVariable" | "property" | "attribute" | "macro" | "label" | "tag" | "operator" | "punctuation";
/** Highlighted ranges of a whole document, packed like LSP semantic tokens. */
export type SyntaxHighlights = {
/** Legend: `data` kind `i` is `kinds[i]`. */
kinds: SyntaxHighlightKind[],
/** `[from, to, kind]` triples: sorted, non-overlapping UTF-16 offsets. */
data: number[],
};
/** One tree-sitter node. */
export type SyntaxNode = {
/** Grammar node kind, e.g. `method_invocation`, `identifier`, `;`. */
@@ -3774,15 +3870,26 @@ export type ToolInfo = {
/** Manual install instructions from the language definition. */
installHint: string | null,
homepage: string | null,
/** Why the executable chosen in settings cannot be used (status is then `Missing`). */
customError: string | null,
};
export type ToolKind = "languageServer" | "debugger";
export type ToolKind = "languageServer" | "debugger" |
/** Loaded into another tool's process, e.g. a jdtls agent. */
"plugin";
export type ToolSettings = {
/** Executable to launch instead of the managed / `PATH` one; empty = auto-detect. */
path?: string,
};
export type ToolStatus =
/** Installed by the IDE (managed tools dir or a toolchain component it manages). */
"installed" |
/** Found on the system `PATH`. */
"onPath" | "missing";
"onPath" |
/** The executable chosen in settings. */
"custom" | "missing";
export type TypeScriptSettings = {
/**
@@ -3828,6 +3935,14 @@ export type VcsConfirmationSettings = {
onDelete?: string,
};
/** A repository of the project (IDEA's VCS root). */
export type VcsRoot = {
/** Worktree root. */
root: IpcPath,
/** Merge / rebase / cherry-pick / revert in progress. */
operation: string | null,
};
/** Version Control (main page) and its sub-pages. */
export type VcsSettings = {
/** Colour folders that contain changed files (project tree, tabs). */
+7
Переглянути файл
@@ -18,6 +18,7 @@ import {
type LineEnding,
type OutlineItem,
type Range,
type SyntaxHighlights,
type TextChange,
} from "@/platform/ipc";
@@ -43,6 +44,8 @@ export interface DocBackend {
setEncoding(doc: DocId, encoding: string, reload: boolean): Promise<string>;
outline(doc: DocId): Promise<OutlineItem[]>;
folding(doc: DocId): Promise<FoldRange[]>;
/** Tree-sitter highlighting, for languages without a CodeMirror mode. */
highlights(doc: DocId): Promise<SyntaxHighlights>;
selectionRanges(doc: DocId, offset: number): Promise<Range[]>;
languages(): Promise<LanguageInfo[]>;
onPatched(handler: (e: DocPatchedEvent) => void): () => void;
@@ -62,6 +65,7 @@ export const ipcBackend: DocBackend = {
setEncoding: (doc, encoding, reload) => call(commands.docSetEncoding(doc, encoding, reload)),
outline: (doc) => call(commands.docOutline(doc)),
folding: (doc) => call(commands.docFolding(doc)),
highlights: (doc) => call(commands.docHighlights(doc)),
selectionRanges: (doc, offset) => call(commands.docSelectionRanges(doc, offset)),
languages: () => commands.languages(),
onPatched: (h) => onIdeEvent("docPatched", (e) => h(e)),
@@ -343,6 +347,9 @@ export function createMemoryBackend(files: Record<string, string> = {}): MemoryB
}
return items;
},
async highlights() {
return { kinds: [], data: [] };
},
async folding(doc) {
const d = get(doc);
const out: FoldRange[] = [];
+2
Переглянути файл
@@ -25,6 +25,7 @@ import { openideaTheme } from "./theme";
import { caretRowHighlight } from "./caretRow";
import { changeLane, overviewLane } from "./lanes";
import { foldingExtension } from "./folding";
import { syntaxHighlightField } from "./syntaxHighlight";
import { indentGuides } from "./indentGuides";
import { stickyMaxLines, stickyScroll } from "./stickyScroll";
import { findExtension } from "./find";
@@ -267,6 +268,7 @@ export function baseExtensions(o: SetupOptions): Extension {
clipboardHistoryExtension,
indentOnInput(),
syntaxHighlighting(openideaHighlightStyle),
syntaxHighlightField,
closeBrackets(),
caretRowHighlight,
fontZoom,
+37
Переглянути файл
@@ -0,0 +1,37 @@
import { describe, expect, it } from "vitest";
import { EditorState } from "@codemirror/state";
import { highlightingFor, syntaxHighlighting } from "@codemirror/language";
import { tags as t } from "@lezer/highlight";
import { openideaHighlightStyle } from "./highlight";
import { setSyntaxHighlights, syntaxHighlightField } from "./syntaxHighlight";
function marks(state: EditorState) {
const out: { text: string; cls: string }[] = [];
state.field(syntaxHighlightField).between(0, state.doc.length, (from, to, d) => {
out.push({ text: state.doc.sliceString(from, to), cls: d.spec.class as string });
});
return out;
}
describe("syntaxHighlightField", () => {
const create = () =>
EditorState.create({ doc: "def hi, do: :ok", extensions: [syntaxHighlighting(openideaHighlightStyle), syntaxHighlightField] });
it("styles backend ranges with the active highlight style and maps them through edits", () => {
let state = create();
state = state.update({
effects: setSyntaxHighlights.of({ kinds: ["keyword", "atom", "functionCall"], data: [0, 3, 0, 4, 6, 2, 12, 15, 1, 99, 120, 0] }),
}).state;
const keyword = highlightingFor(state, [t.keyword]);
const atom = highlightingFor(state, [t.atom]);
expect(keyword).toBeTruthy();
expect(marks(state)).toEqual([
{ text: "def", cls: keyword },
{ text: "hi", cls: highlightingFor(state, [t.function(t.variableName)]) },
{ text: ":ok", cls: atom },
]);
state = state.update({ changes: { from: 0, insert: " " } }).state;
expect(marks(state).map((m) => m.text)).toEqual(["def", "hi", ":ok"]);
});
});
+66
Переглянути файл
@@ -0,0 +1,66 @@
/**
* Tree-sitter highlighting (`doc_highlights`) for languages without a
* CodeMirror mode (Elixir, ...): backend kinds → Lezer tags, so the colours
* come from the same highlight style and Color Scheme settings as Lezer
* highlighting. Refreshed with folding; in between, marks are mapped through
* the changes.
*/
import { StateEffect, StateField, type EditorState } from "@codemirror/state";
import { Decoration, EditorView, type DecorationSet } from "@codemirror/view";
import { highlightingFor } from "@codemirror/language";
import { tags as t, type Tag } from "@lezer/highlight";
import type { SyntaxHighlightKind, SyntaxHighlights } from "@/platform/ipc";
const TAGS: Record<SyntaxHighlightKind, Tag> = {
keyword: t.keyword,
string: t.string,
stringSpecial: t.special(t.string),
escape: t.escape,
regexp: t.regexp,
atom: t.atom,
number: t.number,
constant: t.constant(t.variableName),
comment: t.comment,
docComment: t.docComment,
function: t.function(t.definition(t.variableName)),
functionCall: t.function(t.variableName),
builtin: t.standard(t.variableName),
type: t.typeName,
namespace: t.namespace,
variable: t.variableName,
selfVariable: t.self,
property: t.propertyName,
attribute: t.annotation,
macro: t.macroName,
label: t.labelName,
tag: t.tagName,
operator: t.operator,
punctuation: t.punctuation,
};
export const setSyntaxHighlights = StateEffect.define<SyntaxHighlights>();
function decorations(state: EditorState, h: SyntaxHighlights): DecorationSet {
const marks = h.kinds.map((k) => {
const cls = highlightingFor(state, [TAGS[k]]);
return cls ? Decoration.mark({ class: cls }) : null;
});
const len = state.doc.length;
const ranges = [];
for (let i = 0; i + 2 < h.data.length; i += 3) {
const from = h.data[i]!;
const to = Math.min(h.data[i + 1]!, len);
const mark = marks[h.data[i + 2]!];
if (mark && from < to) ranges.push(mark.range(from, to));
}
return Decoration.set(ranges, true);
}
export const syntaxHighlightField = StateField.define<DecorationSet>({
create: () => Decoration.none,
update(deco, tr) {
for (const e of tr.effects) if (e.is(setSyntaxHighlights)) return decorations(tr.state, e.value);
return tr.docChanged ? deco.map(tr.changes) : deco;
},
provide: (f) => EditorView.decorations.from(f),
});
+12 -13
Переглянути файл
@@ -1,5 +1,4 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { closePopup, useLspPopup } from "@/editor/lsp/popupStore";
import type { DocModel } from "./model/document";
import { readOnlyQuestion, toggleReadOnly } from "./fileAttributes";
@@ -13,34 +12,34 @@ function model(readOnly: boolean, extra: Partial<{ virtual: boolean; banner: str
} as unknown as DocModel & { setReadOnly: ReturnType<typeof vi.fn> };
}
beforeEach(() => closePopup());
let answer = true;
const { confirm } = vi.hoisted(() => ({ confirm: vi.fn(async () => answer) }));
vi.mock("@/workbench/messages", () => ({ confirm }));
beforeEach(() => confirm.mockClear());
describe("Toggle Read-only Attribute", () => {
it("asks before making a read-only file writable, then toggles", async () => {
const m = model(true);
answer = true;
toggleReadOnly(m);
const popup = useLspPopup.getState().popup;
expect(popup).toMatchObject({ kind: "choice", title: "Make File Writable" });
if (popup?.kind !== "choice") throw new Error("no choice");
expect(popup.choices.map((c) => c.label)).toEqual(["Make Writable", "Cancel"]);
popup.choices[0]!.run();
expect(confirm).toHaveBeenCalledWith(expect.objectContaining({ title: "Make File Writable", ok: "Make Writable" }));
await vi.waitFor(() => expect(m.setReadOnly).toHaveBeenCalledWith(false));
});
it("Cancel leaves the file alone", () => {
it("Cancel leaves the file alone", async () => {
const m = model(false);
answer = false;
toggleReadOnly(m);
const popup = useLspPopup.getState().popup;
if (popup?.kind !== "choice") throw new Error("no choice");
expect(popup.title).toBe("Make File Read-only");
popup.choices[1]!.run();
expect(confirm).toHaveBeenCalledWith(expect.objectContaining({ title: "Make File Read-only" }));
await Promise.resolve();
expect(m.setReadOnly).not.toHaveBeenCalled();
});
it("does nothing for library and binary documents", () => {
toggleReadOnly(model(true, { virtual: true }));
toggleReadOnly(model(true, { banner: "binary" }));
expect(useLspPopup.getState().popup).toBeNull();
expect(confirm).not.toHaveBeenCalled();
expect(readOnlyQuestion("a.txt", false).confirm).toBe("Make Read-only");
});
});
+4 -10
Переглянути файл
@@ -5,8 +5,8 @@
*/
import { call, commands, isTauri } from "@/platform/ipc";
import { basename } from "@/platform/project";
import { openPopup } from "@/editor/lsp/popupStore";
import { notifications } from "@/workbench/contributions";
import { confirm } from "@/workbench/messages";
import type { DocModel } from "./model/document";
export function readOnlyQuestion(name: string, readOnly: boolean) {
@@ -36,13 +36,7 @@ export function toggleReadOnly(model: DocModel) {
const meta = model.getMeta();
if (meta.banner === "binary" || meta.banner === "tooLarge") return;
const q = readOnlyQuestion(basename(model.path), meta.readOnly);
openPopup({
kind: "choice",
title: q.title,
message: q.message,
choices: [
{ label: q.confirm, primary: true, run: () => void setFileWritable(model, meta.readOnly) },
{ label: "Cancel", run: () => {} },
],
});
void confirm({ title: q.title, message: q.message, ok: q.confirm }).then(
(ok) => ok && void setFileWritable(model, meta.readOnly),
);
}
+15 -2
Переглянути файл
@@ -7,7 +7,7 @@ import { EditorView } from "@codemirror/view";
import type { LanguageDescription, LanguageSupport } from "@codemirror/language";
import { create } from "zustand";
import type { EditorConfigProps } from "@/bindings";
import type { DocId, DocumentInfo, EditorSettings, FileSettings, LineEnding, OutlineItem, Settings } from "@/platform/ipc";
import type { DocId, DocumentInfo, EditorSettings, FileSettings, LineEnding, OutlineItem, Settings, SyntaxHighlights } from "@/platform/ipc";
import {
_emitEditorEvent,
_saveParticipants,
@@ -22,6 +22,7 @@ import type { DocBackend, LanguageInfo } from "../backend";
import { findLanguageDescription, languageInfo, loadLanguageInfos, loadSupport, loadedSupport, commentTokens } from "../cm/languages";
import { foldEffect } from "@codemirror/language";
import { backendFolds, setBackendFolds } from "../cm/folding";
import { setSyntaxHighlights } from "../cm/syntaxHighlight";
import {
caretFor,
compartments,
@@ -265,6 +266,7 @@ export class DocModel {
addSlot(slot: EditorSlot) {
this.slots.add(slot);
if (this.highlights?.counter === this.changeCounter) slot.reconfigure([setSyntaxHighlights.of(this.highlights.value)]);
}
removeSlot(slot: EditorSlot) {
@@ -332,6 +334,8 @@ export class DocModel {
indentOverride: { tabSize: number; insertSpaces: boolean } | null = null;
/** Indentation detected in the file's text at open time. */
detectedIndent: { insertSpaces: boolean; size?: number } | null = null;
/** Last tree-sitter highlighting, for slots opened before the next refresh. */
private highlights: { counter: number; value: SyntaxHighlights } | null = null;
/** Fold-by-default has been applied (first folding ranges of the document). */
private initialFolds = false;
/** Signature of settings that require contributions to be rebuilt. */
@@ -423,7 +427,12 @@ export class DocModel {
await this.sync.whenIdle();
const counter = this.changeCounter;
const backend = this.manager.backend;
const [folds, outline] = await Promise.allSettled([backend.folding(this.doc), backend.outline(this.doc)]);
const [folds, outline, highlights] = await Promise.allSettled([
backend.folding(this.doc),
backend.outline(this.doc),
// Without a CodeMirror mode, colours come from the grammar's tree-sitter query.
this.desc ? null : backend.highlights(this.doc),
]);
if (this.closed) return;
if (counter !== this.changeCounter) {
this.scheduleRefresh();
@@ -436,6 +445,10 @@ export class DocModel {
this.foldByDefault();
}
}
if (highlights.status === "fulfilled" && highlights.value) {
this.highlights = { counter, value: highlights.value };
for (const s of this.slots) s.reconfigure([setSyntaxHighlights.of(highlights.value)]);
}
if (outline.status === "fulfilled") {
useOutline.setState({ [this.path]: outline.value });
const lines = methodLines(outline.value);
+47 -9
Переглянути файл
@@ -8,7 +8,7 @@ import { useEffect, useLayoutEffect, useRef, type KeyboardEvent } from "react";
import { create } from "zustand";
import clsx from "clsx";
import type { EditorView } from "@codemirror/view";
import { Button, IconButton, SearchField } from "@/ui";
import { Button, IconButton, SearchField, T } from "@/ui";
import { editorController, useFindBars, useTabs } from "../controller";
import {
countMatches,
@@ -198,7 +198,11 @@ function FindBarInner({ paneId, replace, seq }: { paneId: string; replace: boole
else run(replaceNext);
} else run(back ? findPrevious : findNext);
} else if (e.altKey && !e.metaKey && !e.ctrlKey) {
const map: Record<string, "caseSensitive" | "wholeWord" | "regexp"> = { KeyC: "caseSensitive", KeyW: "wholeWord", KeyX: "regexp" };
const map: Record<string, "caseSensitive" | "wholeWord" | "regexp"> = {
KeyC: "caseSensitive",
KeyW: "wholeWord",
KeyX: "regexp",
};
const k = map[e.code];
if (k) {
e.preventDefault();
@@ -235,17 +239,51 @@ function FindBarInner({ paneId, replace, seq }: { paneId: string; replace: boole
invalid={invalid || none}
onKeyDown={(e) => onKeyDown(e, "find")}
toggles={[
{ id: "case", icon: "case", title: "Match Case", shortcut: "⌥C", pressed: opts.caseSensitive, onToggle: () => toggle("caseSensitive") },
{ id: "word", icon: "word", title: "Words", shortcut: "⌥W", pressed: opts.wholeWord, onToggle: () => toggle("wholeWord") },
{ id: "regex", icon: "regex", title: "Regex", shortcut: "⌥X", pressed: opts.regexp, onToggle: () => toggle("regexp") },
{ id: "scope", icon: "filter", title: "In Selection", shortcut: "⌥E", pressed: scoped, onToggle: () => toggleScope(paneId) },
{
id: "case",
icon: "case",
title: "Match Case",
shortcut: "⌥C",
pressed: opts.caseSensitive,
onToggle: () => toggle("caseSensitive"),
},
{
id: "word",
icon: "word",
title: "Words",
shortcut: "⌥W",
pressed: opts.wholeWord,
onToggle: () => toggle("wholeWord"),
},
{
id: "regex",
icon: "regex",
title: "Regex",
shortcut: "⌥X",
pressed: opts.regexp,
onToggle: () => toggle("regexp"),
},
{
id: "scope",
icon: "filter",
title: "In Selection",
shortcut: "⌥E",
pressed: scoped,
onToggle: () => toggleScope(paneId),
},
]}
/>
<div className={styles.findButtons}>
<span className={clsx(styles.findCount, (none || invalid) && styles.findCountNone)} aria-live="polite">
{counter}
</span>
<IconButton icon="arrow-up" title="Previous Occurrence" shortcut="⇧↵" size="small" onClick={() => run(findPrevious)} />
<IconButton
icon="arrow-up"
title="Previous Occurrence"
shortcut="⇧↵"
size="small"
onClick={() => run(findPrevious)}
/>
<IconButton icon="arrow-down" title="Next Occurrence" shortcut="↵" size="small" onClick={() => run(findNext)} />
<IconButton
icon="replace"
@@ -270,10 +308,10 @@ function FindBarInner({ paneId, replace, seq }: { paneId: string; replace: boole
/>
<div className={styles.replaceButtons}>
<Button size="small" onClick={() => run(replaceNext)} disabled={!opts.search || invalid}>
Replace
<T>Replace</T>
</Button>
<Button size="small" onClick={() => run(replaceAll)} disabled={!opts.search || invalid}>
Replace All
<T>Replace All</T>
</Button>
</div>
</>
+51 -9
Переглянути файл
@@ -9,11 +9,19 @@ import clsx from "clsx";
import { create } from "zustand";
import { call, commands, isTauri, type OutlineItem } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { Icon, Popup } from "@/ui";
import { Icon, Popup, T } from "@/ui";
import { editorController, useEditorStatus } from "../controller";
import { useOutline } from "../model/document";
import { symbolChain } from "./outline";
import { dirChildren, iconOf, navSegments, stepSegment, symbolChildren, type NavChild, type NavSegment } from "./navBar";
import {
dirChildren,
iconOf,
navSegments,
stepSegment,
symbolChildren,
type NavChild,
type NavSegment,
} from "./navBar";
import styles from "./NavBarPopup.module.css";
export const useNavBarPopup = create<{ open: boolean; seq: number }>(() => ({ open: false, seq: 0 }));
@@ -48,7 +56,12 @@ function NavBar({ path, line, col }: { path: string; line: number; col: number }
const project = useProject((s) => s.project);
const outline = useOutline((s) => s[path]);
const initial = useMemo(
() => navSegments(project ? { root: project.root, name: project.name } : null, path, outline ? symbolChain(outline, line, col) : []),
() =>
navSegments(
project ? { root: project.root, name: project.name } : null,
path,
outline ? symbolChain(outline, line, col) : [],
),
// The bar is a snapshot of where ⌘↑ was pressed.
// eslint-disable-next-line react-hooks/exhaustive-deps
[],
@@ -76,7 +89,10 @@ function NavBar({ path, line, col }: { path: string; line: number; col: number }
const choose = (child: NavChild) => {
if (!list) return;
if (child.kind === "dir") {
const segs: NavSegment[] = [...segments.slice(0, list.seg + 1), { kind: "dir", path: child.path, label: child.label }];
const segs: NavSegment[] = [
...segments.slice(0, list.seg + 1),
{ kind: "dir", path: child.path, label: child.label },
];
setSegments(segs);
setActive(segs.length - 1);
void openList(segs.length - 1, segs);
@@ -101,7 +117,8 @@ function NavBar({ path, line, col }: { path: string; line: number; col: number }
if (e.key === "ArrowLeft") move(-1);
else if (e.key === "ArrowRight") move(1);
else if (e.key === "ArrowDown" && !list) void openList(active);
else if (e.key === "ArrowDown" && list) setList({ ...list, active: Math.min(list.items.length - 1, list.active + 1) });
else if (e.key === "ArrowDown" && list)
setList({ ...list, active: Math.min(list.items.length - 1, list.active + 1) });
else if (e.key === "ArrowUp" && list) setList({ ...list, active: Math.max(0, list.active - 1) });
else if (e.key === "Enter" && list) {
const child = list.items[list.active];
@@ -123,8 +140,23 @@ function NavBar({ path, line, col }: { path: string; line: number; col: number }
}, [list]);
return (
<Popup open anchor={anchor} placement="bottom-start" offset={0} onClose={close} aria-label="Navigation bar" className={styles.popup}>
<div className={styles.root} tabIndex={0} data-autofocus onKeyDown={onKeyDown} role="toolbar" aria-label="Navigation bar">
<Popup
open
anchor={anchor}
placement="bottom-start"
offset={0}
onClose={close}
aria-label="Navigation bar"
className={styles.popup}
>
<div
className={styles.root}
tabIndex={0}
data-autofocus
onKeyDown={onKeyDown}
role="toolbar"
aria-label="Navigation bar"
>
<div className={styles.bar}>
{segments.map((s, i) => (
<span key={`${i}:${s.path}:${s.label}`} className={styles.segmentWrap}>
@@ -147,8 +179,18 @@ function NavBar({ path, line, col }: { path: string; line: number; col: number }
))}
</div>
{list && (
<div ref={listRef} className={styles.list} style={{ marginLeft: list.left }} role="listbox" aria-label="Children">
{list.items.length === 0 && <div className={styles.empty}>Nothing here</div>}
<div
ref={listRef}
className={styles.list}
style={{ marginLeft: list.left }}
role="listbox"
aria-label="Children"
>
{list.items.length === 0 && (
<div className={styles.empty}>
<T>Nothing here</T>
</div>
)}
{list.items.map((c, i) => (
<div
key={`${c.path}:${c.label}:${i}`}
+15 -5
Переглянути файл
@@ -2,6 +2,7 @@
* Navigation bar popup (⌘↑) model: the path of the active file as segments
* (project › dirs › file › symbols at the caret) and the child list of a segment.
*/
import { isIgnoredName } from "@/platform/ignoredNames";
import type { FileEntry, OutlineItem } from "@/platform/ipc";
import { badgeKind, fileIconName } from "@/ui";
@@ -19,7 +20,11 @@ const parentOf = (p: string) => p.slice(0, Math.max(p.lastIndexOf("/"), 0)) || "
const nameOf = (p: string) => p.slice(p.lastIndexOf("/") + 1);
/** Segments for `path`; directories from the project root, or just the parent folder outside it. */
export function navSegments(project: { root: string; name: string } | null, path: string, chain: readonly OutlineItem[]): NavSegment[] {
export function navSegments(
project: { root: string; name: string } | null,
path: string,
chain: readonly OutlineItem[],
): NavSegment[] {
const out: NavSegment[] = [];
const parent = parentOf(path);
if (project && (parent === project.root || parent.startsWith(project.root + "/"))) {
@@ -42,12 +47,17 @@ export function navSegments(project: { root: string; name: string } | null, path
return out;
}
const HIDDEN = new Set([".git", ".hg", ".svn", ".DS_Store", "__pycache__"]);
export function dirChildren(entries: readonly FileEntry[]): NavChild[] {
return entries
.filter((e) => !HIDDEN.has(e.name))
.map((e) => ({ kind: e.kind === "dir" || (e.kind === "symlink" && e.size === 0) ? "dir" : "file", path: e.path, label: e.name }) as NavChild);
.filter((e) => !isIgnoredName(e.name))
.map(
(e) =>
({
kind: e.kind === "dir" || (e.kind === "symlink" && e.size === 0) ? "dir" : "file",
path: e.path,
label: e.name,
}) as NavChild,
);
}
/** Children of a file or symbol segment: its outline items (one level). */
-11
Переглянути файл
@@ -276,14 +276,3 @@
color: var(--fg-search-match, inherit);
border-radius: 2px;
}
.choiceMessage {
padding: 14px 16px 4px;
font-size: var(--fs-ui);
color: var(--fg);
}
.choiceDetail {
padding: 4px 16px 12px;
font-size: var(--fs-ui);
color: var(--fg-muted);
}
-60
Переглянути файл
@@ -1,60 +0,0 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { act, fireEvent, render, screen } from "@testing-library/react";
import { usePlatform } from "@/platform/platformInfo";
import { LspPopups } from "./Popups";
import { openPopup, useLspPopup } from "./popupStore";
function openUsagesDetected() {
const view = vi.fn();
const anyway = vi.fn();
const cancel = vi.fn();
act(() =>
openPopup({
kind: "choice",
title: "Usages Detected",
message: "Function 'unused' has 1 usage that is not safe to delete.",
choices: [
{ label: "View Usages", primary: true, run: view },
{ label: "Delete Anyway", run: anyway },
{ label: "Cancel", run: cancel },
],
onDismiss: cancel,
}),
);
return { view, anyway, cancel };
}
const footerLabels = () =>
[...screen.getByRole("dialog").querySelectorAll("[data-dialog-footer] button")].map((b) => b.textContent);
describe("Usages Detected dialog", () => {
const os = usePlatform.getState().os;
afterEach(() => {
usePlatform.setState({ os });
act(() => useLspPopup.setState({ popup: null }));
});
it("macOS: Cancel · Delete Anyway · View Usages (default rightmost, focused); Enter views usages", () => {
usePlatform.setState({ os: "macos" });
render(<LspPopups />);
const { view } = openUsagesDetected();
expect(footerLabels()).toEqual(["Cancel", "Delete Anyway", "View Usages"]);
expect(document.activeElement).toBe(screen.getByRole("button", { name: "View Usages" }));
fireEvent.keyDown(screen.getByRole("dialog"), { key: "Enter" });
expect(view).toHaveBeenCalledTimes(1);
expect(useLspPopup.getState().popup).toBeNull();
});
it("Windows: View Usages · Delete Anyway · Cancel; Escape and the close button cancel", () => {
usePlatform.setState({ os: "windows" });
render(<LspPopups />);
let { cancel } = openUsagesDetected();
expect(footerLabels()).toEqual(["View Usages", "Delete Anyway", "Cancel"]);
fireEvent.keyDown(document.body, { key: "Escape" });
expect(cancel).toHaveBeenCalledTimes(1);
({ cancel } = openUsagesDetected());
fireEvent.click(screen.getByRole("button", { name: "Close" }));
expect(cancel).toHaveBeenCalledTimes(1);
expect(screen.queryByRole("dialog")).toBeNull();
});
});
+51 -57
Переглянути файл
@@ -1,7 +1,19 @@
/** React popups for LSP editor features, rendered as a workbench overlay. */
import { useEffect, useMemo, useRef, useState, type KeyboardEvent } from "react";
import clsx from "clsx";
import { Button, Dialog, HighlightedText, Icon, Input, List, Popup, SymbolBadge, fileIconName, fuzzyMatch } from "@/ui";
import {
Button,
Dialog,
HighlightedText,
Icon,
Input,
List,
Popup,
SymbolBadge,
fileIconName,
fuzzyMatch,
T,
} from "@/ui";
import { basename, relativePath, useProject } from "@/platform/project";
import { editorService } from "@/workbench/contributions";
import { closePopup, useLspPopup, type ListPopupItem, type LspPopup } from "./popupStore";
@@ -24,9 +36,7 @@ function ListPopup({ popup }: { popup: Extract<LspPopup, { kind: "list" }> }) {
const [query, setQuery] = useState("");
const filtered = useMemo(() => {
if (!query) return popup.items.map((item) => ({ item, match: null as number[] | null }));
return popup.items
.map((item) => ({ item, match: fuzzyMatch(item.label, query) }))
.filter((r) => r.match !== null);
return popup.items.map((item) => ({ item, match: fuzzyMatch(item.label, query) })).filter((r) => r.match !== null);
}, [popup.items, query]);
const firstEnabled = Math.max(
0,
@@ -59,7 +69,9 @@ function ListPopup({ popup }: { popup: Extract<LspPopup, { kind: "list" }> }) {
const width = useMemo(() => {
const chars = Math.max(
popup.title.length,
...popup.items.map((i) => i.label.length + (i.preview?.length ?? 0) + (i.detail?.length ?? 0) + (i.shortcut?.length ?? 0)),
...popup.items.map(
(i) => i.label.length + (i.preview?.length ?? 0) + (i.detail?.length ?? 0) + (i.shortcut?.length ?? 0),
),
);
return Math.min(720, Math.max(320, chars * 7 + 90));
}, [popup]);
@@ -85,7 +97,11 @@ function ListPopup({ popup }: { popup: Extract<LspPopup, { kind: "list" }> }) {
hoverSelects
aria-label={popup.title}
onActivate={(r) => activate(r.item)}
empty={<span className={styles.empty}>Nothing matches</span>}
empty={
<span className={styles.empty}>
<T>Nothing matches</T>
</span>
}
renderItem={({ item, match }) => (
<div
className={clsx(styles.item, item.disabled && styles.disabled, item.emphasis && styles.emphasis)}
@@ -125,7 +141,14 @@ function RenamePopup({ popup }: { popup: Extract<LspPopup, { kind: "rename" }> }
return true;
};
return (
<Popup open anchor={popup.anchor} placement="bottom-start" onClose={closePopup} aria-label={popup.title} className={styles.renamePopup}>
<Popup
open
anchor={popup.anchor}
placement="bottom-start"
onClose={closePopup}
aria-label={popup.title}
className={styles.renamePopup}
>
<form
onSubmit={(e) => {
e.preventDefault();
@@ -143,7 +166,8 @@ function RenamePopup({ popup }: { popup: Extract<LspPopup, { kind: "rename" }> }
value={value}
onChange={(e) => setValue(e.target.value)}
onKeyDown={(e) => {
if ((e.key === "ArrowDown" || e.key === "ArrowUp") && pick(e.key === "ArrowDown" ? 1 : -1)) e.preventDefault();
if ((e.key === "ArrowDown" || e.key === "ArrowUp") && pick(e.key === "ArrowDown" ? 1 : -1))
e.preventDefault();
}}
invalid={!value.trim()}
aria-label="New name"
@@ -214,14 +238,11 @@ function DefinitionPopup({ popup }: { popup: Extract<LspPopup, { kind: "definiti
</span>
<span className={styles.spacer} />
<Button size="small" variant="ghost" onClick={open}>
Open
<T>Open</T>
</Button>
</div>
<div className={clsx(popup.themeClasses, styles.docScope)}>
<DomContent
className={styles.defBody}
build={() => renderCode(popup.text, popup.language, "cm-lsp-code")}
/>
<DomContent className={styles.defBody} build={() => renderCode(popup.text, popup.language, "cm-lsp-code")} />
</div>
</Popup>
);
@@ -276,53 +297,28 @@ function PreviewDialog({ popup }: { popup: Extract<LspPopup, { kind: "preview" }
})}
</ul>
) : (
<ul className={styles.previewList} aria-label="Changes">
{summary.entries.map((e) => (
<li key={e.path} className={styles.previewRow}>
<Icon name={fileIconName(basename(e.path))} size={14} className={styles.itemIcon} />
<span className={styles.previewName}>{basename(e.path)}</span>
<span className={styles.previewPath}>{relativePath(root, e.path)}</span>
<span className={styles.spacer} />
{e.operation === "rename" && e.to && <span className={styles.previewOp}>→ {basename(e.to)}</span>}
{e.operation && e.operation !== "rename" && <span className={styles.previewOp}>{e.operation}</span>}
{e.edits > 0 && (
<span className={styles.previewCount}>
{e.edits} {e.edits === 1 ? "occurrence" : "occurrences"}
</span>
)}
</li>
))}
</ul>
<ul className={styles.previewList} aria-label="Changes">
{summary.entries.map((e) => (
<li key={e.path} className={styles.previewRow}>
<Icon name={fileIconName(basename(e.path))} size={14} className={styles.itemIcon} />
<span className={styles.previewName}>{basename(e.path)}</span>
<span className={styles.previewPath}>{relativePath(root, e.path)}</span>
<span className={styles.spacer} />
{e.operation === "rename" && e.to && <span className={styles.previewOp}>→ {basename(e.to)}</span>}
{e.operation && e.operation !== "rename" && <span className={styles.previewOp}>{e.operation}</span>}
{e.edits > 0 && (
<span className={styles.previewCount}>
{e.edits} {e.edits === 1 ? "occurrence" : "occurrences"}
</span>
)}
</li>
))}
</ul>
)}
</Dialog>
);
}
function ChoiceDialog({ popup }: { popup: Extract<LspPopup, { kind: "choice" }> }) {
// Answer first, then close (unless the answer opened another popup).
const answer = (run?: () => void) => {
run?.();
if (useLspPopup.getState().popup === popup) closePopup();
};
return (
<Dialog
open
onClose={() => answer(popup.onDismiss)}
title={popup.title}
width={460}
buttons={popup.choices.map((c) => ({
label: c.label,
role: c.primary ? "default" : c.label === "Cancel" ? "cancel" : "extra",
autoFocus: c.primary,
onClick: () => answer(c.run),
}))}
>
<div className={styles.choiceMessage}>{popup.message}</div>
{popup.detail && <div className={styles.choiceDetail}>{popup.detail}</div>}
</Dialog>
);
}
/** Overlay host: renders the current LSP popup, if any. */
export function LspPopups() {
const popup = useLspPopup((s) => s.popup);
@@ -339,7 +335,5 @@ export function LspPopups() {
return <DefinitionPopup key={seq} popup={popup} />;
case "preview":
return <PreviewDialog key={seq} popup={popup} />;
case "choice":
return <ChoiceDialog key={seq} popup={popup} />;
}
}
-17
Переглянути файл
@@ -61,25 +61,8 @@ export type LspPopup =
warnings?: string[];
/** Individual occurrences with line previews (single-file syntax-based renames). */
occurrences?: PreviewOccurrence[];
}
| {
/** Modal question with several answers, e.g. Safe Delete's "Usages Detected". */
kind: "choice";
title: string;
message: string;
detail?: string;
choices: PopupChoice[];
/** Escape / close button / replaced by another popup. */
onDismiss?: () => void;
};
export interface PopupChoice {
label: string;
/** The default button (Enter). */
primary?: boolean;
run: () => void;
}
export interface PreviewOccurrence {
line: number;
/** The line's text and the occurrence within it. */
+18 -18
Переглянути файл
@@ -2,6 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { EditorState, Text } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { history, undo } from "@codemirror/commands";
import type { MessageRequest } from "@/workbench/messages";
import type { LocalSymbol, Location, Locals, OutlineItem, Range, StructuralRanges, SyntaxNode } from "@/bindings";
// --- backend fakes ---------------------------------------------------------
@@ -56,9 +57,13 @@ const showHint = vi.fn();
vi.mock("@/editor/lsp/hint", () => ({ showHint }));
const executeAction = vi.fn();
vi.mock("@/platform/actions", () => ({ executeAction }));
let answer = "cancel";
const ask = vi.fn(async (_request: MessageRequest) => ({ button: answer, checked: false }));
vi.mock("@/workbench/messages", () => ({ ask }));
const { deletionRange, localDeclaration, outlineItemAt, safeDelete, fileUsages, usagesMessage } = await import("./safeDelete");
const { useLspPopup, closePopup } = await import("@/editor/lsp/popupStore");
const { deletionRange, localDeclaration, outlineItemAt, safeDelete, fileUsages, usagesMessage } =
await import("./safeDelete");
const { closePopup } = await import("@/editor/lsp/popupStore");
const { lspDoc } = await import("@/editor/lsp/lsp");
// --- helpers ----------------------------------------------------------------
@@ -101,8 +106,6 @@ function item(text: string, name: string, decl: string, kind: OutlineItem["kind"
};
}
const flush = () => new Promise((r) => setTimeout(r, 0));
beforeEach(() => {
goto = ok([]);
outline = ok([]);
@@ -223,26 +226,23 @@ describe("safeDelete in the editor", () => {
outline = ok([item(text, "used", "fn used() {}")]);
references = ok([usage]);
const run = async (choice: string) => {
const run = async (button: string) => {
const v = editor(text, "used() {}");
const done = safeDelete(v);
for (let i = 0; i < 20 && useLspPopup.getState().popup?.kind !== "choice"; i++) await flush();
const popup = useLspPopup.getState().popup;
if (popup?.kind !== "choice") throw new Error("no dialog");
expect(popup.title).toBe("Usages Detected");
expect(popup.message).toBe("1 usage found");
expect(popup.choices.map((c) => c.label)).toEqual(["View Usages", "Delete Anyway", "Cancel"]);
popup.choices.find((c) => c.label === choice)!.run();
closePopup();
await done;
answer = button;
ask.mockClear();
await safeDelete(v);
const request = ask.mock.calls[0]![0];
expect(request.title).toBe("Usages Detected");
expect(request.body).toBe("1 usage found\nFunction 'used' has 1 usage that is not safe to delete.");
expect(request.buttons.map((b) => b.label)).toEqual(["View Usages", "Delete Anyway"]);
return v;
};
expect((await run("Cancel")).state.doc.toString()).toBe(text);
expect((await run("cancel")).state.doc.toString()).toBe(text);
expect(executeAction).not.toHaveBeenCalled();
expect((await run("View Usages")).state.doc.toString()).toBe(text);
expect((await run("view")).state.doc.toString()).toBe(text);
expect(executeAction).toHaveBeenCalledWith("find.showUsageResults", { symbol: "used", locations: [usage] });
expect((await run("Delete Anyway")).state.doc.toString()).toBe("fn unused() {\n unused();\n}\n\nfn main() {}\n");
expect((await run("delete")).state.doc.toString()).toBe("fn unused() {\n unused();\n}\n\nfn main() {}\n");
});
it("refuses a declaration in another file instead of doing something else", async () => {
+49 -38
Переглянути файл
@@ -20,7 +20,7 @@ import { structure } from "@/editor/structure";
import { docOf, isUnavailable, lspRequest } from "@/editor/lsp/lsp";
import { comparePos, offsetToPos, rangeContains, rangeToOffsets } from "@/editor/lsp/positions";
import { showHint } from "@/editor/lsp/hint";
import { openPopup, useLspPopup } from "@/editor/lsp/popupStore";
import { ask } from "@/workbench/messages";
import { cannotPerform } from "./catalog";
import { cancelled, languageName } from "./query";
@@ -56,7 +56,9 @@ export function deletionRange(
const restOk =
!rest ||
/^[;,]$/.test(rest) ||
(!!comments.line && (rest.startsWith(comments.line) || /^[;,]\s*/.test(rest) && rest.replace(/^[;,]\s*/, "").startsWith(comments.line)));
(!!comments.line &&
(rest.startsWith(comments.line) ||
(/^[;,]\s*/.test(rest) && rest.replace(/^[;,]\s*/, "").startsWith(comments.line))));
if (!restOk) return null;
// Attached comments and annotations above (no blank line in between).
@@ -88,7 +90,8 @@ export function deletionRange(
const next = last.number + 1;
if (blank(next) && next < doc.lines) end = doc.line(next).to + 1;
else if (blank(next)) end = doc.line(next).to;
else if (blank(startLine - 1) && /^[}\])]|^end\b/.test(doc.line(next).text.trim())) start = doc.line(startLine - 1).from;
else if (blank(startLine - 1) && /^[}\])]|^end\b/.test(doc.line(next).text.trim()))
start = doc.line(startLine - 1).from;
} else if (startLine > 1) {
// Last line: take the line break before it (and a blank line above).
start = doc.line(blank(startLine - 1) && startLine > 2 ? startLine - 2 : startLine - 1).to;
@@ -147,14 +150,17 @@ const FUNCTION_STATEMENT = /function|method|^def|^fn|func|procedure/;
/** Declaration statement of a syntax-resolved local, or why it can't be deleted on its own. */
export function localDeclaration(doc: Text, symbol: LocalSymbol, statement: SyntaxNode | null): Range | string {
if (symbol.kind === "parameter") return "Deleting a parameter changes its call sites; use Change Signature";
if (symbol.kind === "label" || symbol.kind === "type" || symbol.kind === "macro") return "Caret should be on a variable or function declaration";
if (symbol.kind === "label" || symbol.kind === "type" || symbol.kind === "macro")
return "Caret should be on a variable or function declaration";
if (!symbol.certain) return `'${symbol.name}' is declared more than once in this scope`;
if (!statement || !rangeContains(statement.range, symbol.definition.start)) return "The declaration could not be determined";
if (!statement || !rangeContains(statement.range, symbol.definition.start))
return "The declaration could not be determined";
const kind = statement.kind;
if (symbol.kind === "function") {
return FUNCTION_STATEMENT.test(kind) ? statement.range : "The declaration could not be determined";
}
if (COMPOUND_STATEMENT.test(kind) || !DECLARATION_STATEMENT.test(kind)) return `'${symbol.name}' is not declared by a separate statement`;
if (COMPOUND_STATEMENT.test(kind) || !DECLARATION_STATEMENT.test(kind))
return `'${symbol.name}' is not declared by a separate statement`;
const { from, to } = rangeToOffsets(doc, statement.range);
const defEnd = rangeToOffsets(doc, symbol.definition).to;
// Up to the initializer, the statement must declare only this name (no `a, b` / destructuring).
@@ -193,7 +199,13 @@ async function resolveTarget(view: EditorView, ctx: EditorDocContext): Promise<R
if (lsp)
return {
status: "ok",
target: { name: item.name, kind: kindLabel(item.kind), at: item.selection_range.start, range: item.range, local: null },
target: {
name: item.name,
kind: kindLabel(item.kind),
at: item.selection_range.start,
range: item.range,
local: null,
},
};
}
@@ -224,14 +236,20 @@ async function resolveTarget(view: EditorView, ctx: EditorDocContext): Promise<R
reason: `The language server for ${lang} is not available; only local declarations can be deleted safely without it`,
};
}
return { status: "refused", reason: item ? `'${name}' can't be deleted` : "Caret should be on the name of a declaration" };
return {
status: "refused",
reason: item ? `'${name}' can't be deleted` : "Caret should be on the name of a declaration",
};
}
/** LSP references to the target, its own declaration excluded. */
async function findUsages(ctx: EditorDocContext, target: SafeDeleteTarget): Promise<Location[]> {
const outside = (path: string, range: Range) =>
path !== ctx.path || comparePos(range.start, target.range.start) < 0 || comparePos(range.start, target.range.end) > 0;
if (target.local) return target.local.references.filter((r) => outside(ctx.path, r)).map((range) => ({ path: ctx.path, range }));
path !== ctx.path ||
comparePos(range.start, target.range.start) < 0 ||
comparePos(range.start, target.range.end) > 0;
if (target.local)
return target.local.references.filter((r) => outside(ctx.path, r)).map((range) => ({ path: ctx.path, range }));
const refs = await lspRequest(() => commands.lspReferences(ctx.doc, target.at, false));
return refs.filter((l) => outside(l.path, l.range));
}
@@ -242,7 +260,11 @@ async function findUsages(ctx: EditorDocContext, target: SafeDeleteTarget): Prom
export type UsagesAnswer = "view" | "delete" | "cancel";
/** `subject`: "Function 'foo'", "File 'a.ts'", "3 files" (`plural`). */
export function usagesMessage(subject: string, usages: readonly Location[], plural = false): { message: string; detail: string } {
export function usagesMessage(
subject: string,
usages: readonly Location[],
plural = false,
): { message: string; detail: string } {
const n = usages.length;
const files = new Set(usages.map((u) => u.path)).size;
const noun = n === 1 ? "usage that is" : "usages that are";
@@ -252,34 +274,23 @@ export function usagesMessage(subject: string, usages: readonly Location[], plur
};
}
/** IDEA's "Usages Detected" question; resolves "cancel" when dismissed or replaced. */
export function askUsagesDetected(subject: string, usages: readonly Location[], plural = false): Promise<UsagesAnswer> {
return new Promise((resolve) => {
let done = false;
const finish = (a: UsagesAnswer) => {
if (done) return;
done = true;
unsub();
resolve(a);
};
const { message, detail } = usagesMessage(subject, usages, plural);
openPopup({
kind: "choice",
title: "Usages Detected",
message,
detail,
choices: [
{ label: "View Usages", primary: true, run: () => finish("view") },
{ label: "Delete Anyway", run: () => finish("delete") },
{ label: "Cancel", run: () => finish("cancel") },
],
onDismiss: () => finish("cancel"),
});
const mine = useLspPopup.getState().popup;
const unsub = useLspPopup.subscribe((s) => {
if (s.popup !== mine) finish("cancel");
});
/** IDEA's "Usages Detected" question; resolves "cancel" when dismissed. */
export async function askUsagesDetected(
subject: string,
usages: readonly Location[],
plural = false,
): Promise<UsagesAnswer> {
const { message, detail } = usagesMessage(subject, usages, plural);
const { button } = await ask({
title: "Usages Detected",
icon: "warning",
body: `${message}\n${detail}`,
buttons: [
{ id: "view", label: "View Usages", primary: true },
{ id: "delete", label: "Delete Anyway" },
],
});
return button === "view" || button === "delete" ? button : "cancel";
}
/** Opens the Find Usages tool window with `usages` (code-insight's `find.showUsageResults`). */
+14 -8
Переглянути файл
@@ -9,7 +9,7 @@ import {
type StructuralLanguage,
} from "@/platform/ipc";
import { basename } from "@/platform/project";
import { Checkbox, Dialog, Input, Select, Spinner } from "@/ui";
import { Checkbox, Dialog, Input, Select, Spinner, T } from "@/ui";
import { ScopeFields, openDialog } from "./dialogs";
import { locateDuplicates, loadDuplicateOptions } from "./duplicates";
import { runInspection } from "./inspect";
@@ -45,7 +45,9 @@ function InspectCodeDialog({ onClose }: { onClose: () => void }) {
>
<div className={styles.form}>
<ScopeFields name="inspect-scope" value={scope} onChange={setScope} />
<div className={styles.hint}>Files are checked by their language servers; files without one are skipped.</div>
<div className={styles.hint}>
<T>Files are checked by their language servers; files without one are skipped.</T>
</div>
</div>
</Dialog>
);
@@ -76,7 +78,9 @@ function DuplicatesDialog({ onClose }: { onClose: () => void }) {
<div className={styles.form}>
<ScopeFields name="duplicates-scope" value={scope} onChange={setScope} />
<label className={styles.fieldRow}>
<span>Minimum size</span>
<span>
<T>Minimum size</T>
</span>
<Input
className={styles.number}
type="number"
@@ -185,7 +189,9 @@ function StructuralDialog({ replace, onClose }: { replace: boolean; onClose: ()
>
<div className={styles.form}>
<div className={styles.fieldRow}>
<span>Language</span>
<span>
<T>Language</T>
</span>
<Select
value={language || null}
options={options}
@@ -196,7 +202,7 @@ function StructuralDialog({ replace, onClose }: { replace: boolean; onClose: ()
/>
</div>
<label className={styles.fieldLabel} htmlFor="ssr-template">
Search template
<T>Search template</T>
</label>
<textarea
id="ssr-template"
@@ -211,7 +217,7 @@ function StructuralDialog({ replace, onClose }: { replace: boolean; onClose: ()
{replace && (
<>
<label className={styles.fieldLabel} htmlFor="ssr-replacement">
Replace template
<T>Replace template</T>
</label>
<textarea
id="ssr-replacement"
@@ -224,8 +230,8 @@ function StructuralDialog({ replace, onClose }: { replace: boolean; onClose: ()
</>
)}
<div className={styles.hint}>
Placeholders: <code>$name$</code> or <code>$NAME</code> match one node, <code>$$$NAME</code> any number of
nodes (arguments, statements). A placeholder used twice must match equal code.
<T>Placeholders:</T> <code>$name$</code> or <code>$NAME</code> <T>match one node,</T> <code>$$$NAME</code>{" "}
<T>any number of nodes (arguments, statements). A placeholder used twice must match equal code.</T>
</div>
<ScopeFields name="ssr-scope" value={scope} onChange={setScope} />
</div>
+5 -3
Переглянути файл
@@ -2,7 +2,7 @@
import { Fragment, type ReactNode } from "react";
import { create } from "zustand";
import { isTauri } from "@/platform/ipc";
import { Button, Input } from "@/ui";
import { Button, Input, T } from "@/ui";
import { SCOPE_LABELS, currentFile, type ScopeChoice, type ScopeKind } from "./scope";
import styles from "./Analysis.module.css";
@@ -57,7 +57,9 @@ export function ScopeFields({
const file = currentFile();
return (
<fieldset className={styles.scope}>
<legend className={styles.fieldLabel}>Scope</legend>
<legend className={styles.fieldLabel}>
<T>Scope</T>
</legend>
{KINDS.map((kind) => (
<label key={kind} className={styles.radioRow}>
<input
@@ -81,7 +83,7 @@ export function ScopeFields({
<Button
onClick={() => void browseDirectory(value.directory).then((d) => d && onChange({ ...value, directory: d }))}
>
Browse…
<T>Browse…</T>
</Button>
</div>
)}
+15 -6
Переглянути файл
@@ -9,7 +9,7 @@ import { create } from "zustand";
import type { InvalidateCachesOptions } from "@/bindings";
import { registerActions } from "@/platform/actions";
import { call, commands, isTauri } from "@/platform/ipc";
import { Checkbox, Dialog } from "@/ui";
import { Checkbox, Dialog, T } from "@/ui";
import { notifications } from "@/workbench/contributions";
import styles from "./app.module.css";
@@ -30,7 +30,11 @@ export const DEFAULT_INVALIDATE_OPTIONS: Required<InvalidateCachesOptions> = {
/** Schedules the invalidation (or none, for Just Restart) and restarts. */
export async function invalidateAndRestart(options: InvalidateCachesOptions | null): Promise<void> {
if (!isTauri()) {
notifications().notify({ level: "info", title: "Restart is only available in the desktop app", key: "app.invalidateCaches" });
notifications().notify({
level: "info",
title: "Restart is only available in the desktop app",
key: "app.invalidateCaches",
});
return;
}
try {
@@ -78,10 +82,15 @@ export function InvalidateCachesDialog({ onClose = close }: { onClose?: () => vo
>
<div className={styles.invalidateBody}>
<p className={styles.invalidateText}>
The caches will be invalidated and rebuilt on the next startup: the symbol index of every project and the
syntax caches.
<T>
{
"The caches will be invalidated and rebuilt on the next startup: the symbol index of every project and the syntax caches."
}
</T>
</p>
<div className={styles.invalidateHeading}>Optional:</div>
<div className={styles.invalidateHeading}>
<T>Optional:</T>
</div>
<Checkbox
label="Clear file system cache and Local History"
checked={options.localHistory}
@@ -99,7 +108,7 @@ export function InvalidateCachesDialog({ onClose = close }: { onClose?: () => vo
/>
{options.localHistory && (
<p className={styles.invalidateWarning} role="note">
Local History of all projects will be deleted.
<T>Local History of all projects will be deleted.</T>
</p>
)}
</div>
+2 -2
Переглянути файл
@@ -1,6 +1,6 @@
import { describe, expect, it, vi } from "vitest";
import { confirmExitEnabled, decideClose, type CloseDeps, type CloseInput } from "../closeGuard";
import type { PromptRequest, PromptResult } from "../prompt";
import type { MessageRequest as PromptRequest, MessageResult as PromptResult } from "@/workbench/messages";
function deps(answers: PromptResult[]) {
const asked: PromptRequest[] = [];
@@ -28,7 +28,7 @@ describe("decideClose", () => {
it("confirms exit for the last window when enabled", async () => {
const { d, asked } = deps([{ button: "exit", checked: false }]);
await expect(decideClose({ ...base, confirmExit: true }, d)).resolves.toBe(true);
expect(asked[0]?.title).toBe("Exit OpenIDEA?");
expect(asked[0]?.title).toBe("Confirm Exit");
expect(d.disableConfirmExit).not.toHaveBeenCalled();
});
+1 -1
Переглянути файл
@@ -5,7 +5,7 @@ import type { Action } from "@/platform/actions";
import { keymapReference, KeymapReferenceOverlay, showKeymapReference } from "../KeymapReference";
import { windowTitle } from "../title";
import { aboutRows } from "../AboutDialog";
import { ask, PromptOverlay } from "../prompt";
import { ask, MessagesHost as PromptOverlay } from "@/workbench/messages";
import { usePlatform } from "@/platform/platformInfo";
describe("window title", () => {
-7
Переглянути файл
@@ -1,10 +1,3 @@
.promptBody {
margin: 0;
padding: 14px 16px;
color: var(--fg);
line-height: 1.5;
}
/* About (JetBrains-style: logo left, product facts as plain lines) */
.about {
display: flex;
+2 -1
Переглянути файл
@@ -11,7 +11,7 @@ import { commands, isTauri, onIdeEvent, type Settings } from "@/platform/ipc";
import { t } from "@/platform/i18n";
import { provideLeaveProjectGuard, useProject } from "@/platform/project";
import { maybeEditorService, notifications } from "@/workbench/contributions";
import { ask, type Ask } from "./prompt";
import { ask, type Ask } from "@/workbench/messages";
/** Document ids the backend reports dirty in this window. */
const dirtyDocs = new Set<number>();
@@ -59,6 +59,7 @@ export async function decideClose(input: CloseInput, deps: CloseDeps): Promise<b
{ id: "discard", label: t("app.unsaved.discard") },
{ id: "save", label: t("app.unsaved.save"), primary: true },
],
icon: "warning",
});
if (r.button === "cancel") return false;
if (r.button === "save") {
+3 -2
Переглянути файл
@@ -11,17 +11,18 @@ import { buildInfo } from "./host";
import { KeymapReferenceOverlay } from "./KeymapReference";
import { installLocaleSync, registerLocalizedActions } from "./locale";
import { installMenuBridge } from "./menuBridge";
import { PromptOverlay } from "./prompt";
import { installWindowTitle } from "./title";
import { installLaunchHandling, windowActions } from "./windows";
/** The UI locale of a secondary (Settings) window. */
export const activateLocale = installLocaleSync;
export function activate(): () => void {
const disposers = [
installLocaleSync(),
registerLocalizedActions(() => [...appActions(), ...windowActions()]),
registerOverlay({ id: "app.about", component: AboutOverlay }),
registerOverlay({ id: "app.keymapReference", component: KeymapReferenceOverlay }),
registerOverlay({ id: "app.prompt", component: PromptOverlay }),
registerOverlay({ id: "app.invalidateCaches", component: InvalidateCachesOverlay }),
registerInvalidateCachesActions(),
installMenuBridge(),
-83
Переглянути файл
@@ -1,83 +0,0 @@
/** Promise-based modal prompts (exit confirmation, unsaved changes). */
import { useState } from "react";
import { create } from "zustand";
import { useT } from "@/platform/i18n";
import { Checkbox, Dialog } from "@/ui";
import styles from "./app.module.css";
export interface PromptButton {
id: string;
label: string;
primary?: boolean;
}
export interface PromptRequest {
title: string;
body: string;
/** Declaration order (IDEA `createActions`); the dialog orders them per platform. A Cancel button (id `cancel`) is added unless present. */
buttons: PromptButton[];
checkbox?: string;
}
export interface PromptResult {
button: string;
checked: boolean;
}
export type Ask = (request: PromptRequest) => Promise<PromptResult>;
interface PromptState {
current: (PromptRequest & { resolve: (r: PromptResult) => void }) | null;
}
export const usePrompt = create<PromptState>(() => ({ current: null }));
/** Shows a prompt; a prompt already open is cancelled first. */
export const ask: Ask = (request) => {
usePrompt.getState().current?.resolve({ button: "cancel", checked: false });
return new Promise((resolve) => {
usePrompt.setState({
current: {
...request,
resolve: (r) => {
usePrompt.setState({ current: null });
resolve(r);
},
},
});
});
};
export function PromptOverlay() {
const current = usePrompt((s) => s.current);
if (!current) return null;
// Keyed so the checkbox state resets per prompt.
return <PromptDialog key={current.title + current.body} request={current} />;
}
function PromptDialog({ request }: { request: NonNullable<PromptState["current"]> }) {
const t = useT();
const [checked, setChecked] = useState(false);
const done = (button: string) => request.resolve({ button, checked });
return (
<Dialog
open
onClose={() => done("cancel")}
title={request.title}
width={420}
footerStart={
request.checkbox && <Checkbox checked={checked} onChange={setChecked} label={request.checkbox} />
}
buttons={[
...request.buttons.map((b) => ({
label: b.label,
role: b.primary ? ("default" as const) : b.id === "cancel" ? ("cancel" as const) : ("extra" as const),
onClick: () => done(b.id),
})),
...(request.buttons.some((b) => b.id === "cancel") ? [] : [{ label: t("common.cancel"), role: "cancel" as const }]),
]}
>
<p className={styles.promptBody}>{request.body}</p>
</Dialog>
);
}
+11 -6
Переглянути файл
@@ -6,9 +6,10 @@
import type { Action } from "@/platform/actions";
import { t } from "@/platform/i18n";
import { call, commands, isTauri } from "@/platform/ipc";
import { basename, confirmLeaveProject, openProject, useProject } from "@/platform/project";
import { basename, confirmLeaveProject, openProject, provideStartupLaunch, useProject } from "@/platform/project";
import { holdSplash } from "@/platform/splash";
import { notifications } from "@/workbench/contributions";
import { ask } from "./prompt";
import { ask } from "@/workbench/messages";
export const LAUNCH_EVENT = "openidea://launch";
@@ -75,8 +76,8 @@ export async function openProjectWithPolicy(path: string): Promise<void> {
title: t("app.window.askTitle"),
body: t("app.window.askBody", { name: basename(path) }),
buttons: [
{ id: "same", label: t("app.window.askThis") },
{ id: "new", label: t("app.window.askNew"), primary: true },
{ id: "new", label: t("app.window.askNew") },
{ id: "same", label: t("app.window.askThis"), primary: true },
{ id: "cancel", label: t("common.cancel") },
],
checkbox: t("app.window.askRemember"),
@@ -85,7 +86,9 @@ export async function openProjectWithPolicy(path: string): Promise<void> {
mode = r.button;
if (r.checked) {
try {
useProject.setState({ settings: await call(commands.settingsSet("global", "general.openProjectIn", JSON.stringify(mode))) });
useProject.setState({
settings: await call(commands.settingsSet("global", "general.openProjectIn", JSON.stringify(mode))),
});
} catch {
/* the choice still applies to this open */
}
@@ -195,7 +198,9 @@ export function installLaunchHandling(): () => void {
if (!isTauri()) return () => {};
let disposed = false;
let unlisten: (() => void) | undefined;
void consumeLaunch();
const launch = consumeLaunch();
provideStartupLaunch(launch);
holdSplash(launch);
void import("@tauri-apps/api/webviewWindow").then(async ({ getCurrentWebviewWindow }) => {
const off = await getCurrentWebviewWindow().listen(LAUNCH_EVENT, () => void consumeLaunch());
if (disposed) off();
Loaded 100 of 295 files, more files were not shown because too many files have changed in this diff. Show more