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

...
Автор SHA1 Повідомлення Дата
l0ng-ai 1982f22005 fix(search): start Find in Files from the selection in its preview
Find in Files and Search Everywhere took the selection only from the active
editor tab, so text selected in the Find in Files preview (or another
focused editor, such as a diff pane) was ignored when the action ran again.
The focused editor's selection now comes first, then the active editor's.

Fixes #6992
2026-11-30 20:02:17 +08:00
Muuтаmuutot f47a83828c feat(structure): temporarily enable filters to find matches (#6934)
With Narrow down on typing on, a File Structure query that matches nothing now turns on the unchecked filters (Show fields, Show non-public, Show inherited members) one at a time until a match appears. Filters enabled this way are restored as the query gets shorter and when the popup closes, and are never saved; a checkbox the user changes by hand keeps its new state, and the cascade stops right after a backspace restores a filter.

Co-authored-by: muutot <[email protected]>
2026-11-30 19:58:05 +08:00
薛纪克таxuejike 4d5ee2d01c feat(agents): drag and delete the whole task list selection (#6933)
In the Agents task list, dragging a row of a multi-selection moves every selected task (into a group, Pinned, a status group, or before or after a task, keeping their order), and Delete deletes the selection while the list has focus. Tree collapsed the selection to the pressed row on mouse down, before a drag could start; a press on a selected row now narrows the selection only on a release without movement. agents.deleteTasks gets a list-focus key binding like agents.archiveTasks, and a click or arrow key opens the session without taking focus from the list; Enter and double-click still focus it.

Closes #6932

Co-authored-by: xuejike <[email protected]>
2026-11-30 19:56:24 +08:00
l0ng-ai 2ecb44098a fix(debugger): drop lldb-dap pseudo paths on Windows too (#7030)
A referenced source's pseudo path such as /usr/lib/swift/libswiftCore.dylib`swift_willThrow was kept on Windows, where a path with a root but no drive is not absolute, so frames_drop_pseudo_paths_of_referenced_sources failed on Rust (windows-latest) since #6961. A rooted path now counts.
2026-11-30 19:48:37 +08:00
Mollo-i b1039bc175 feat(search): select Search Everywhere results in the Project view (#6955)
File, symbol and text results in Search Everywhere get Select in Project View, in the Alt+Enter menu and in a new right-click menu on the row: it closes the popup and selects the result in the Project tool window. This helps with files that open in another application, such as a .doc, where choosing the result leaves no trace of where the file lives. The item is offered only for paths inside the project. One item list now feeds both menus, and Open to the Side is disabled for folders.

Co-authored-by: Greenker <[email protected]>
2026-11-30 19:43:10 +08:00
薛纪克таxuejike 182c7c1dbb feat(editor): double-click the empty tab strip to maximize the editor (#6969)
A double click on the empty part of an editor tab strip (not on a tab, a button or trailing content) now maximizes the editor by hiding all tool windows, the same as a double click on a regular tab; doing it again restores them. Tabs gets an onBlankDoubleClick callback that fires only for the strip itself or its scroller.

Closes #6968

Co-authored-by: xuejike <[email protected]>
2026-11-30 19:42:00 +08:00
l0ng-ai c8dc613485 fix(projects): offer New Tab when opening a remote project or from a remote window (#7017)
The Open Project prompt gated Attach and New Tab on one flag that required a local project in a local window, so opening an SSH/WSL project, or any project from a remote window, offered only New Window and This Window, and "Open project in: tab" fell back to a new window. Attach still needs a local project in a local window, but a project tab is a window of its own joined to this window's group, so it now applies whenever this window has a project: a remote project opens in a new window that joins the group.

Fixes #6923
2026-11-30 18:36:46 +08:00
audichuang 88a6bbca14 perf(vcs): run Git outside the log index lock so commit details and one-commit queries do not wait for a history walk (#7006)
history::log held the log index lock for its whole run, so every Git subprocess it started (file history, path selection, range ids, rev-list, the --grep text filter) ran under the lock, and commit details plus the one-commit queries behind inline blame waited for the whole walk. The lock is now taken per phase: Git runs unlocked and only in-memory work holds the guard. update_head_reachable runs under the guard that builds the rows, and the shared nodes are used only when they were built for the query's shallow set, rebuilt otherwise, so a query stays on one snapshot while others run in between.

Co-authored-by: audichuang <[email protected]>
2026-11-30 18:32:37 +08:00
Ivan b9e555300f fix(macos): defer moving a full-screen tab out of its group until the app is active (#6997)
Close Project on a tab of a native full-screen group moves the tab into a window, and so a full-screen Space, of its own. While the app is inactive, AppKit's enter-full-screen transition for that Space crashes in SLSWindowServerClientSpaceAddWindowsAndRemoveFromSpaces as soon as the web view draws its next frame, taking every project window with it. Detaching such a tab is now deferred: the tab stays in its group (showing Welcome) and moves to its own Space when the app is next activated. Foreground closes and windowed groups detach immediately as before.

Fixes #6937

Co-authored-by: Pecnikas <[email protected]>
2026-11-30 18:30:57 +08:00
l0ng-ai 7ff223001b fix(fonts): keep Latin text monospaced when the chosen font isn't installed (#7013)
With a fallback font set and a primary family that isn't installed, every glyph came from the fallback. A CJK fallback such as PingFang SC has proportional Latin letters, and the terminal sized its cells for the widest of them, so text came out spread apart. Once the native font catalog shows the family is missing, the bundled JetBrains Mono now stands in for it ahead of the fallback, which still covers the glyphs it lacks. Applies to every monospace stack built from the editor or terminal font settings.

Fixes #6974
2026-11-30 18:25:17 +08:00
l0ng-ai cc9279a6d6 fix(editor): indent Slint element blocks by their braces (#7012)
Slint borrows the C mode for highlighting until slint-lsp's semantic tokens arrive, and Enter used that mode's statement indentation: after a child element's closing brace the next line went back to column 0, and nested blocks below it opened one level short. Slint now uses the brace-based fallback indentation even though a highlighting mode is loaded. No other language with a borrowed mode has this mismatch.

Fixes #6976
2026-11-30 18:22:26 +08:00
l0ng-ai 1cfbb24b31 fix(project-tree): add Select Opened File as a Project View action for the keymap (#7011)
The keymap listed "Select Opened File" only as the Database view action, so a shortcut assigned to it revealed the file in the Database view and did nothing in a project without data sources. Like IDEA's SelectOpenedFileInProjectView, the Project view now has its own Select Opened File action (the toolbar button runs it), and imported IDEA keymaps map SelectOpenedFileInProjectView and SelectInProjectView.

Fixes #6978
2026-11-30 18:18:33 +08:00
l0ng-ai a8a0cdb315 fix(plugins): load precompiled plugin components in the signed macOS app (#7010)
compile_cached loaded the cached .cwasm with Component::deserialize_file, which maps the file and makes its pages executable; the hardened runtime of the signed app refuses that, so every activation discarded the cache and compiled the plugin again. The file is now read into memory and deserialized from the bytes. A new test checks the cache is hit; signed with the app entitlements it fails with the old code.

Refs #6954
2026-11-30 18:16:20 +08:00
l0ng-ai 8ab776ada6 fix(keymap): import an Emacs-based IDEA keymap on top of $default, not macOS (#7008)
presetOf picked the macOS preset for any parent whose name contains "mac", including "Emacs", so a keymap derived from IDEA's Emacs keymap was imported as based on macOS. The match is now on the word (Mac OS X, macOS), and Emacs and its copies map to the $default preset they inherit in IDEA.

Refs #6896
2026-11-30 18:14:01 +08:00
LU XIANGRUIтаwildcatDownstairs 88b463d888 fix(debugger): let a tsx program behind a remote root run under Attach to Node.js (#6926)
On a loopback address js-debug makes the program require its child-process bootloader by a local path; behind a remote root (published container port, SSH tunnel) that path is missing, tsx's esbuild worker exits and the program waits for it forever. Attach to Node.js with a remote root, and Node.js debugging on SSH/Docker/Compose run targets, now pass autoAttachChildProcesses: false.

Closes #6925

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-30 18:11:42 +08:00
LU XIANGRUIтаwildcatDownstairs ac88059d0f fix(plugins): index the first 20,000 files of a large project instead of none (#6958)
Plugin navigation discovery refused the whole project above 20,000 matching files, counted out-of-scope and git-ignored files toward the cap, and showed the raw error text half translated. Discovery now keeps the first 20,000 in-scope, non-ignored files, reports total/truncated, and shows one warning naming the project and the counts.

Fixes #6940

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-30 18:11:27 +08:00
Waiting-Night a09c9aa9ad fix(java): navigate inherited method references to their declarations (#6953)
JDT's selection-based definition can answer the functional interface method (Function.apply) for a method reference whose method is inherited. Go to Definition on a Java method reference now asks the app-owned JDT command openidea.java.methodReferenceDefinition (java-usages 1.20.1) for the AST method binding; Lombok accessors without a source range fall back to their field or declaring type. The bundled jar is reproducible from source (SHA-256 a111a935...); tests/method-reference.py checks the command against a real JDT LS.

Co-authored-by: wangyuewen-china <[email protected]>
2026-11-30 18:06:54 +08:00
LU XIANGRUIтаwildcatDownstairs 7fef1e10a8 fix(ai-completion): say why no suggestions appear and let the model be chosen (#6936)
The plugin's optional net:localhost permission is not ticked by default, and a missing Ollama model answers 404; both only reached the IDE log. Failed requests now show one warning that says why and what to do, and a new AI Completion: Set Model command (Set Endpoint URL also asks for its value from the palette). The host answers an empty list instead of "no server supports inline completion" when a plugin offers ghost text, so the editor keeps asking while typing.

Fixes #6930

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-30 18:03:40 +08:00
l0ng-ai 1748c98ac8 test(agents): type the store import of the long agent form e2e (#7004)
The e2e from #7003 imported the store by a literal /src path, which pnpm typecheck rejects (TS2307); it now imports through a variable typed as the store module.
2026-11-30 17:59:41 +08:00
l0ng-ai 399ae25ab6 fix(agents): keep a long agent form scrollable above the composer (#7003)
An agent form (ACP elicitation, used by opencode for its questions) had no height limit, so a form with several fields pushed its last choices, its buttons and the composer out of view with nothing to scroll. FormCard now uses the pinned question card layout (at most half the window, scrolling within), and the pinned card shrinks when the session is shorter so the composer stays in view.

Fixes #6945
2026-11-30 17:58:47 +08:00
audichuang f28dd8125b fix(deps): update yanked async-executor 1.14.0 to 1.14.1 (#6971)
crates.io yanked async-executor 1.14.0 for a use-after-free when a Waker fires during Executor::drop (smol-rs/async-executor#164). Lock-only update to 1.14.1.

Co-authored-by: audichuang <[email protected]>
2026-11-30 17:51:51 +08:00
arookieofcтаarookieofc d5f7e0a99b fix(maven): delegate launch classpath to Maven without jdtls (#6984)
With delegateBuild on a Maven module, launches without jdtls (java-analyzer) used the language server classpath, which ignores child POM exclusions. They now merge the classpath Maven resolves, as the jdtls path does, and fall back to the server classpath when the probe fails.

Fixes #5586

Co-authored-by: arookieofc <[email protected]>
2026-11-30 17:50:57 +08:00
audichuang a66c9e6d05 fix(vcs): retry git status without rename detection when a partial clone cannot fetch a blob (#6987)
In a blobless partial clone rename detection needs a staged blob it cannot fetch (Restricted Mode sets GIT_NO_LAZY_FETCH, or the promisor is unreachable) and git status fails. Status retries once with --no-renames when git reports the promisor remote.

Co-authored-by: audichuang <[email protected]>
2026-11-30 17:50:44 +08:00
audichuang 59bcf7eac5 fix(refactor): keep external changes when a file move's reference edits are rejected (#6990)
FileMoves::perform restored its pre-edit snapshots when the reference edits were rejected, overwriting a change another program wrote after the snapshot. apply_edit is transactional and leaves nothing behind on error, so a rejected edit is now returned without a restore; a failed move still rolls back the applied edits.

Co-authored-by: audichuang <[email protected]>
2026-11-30 17:50:29 +08:00
LU XIANGRUIтаwildcatDownstairs fe21c67537 fix(debugger): do not open lldb-dap's disassembly pseudo paths as files (#6961)
lldb-dap reports frames without debug info with a sourceReference and a pseudo path such as libswiftCore.dylib`swift_willThrow, which opened as a missing file. An absolute path that does not exist on a referenced source is dropped, so the stop selects the first frame with source.

Closes #6960

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-30 17:50:10 +08:00
audichuang c085f52b59 fix(editor): paste an image from the Markdown editor's context menu without WebKit's Paste callout (#6994)
On macOS the context-menu Paste in a Markdown editor called execCommand(paste), which shows the WebKit Paste callout. Images and copied image files are read through the backend instead; text takes the native path.

Co-authored-by: audichuang <[email protected]>
2026-11-30 17:43:14 +08:00
Bin 0104ed63c1 fix(project-tree): open external files on double-click only (#6993)
Single-click in the project tree opened files associated with an external application. Those now open on double-click only.

Co-authored-by: ffgenius <[email protected]>
2026-11-30 17:42:57 +08:00
Chris-young42таChris-young42 a441b2a906 fix(java): remove extra spaces from annotation completions (#6989)
JDT LS appends a space to annotation completions; it is dropped when nothing follows that needs a separator, so no trailing whitespace after @Override or space before the parenthesis.

Co-authored-by: Chris-young42 <[email protected]>
2026-11-30 17:42:42 +08:00
audichuang c4f7fec86c fix(build): keep output the channel delivers after the build result (#6988)
Tauri delivers channel messages over 8 KiB through an async fetch and holds later ones back, so output can arrive after the command result. Output and step events of the latest build are still applied after it finished, until another build takes the window.

Co-authored-by: audichuang <[email protected]>
2026-11-30 17:42:28 +08:00
audichuang 37a8aae018 fix(vcs): keep focused and unsaved all-in-one diff blocks mounted while the view has no height (#6983)
With no height (a maximized tool window over the diff) the virtualizer rendered no range and unmounted the focused and unsaved blocks, saving an unsaved index edit. The view now reports at least 1 px and keeps the last measured block sizes while hidden.

Co-authored-by: audichuang <[email protected]>
2026-11-30 17:42:16 +08:00
LU XIANGRUIтаwildcatDownstairs acc48a4816 fix(run): clear a selected test's output with Clear All (#6982)
A selected test node shows the output captured on that node, which Clear All did not touch. Clear All now drops captured test output as well; statuses and the tree stay.

Closes #6975

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-30 17:42:00 +08:00
audichuang 8301326289 fix(ui): remeasure the custom scrollbar when its content grows without the scroller resizing (#6973)
The custom scrollbar observed only the scroller, whose size does not change when its content grows (a Markdown preview reflowing after a width change). It now also observes the scroller children, re-observing them when they are replaced.

Co-authored-by: audichuang <[email protected]>
2026-11-30 17:41:43 +08:00
sonnartliao 4c71299745 fix(editor): resolve C declarations without include metadata (#6959)
Without a compilation database clangd leaves nested includes unresolved or answers with the call site itself. For C-family files an empty or self-only answer falls back to syntax and the project index (including identifiers in macro bodies), Go to Implementation from a header finds the source definition, and member access is never guessed by bare name.

Co-authored-by: sonnartliao <[email protected]>
2026-11-30 17:41:27 +08:00
Jimmy Song 08249ca5fd fix(viewers): reload preview images when files change on disk (#6952)
Preview image data URLs were cached by path forever. The cache now drops entries on fsChanged and open Markdown and reStructuredText previews reload the affected images.

Co-authored-by: zhiai007 <[email protected]>
2026-11-30 17:41:09 +08:00
Waiting-Night edd6746439 fix(editor): stop type hierarchy searches from library gutter markers (#6951)
Library gutter markers asked jdtls for inheritors of every visible class, which on a JDK interface ran a full type hierarchy search and timed out. Library sources keep super-method markers but ask for no inheritors; Go to Implementation still answers.

Co-authored-by: wangyuewen-china <[email protected]>
2026-11-30 17:40:54 +08:00
LU XIANGRUIтаwildcatDownstairs 695424beb2 fix(editor): reopen restored library source tabs read-only (#6950)
The library-source mark lived only in memory, so a tab restored after a reload opened the same file editable. The editor session now saves the mark and restores it before the documents open.

Closes #6947

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-30 17:40:41 +08:00
LU XIANGRUIтаwildcatDownstairs 9943d71d02 fix(editor): show no diagnostics in library sources (#6946)
Language servers publish errors for files they generate or read outside the project (sourcekit-lsp parse errors in its .swiftinterface). Library sources open read-only, so their diagnostics are dropped from the editor and the Problems view.

Closes #6943

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-30 17:40:25 +08:00
l0ng-ai e03c5507f7 ci: publish a nightly prerelease of main every day (#6962)
nightly.yml builds main at 18:00 UTC, when it has moved since the last
nightly, as v<next patch>-nightly.<date>: a tag on a commit over main that
only sets the version (scripts/nightly-prepare.ts), built and published by
release.yml, which can now be called with `nightly: true` (notes from the
previous nightly; no official plugins, CNB mirror or Homebrew cask).

Nightly apps update from the rolling `nightly` release, which holds the
newest nightly's latest.json, and skip the CNB mirror, which carries only
stable releases. Stable apps keep reading releases/latest, never a
prerelease. The MSI gets a numeric version (last release + run number),
and the newest 14 nightlies are kept.
2026-11-30 15:55:50 +08:00
125 змінених файлів з 4020 додано та 295 видалено

No files matched your search

+104
Переглянути файл
@@ -0,0 +1,104 @@
name: Nightly
# Builds main every night, when it has moved since the last nightly, into a prerelease
# v<next patch>-nightly.<date> (scripts/nightly-prepare.ts: the tag points at a commit on top of
# main that only sets the version). Nightly apps update from the rolling `nightly` release, which
# holds the newest nightly's latest.json; stable apps read releases/latest, which is never a
# prerelease, so they never see a nightly. The newest 14 nightlies are kept.
on:
schedule:
- cron: "0 18 * * *" # 02:00 Beijing
workflow_dispatch:
inputs:
force:
description: "Build even when main has not changed since the last nightly"
type: boolean
default: false
permissions:
contents: read
concurrency:
group: nightly
jobs:
prepare:
if: github.repository == 'l0ng-ai/openidea'
permissions:
contents: write
runs-on: ubuntu-latest
outputs:
tag: ${{ steps.tag.outputs.tag }}
steps:
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
with: { ref: main, fetch-depth: 0 }
- id: changed
env:
FORCE: ${{ inputs.force == true }}
run: |
last="$(git tag --list 'v*-nightly.*' --sort=-creatordate | head -1)"
if [ "$FORCE" != true ] && [ -n "$last" ] && [ "$(git rev-parse "$last^")" = "$(git rev-parse HEAD)" ]; then
echo "::notice::main has not changed since $last"
echo "skip=true" >> "$GITHUB_OUTPUT"
fi
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
if: steps.changed.outputs.skip != 'true'
with: { node-version: 22 }
- name: Version commit and tag
id: tag
if: steps.changed.outputs.skip != 'true'
env:
BUILD: ${{ github.run_number }}
run: |
version="$(node scripts/nightly-prepare.ts --date "$(date -u +%Y%m%d)" --build "$BUILD" | tail -1)"
git config user.name "github-actions[bot]"
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
git add -A
git commit -q -m "chore: v$version"
git tag "v$version"
# Pushed with GITHUB_TOKEN, the tag does not start release.yml: the job below calls it.
git push origin "refs/tags/v$version"
echo "tag=v$version" >> "$GITHUB_OUTPUT"
release:
needs: prepare
if: needs.prepare.outputs.tag != ''
permissions:
contents: write
uses: ./.github/workflows/release.yml
with:
tag: ${{ needs.prepare.outputs.tag }}
nightly: true
secrets: inherit
# Points the nightly channel at the new nightly and drops the old ones.
channel:
needs: [prepare, release]
permissions:
contents: write
runs-on: ubuntu-latest
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GH_REPO: ${{ github.repository }}
TAG: ${{ needs.prepare.outputs.tag }}
steps:
- name: Nightly manifest
run: |
if ! gh release download "$TAG" -p latest.json -D "$RUNNER_TEMP/manifest"; then
echo "::warning::$TAG has no latest.json (unsigned build): the nightly channel stays where it was"
exit 0
fi
notes="The update channel of the [nightly builds](https://github.com/$GH_REPO/releases?q=nightly&expanded=true): its latest.json is the newest nightly's, [$TAG](https://github.com/$GH_REPO/releases/tag/$TAG)."
if gh release view nightly >/dev/null 2>&1; then
gh release edit nightly --notes "$notes"
else
gh release create nightly --prerelease --target main --title "OpenIDEA Nightly" --notes "$notes"
fi
gh release upload nightly "$RUNNER_TEMP/manifest/latest.json" --clobber
- name: Drop old nightlies
run: |
gh release list --limit 200 --json tagName,createdAt \
--jq '[.[] | select(.tagName | test("^v.*-nightly\\."))] | sort_by(.createdAt) | reverse | .[14:][] | .tagName' |
while read -r old; do
gh release delete "$old" --cleanup-tag --yes
done
+27 -8
Переглянути файл
@@ -7,17 +7,23 @@ on:
tag:
description: "Tag to release (e.g. v0.1.0); must already exist"
required: true
# nightly.yml: a nightly is a prerelease whose notes start at the previous nightly, without the
# official plugins, the CNB mirror or the Homebrew cask.
workflow_call:
inputs:
tag: { type: string, required: true }
nightly: { type: boolean, default: false }
permissions:
contents: read
concurrency:
group: release-${{ github.event.inputs.tag || github.ref_name }}
group: release-${{ inputs.tag || github.ref_name }}
env:
CARGO_TERM_COLOR: always
CARGO_INCREMENTAL: 0
TAG: ${{ github.event.inputs.tag || github.ref_name }}
TAG: ${{ inputs.tag || github.ref_name }}
COMMUNITY_PLUGINS_INDEX: https://github.com/l0ng-ai/openidea-plugins/releases/download/index/index.json
# The jobs that read a signing key or token, here and in the workflows called below, run in
@@ -52,6 +58,8 @@ jobs:
fi
- id: release
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
env:
NIGHTLY: ${{ inputs.nightly == true }}
with:
script: |
const tag = process.env.TAG;
@@ -63,8 +71,13 @@ jobs:
core.setOutput("id", existing.id);
return;
}
// Prereleases are skipped: the notes span stable release to stable release.
const previous = releases.find((r) => !r.draft && !r.prerelease);
// Prereleases are skipped: the notes span stable release to stable release. A
// nightly's span from the newest published release, nightly or stable (not the
// rolling `nightly` release, which only holds the channel's manifest).
const nightly = process.env.NIGHTLY === "true";
const previous = releases.find(
(r) => !r.draft && r.tag_name !== "nightly" && (nightly || !r.prerelease),
);
const { data: notes } = await github.rest.repos.generateReleaseNotes({
owner, repo, tag_name: tag, previous_tag_name: previous?.tag_name,
});
@@ -80,7 +93,7 @@ jobs:
needs: create-release
uses: ./.github/workflows/release-build.yml
with:
tag: ${{ github.event.inputs.tag || github.ref_name }}
tag: ${{ inputs.tag || github.ref_name }}
release_id: ${{ needs.create-release.outputs.release_id }}
secrets: inherit
@@ -102,10 +115,14 @@ jobs:
runs-on: ubuntu-22.04
env:
SIGNING_KEY: ${{ secrets.PLUGIN_SIGNING_KEY }}
NIGHTLY: ${{ inputs.nightly == true }}
steps:
- id: key
run: |
if [ -z "$SIGNING_KEY" ]; then
if [ "$NIGHTLY" = true ]; then
echo "a nightly does not publish the official plugins"
echo "skip=true" >> "$GITHUB_OUTPUT"
elif [ -z "$SIGNING_KEY" ]; then
echo "::warning::PLUGIN_SIGNING_KEY is not set: the official plugins are not published"
echo "skip=true" >> "$GITHUB_OUTPUT"
fi
@@ -178,13 +195,15 @@ jobs:
# The China mirror the updater's CNB source reads; a failure here leaves the GitHub release as is.
cnb-mirror:
needs: publish
if: ${{ !inputs.nightly }}
uses: ./.github/workflows/cnb-mirror.yml
with: { tag: "${{ github.event.inputs.tag || github.ref_name }}" }
with: { tag: "${{ inputs.tag || github.ref_name }}" }
secrets: inherit
# The cask in l0ng-ai/homebrew-tap; skipped for prereleases and without HOMEBREW_TAP_DEPLOY_KEY.
homebrew:
needs: publish
if: ${{ !inputs.nightly }}
uses: ./.github/workflows/homebrew.yml
with: { tag: "${{ github.event.inputs.tag || github.ref_name }}" }
with: { tag: "${{ inputs.tag || github.ref_name }}" }
secrets: inherit
Створено
+2 -2
Переглянути файл
@@ -252,9 +252,9 @@ dependencies = [
[[package]]
name = "async-executor"
version = "1.14.0"
version = "1.14.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c96bf972d85afc50bf5ab8fe2d54d1586b4e0b46c97c50a0c9e71e2f7bcd812a"
checksum = "f426a31126c735126297bc5ea7a521263c9faff4f63ca415267ee625651c4f37"
dependencies = [
"async-task",
"concurrent-queue",
+15 -1
Переглянути файл
@@ -614,6 +614,16 @@ pub(crate) fn take_debug_server(arguments: &mut Value) -> IdeResult<Option<Debug
Ok(Some(DebugServer { host, port }))
}
/// A source served only through the `source` request whose `path` is no file, such as
/// lldb-dap's ``/usr/lib/swift/libswiftCore.dylib`swift_willThrow`` for a frame without
/// debug info. Opening it would show an error tab; without a path the stop selects the
/// first frame with source instead. Non-file paths (`jdt://`, `<node_internals>`) stay.
/// Rooted rather than absolute: on Windows a `/usr/…` path has a root but no drive.
fn is_pseudo_path(source: Option<&Value>, path: &str) -> bool {
let reference = source.and_then(|s| s.get("sourceReference")).and_then(Value::as_i64).unwrap_or(0);
reference > 0 && Path::new(path).has_root() && !Path::new(path).exists()
}
/// DAP stack frame → [`StackFrame`] (1-based → 0-based).
pub(crate) fn frame_from(f: &Value) -> StackFrame {
let source = f.get("source");
@@ -626,7 +636,11 @@ pub(crate) fn frame_from(f: &Value) -> StackFrame {
StackFrame {
id: f.get("id").and_then(Value::as_i64).unwrap_or_default(),
name: f.get("name").and_then(Value::as_str).unwrap_or_default().to_owned(),
path: source.and_then(|s| s.get("path")).and_then(Value::as_str).map(Into::into),
path: source
.and_then(|s| s.get("path"))
.and_then(Value::as_str)
.filter(|p| !is_pseudo_path(source, p))
.map(Into::into),
line: (f.get("line").and_then(Value::as_u64).unwrap_or(0) as u32).saturating_sub(1),
column: (f.get("column").and_then(Value::as_u64).unwrap_or(0) as u32).saturating_sub(1),
presentation_hint: hint,
+15
Переглянути файл
@@ -2164,6 +2164,21 @@ fn frames_keep_their_instruction_pointer() {
assert!(json.get("instructionPointerReference").is_none());
}
#[test]
fn frames_drop_pseudo_paths_of_referenced_sources() {
let frame = |path: &str, reference: i64| {
frame_from(&json!({"id": 1, "name": "f", "line": 1,
"source": {"path": path, "sourceReference": reference}}))
.path
};
let lldb = "/usr/lib/swift/libswiftCore.dylib`swift_willThrow";
assert_eq!(frame(lldb, 1), None, "lldb-dap disassembly");
assert_eq!(frame(lldb, 0).as_deref(), Some(Path::new(lldb)), "no reference: kept as sent");
let here = env!("CARGO_MANIFEST_DIR");
assert_eq!(frame(here, 3).as_deref(), Some(Path::new(here)), "an existing file");
assert!(frame("jdt://contents/rt.jar/java.lang/String.class", 2).is_some(), "not a file path");
}
#[tokio::test]
async fn smart_step_into_and_reset_frame() {
let h = harness(Script::default());
+118 -30
Переглянути файл
@@ -544,38 +544,24 @@ async fn resolve_launch_without_jdtls(
let cancel = cancel.clone();
tokio::task::spawn_blocking(move || {
let (root, cache, settings) = (&scope.root, &scope.cache, &scope.settings);
match from_server {
// The IDE's Java build gave the whole classpath; the server adds its JDK.
Some(server) if by_service => {
info.project_root = server.classpath.project_root;
info.java_home = server.jdk_home.map(Into::into);
}
None if by_service => {}
Some(server) => {
info.project_root = server.classpath.project_root;
info.module_paths = server.classpath.module_paths;
info.java_home = server.jdk_home.map(Into::into);
append_unique_class_paths(&mut class_paths, server.classpath.class_paths);
}
None => {
if !is_maven_module(root, &model, &module) {
return Err(IdeError::unavailable(
"Cannot resolve the classpath: the Java language server does not report it \
(java-analyzer/projectClasspath), and the module is not a Maven project",
));
}
let is_maven = is_maven_module(root, &model, &module);
let delegated_maven = !by_service && settings.languages.java.maven.delegate_build && is_maven;
apply_without_jdtls_classpath(
&mut class_paths,
&mut info,
from_server,
by_service,
is_maven,
delegated_maven,
|| {
let local_repo = ide_sdk::apply::maven_local_repository(root, settings);
let classpath = if aggregator && policy == BuildPolicy::NoBuild {
compile::module_classpath_without_build(root, &model, &module, test, cache, &cancel)?
if aggregator && policy == BuildPolicy::NoBuild {
compile::module_classpath_without_build(root, &model, &module, test, cache, &cancel)
} else {
compile::module_classpath(root, &model, &module, test, local_repo, cache, &cancel)?
};
append_unique_class_paths(
&mut class_paths,
std::env::split_paths(&classpath).map(|p| p.to_string_lossy().into_owned()),
);
}
}
compile::module_classpath(root, &model, &module, test, local_repo, cache, &cancel)
}
},
)?;
info.class_paths = class_paths;
apply_library_classpath(&mut info, root, &settings.project_structure.libraries, test);
finish_launch(&mut info, root, &module, settings, &model, &data_dir);
@@ -825,6 +811,59 @@ fn same_entry(a: &str, b: &str, windows: bool) -> bool {
a == b || entry_key(a, windows) == entry_key(b, windows)
}
/// Resolves the runtime/test classpath for a launch without jdtls (e.g. `java-analyzer` or
/// no Java language server). When `delegated_maven` is true (`delegateBuild = true` on a Maven
/// module), delegates classpath resolution to Maven itself (falling back to the language server's
/// classpath on error, matching the jdtls path) so child POM `<exclusions>` and Maven dependency
/// mediation are respected (#5586).
fn apply_without_jdtls_classpath(
class_paths: &mut Vec<String>,
info: &mut JavaLaunchInfo,
from_server: Option<ide_lsp::java_project::ServerClasspath>,
by_service: bool,
is_maven: bool,
delegated_maven: bool,
probe_maven: impl FnOnce() -> IdeResult<String>,
) -> IdeResult<()> {
match from_server {
// The IDE's Java build gave the whole classpath; the server adds its JDK.
Some(server) if by_service => {
info.project_root = server.classpath.project_root;
info.java_home = server.jdk_home.map(Into::into);
Ok(())
}
None if by_service => Ok(()),
Some(server) if delegated_maven => {
info.project_root = server.classpath.project_root;
info.module_paths = server.classpath.module_paths;
info.java_home = server.jdk_home.map(Into::into);
info.class_paths = server.classpath.class_paths;
merge_maven_launch_classpath(class_paths, info, probe_maven(), &[])
}
Some(server) => {
info.project_root = server.classpath.project_root;
info.module_paths = server.classpath.module_paths;
info.java_home = server.jdk_home.map(Into::into);
append_unique_class_paths(class_paths, server.classpath.class_paths);
Ok(())
}
None => {
if !is_maven {
return Err(IdeError::unavailable(
"Cannot resolve the classpath: the Java language server does not report it \
(java-analyzer/projectClasspath), and the module is not a Maven project",
));
}
let classpath = probe_maven()?;
append_unique_class_paths(
class_paths,
std::env::split_paths(&classpath).map(|p| p.to_string_lossy().into_owned()),
);
Ok(())
}
}
}
/// Merge the Maven launch classpath without turning a recoverable probe failure into a
/// failed launch. Cancellation still propagates; ordinary failures keep jdtls' classpath
/// and leave the reason in the run console. Maven lists the module's and its reactor
@@ -1259,6 +1298,55 @@ mod tests {
);
}
#[test]
fn delegated_maven_without_jdtls_prefers_maven_classpath_over_server_classpath() {
let server = ide_lsp::java_project::ServerClasspath {
classpath: ide_lsp::jdtls::JavaClasspath {
project_root: Some(PathBuf::from("/work/child").into()),
// Static server resolver kept an excluded parent transitive jar (#5586).
class_paths: vec![
"/work/child/target/classes".into(),
"/m2/log4j-slf4j-impl-2.12.1.jar".into(),
"/m2/logback-classic.jar".into(),
],
module_paths: vec![],
},
jdk_home: Some(PathBuf::from("/jdk8")),
};
let maven = std::env::join_paths(["/work/child/target/classes", "/m2/logback-classic.jar"])
.unwrap()
.to_string_lossy()
.into_owned();
let mut class_paths = vec!["/work/child/target/classes".to_owned()];
let mut info = JavaLaunchInfo::default();
apply_without_jdtls_classpath(&mut class_paths, &mut info, Some(server), false, true, true, || Ok(maven))
.unwrap();
assert_eq!(class_paths, ["/work/child/target/classes", "/m2/logback-classic.jar"]);
assert_eq!(info.project_root, Some(PathBuf::from("/work/child").into()));
assert_eq!(info.java_home, Some(PathBuf::from("/jdk8").into()));
assert!(info.hints.is_empty(), "{:?}", info.hints);
}
#[test]
fn delegated_maven_without_jdtls_falls_back_to_server_classpath_on_probe_error() {
let server = ide_lsp::java_project::ServerClasspath {
classpath: ide_lsp::jdtls::JavaClasspath {
project_root: Some(PathBuf::from("/work/child").into()),
class_paths: vec!["/m2/server-fallback.jar".into()],
module_paths: vec![],
},
jdk_home: None,
};
let mut class_paths = vec!["/work/child/target/classes".to_owned()];
let mut info = JavaLaunchInfo::default();
apply_without_jdtls_classpath(&mut class_paths, &mut info, Some(server), false, true, true, || {
Err(IdeError::internal("maven offline"))
})
.unwrap();
assert_eq!(class_paths, ["/work/child/target/classes", "/m2/server-fallback.jar"]);
assert!(info.hints[0].contains("maven offline"), "{:?}", info.hints);
}
#[test]
fn cancelled_maven_classpath_probe_propagates_without_fallback() {
let mut class_paths = vec!["snapshot.jar".to_owned()];
+32 -3
Переглянути файл
@@ -336,20 +336,36 @@ pub async fn lsp_inline_completion(
let plugin = match plugin_providers(host, window, doc, ProviderKind::InlineCompletion) {
Some((plugins, d)) if !matches!(&result, Ok(items) if !items.is_empty()) => {
let cancel = cancel.clone();
plugin_call(move || plugins.provide_inline_completion(&d, pos, &cancel)).await.flatten()
plugin_call(move || {
let offered = plugins.offers_inline_completion(&d.language);
(offered, plugins.provide_inline_completion(&d, pos, &cancel).map(|(_, s)| s))
})
.await
}
_ => None,
};
host.end_request(request);
inline_items(result, plugin)
}
/// The plugin's suggestion, else the servers'. When a plugin offers ghost text
/// for the document, "no server supports inline completion" is not returned:
/// the editor would stop asking while typing for 30 s, and a plugin that had
/// nothing this time (cancelled by the next keystroke) may have some next time.
fn inline_items(
servers: IdeResult<Vec<InlineCompletionItem>>,
plugin: Option<(bool, Option<ide_plugin::InlineSuggestion>)>,
) -> IdeResult<Vec<InlineCompletionItem>> {
match plugin {
Some((_, s)) => Ok(vec![InlineCompletionItem {
Some((_, Some(s))) => Ok(vec![InlineCompletionItem {
insert_text: s.insert_text,
range: s.replace,
filter_text: None,
command: None,
server: PLUGIN_SERVER,
}]),
None => result,
Some((true, None)) => provider_server(servers),
_ => servers,
}
}
@@ -2429,6 +2445,19 @@ pub fn plugin_formatters() -> IdeResult<Vec<crate::plugins::language_features::F
#[cfg(test)]
mod tests {
#[test]
fn a_plugin_offering_ghost_text_keeps_the_editor_asking() {
use super::*;
let none = || Err(ide_core::IdeError::unavailable("No server supports inline completion"));
// Nothing this time (cancelled by the next keystroke): an empty answer, not "unavailable".
assert!(inline_items(none(), Some((true, None))).unwrap().is_empty());
// No plugin for this language: the servers' answer as it is.
assert!(inline_items(none(), Some((false, None))).is_err());
assert!(inline_items(none(), None).is_err());
let s = ide_plugin::InlineSuggestion { insert_text: "a + b".into(), replace: None };
assert_eq!(inline_items(none(), Some((true, Some(s)))).unwrap()[0].insert_text, "a + b");
}
#[test]
fn a_completion_word_is_its_line_and_what_precedes_it() {
use super::*;
+44 -6
Переглянути файл
@@ -9,6 +9,22 @@ pub struct NavigationFiles {
pub paths: Vec<ide_core::IpcPath>,
pub indexing: bool,
pub extensions: Vec<String>,
/// In-scope files matching `extensions`; `paths` holds the first
/// `MAX_NAVIGATION_FILES` of them.
pub total: u32,
pub truncated: bool,
}
/// Discovery offers at most this many files; larger projects get navigation
/// on the first ones instead of none.
const MAX_NAVIGATION_FILES: usize = 20_000;
/// The first `limit` files `in_scope` accepts, and how many it accepts in all.
fn first_in_scope(files: Vec<PathBuf>, in_scope: impl Fn(&PathBuf) -> bool, limit: usize) -> (Vec<PathBuf>, usize) {
let mut files: Vec<_> = files.into_iter().filter(in_scope).collect();
let total = files.len();
files.truncate(limit);
(files, total)
}
#[command(trust = trusted)]
@@ -24,19 +40,25 @@ pub async fn plugin_navigation_files(
blocking(move || {
let extensions = plugins.navigation_extensions(&project.root);
if extensions.is_empty() {
return Ok(NavigationFiles { paths: vec![], indexing: false, extensions: vec![] });
return Ok(NavigationFiles {
paths: vec![],
indexing: false,
extensions: vec![],
total: 0,
truncated: false,
});
}
let indexing = project.index.status().indexing;
let files = project.index.files_with_extensions(&extensions, 20_001);
if files.len() > 20_000 {
return Err(IdeError::unavailable("plugin navigation supports up to 20,000 matching files"));
}
let files = project.index.files_with_extensions(&extensions, usize::MAX);
// A project window group's members are project scope: their files are
// in the group's index (the group root holds none of them).
let members = crate::project::workspace_member_roots(&project.root);
let in_scope = |p: &PathBuf| p.starts_with(&project.root) || members.iter().any(|m| p.starts_with(m));
let (files, total) = first_in_scope(files, in_scope, MAX_NAVIGATION_FILES);
Ok(NavigationFiles {
paths: files.into_iter().filter(in_scope).map(Into::into).collect(),
truncated: total > files.len(),
total: u32::try_from(total).unwrap_or(u32::MAX),
paths: files.into_iter().map(Into::into).collect(),
indexing,
extensions,
})
@@ -210,3 +232,19 @@ ide_command::domain!(
plugin_navigation_invalidate,
plugin_navigation_markers,
);
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn discovery_keeps_the_first_in_scope_files_and_counts_them_all() {
let files: Vec<PathBuf> = (0..7).map(|i| PathBuf::from(format!("/p/{}/f{i}.xml", i % 2))).collect();
let (kept, total) = first_in_scope(files, |p| p.starts_with("/p/0"), 3);
// Out-of-scope files neither take a slot nor count toward the total.
assert_eq!(total, 4);
assert_eq!(kept, ["/p/0/f0.xml", "/p/0/f2.xml", "/p/0/f4.xml"].map(PathBuf::from));
let (kept, total) = first_in_scope(kept, |_| true, 20_000);
assert_eq!((kept.len(), total), (3, 3));
}
}
+5
Переглянути файл
@@ -653,6 +653,11 @@ impl PluginHost {
.collect()
}
/// Whether a usable plugin offers ghost text for `language`.
pub fn offers_inline_completion(&self, language: &str) -> bool {
!self.provider_plugins(ProviderKind::InlineCompletion, language).is_empty()
}
/// Ghost text from the first plugin that has some. Not bound by the
/// edit-path soft deadline (it may need the network) but by `cancel`:
/// the editor cancels a request as soon as the user types on.
+32
Переглянути файл
@@ -3027,6 +3027,38 @@ fn official_ai_completion_cancels_superseded_requests() {
assert!(times[9] < Duration::from_millis(500), "{times:?}");
}
/// Installed with the optional network permission refused (it is not ticked by
/// default), a suggestion request says so in the window instead of failing silently.
#[test]
fn official_ai_completion_explains_a_refused_network_permission() {
let f = fixture(Limits::default());
f.host.install_from_dir(&official("ai-completion"), &Consent::default()).unwrap();
let (port, seen) = http_server(r#"{"choices":[{"text":"a + b\n"}]}"#, |_| Duration::ZERO);
f.run("openidea.ai-completion", "set-endpoint", Some(&format!("http://localhost:{port}"))).unwrap();
f.take_events();
let doc = ide_plugin::ProviderDocument {
path: f.project.join("src/a.rs"),
language: "rust".into(),
version: 1,
text: "let x = ".into(),
};
for _ in 0..2 {
assert!(f.host.provide_inline_completion(&doc, ide_core::Pos::new(0, 8), &Default::default()).is_none());
}
assert!(seen.lock().is_empty(), "denied before connecting");
let notices: Vec<String> = f
.take_events()
.into_iter()
.filter_map(|(_, e)| match e {
PluginEvent::Notification { level: NotificationLevel::Warning, body, .. } => Some(body),
_ => None,
})
.collect();
assert_eq!(notices.len(), 1, "once: {notices:?}");
assert!(notices[0].contains("Settings › Plugins › AI Completion"), "{notices:?}");
assert_eq!(f.status("openidea.ai-completion"), PluginStatus::Active, "not a crash");
}
/// Checkstyle: a save runs the approved `checkstyle` and publishes
/// diagnostics; quick fixes come through the code-action provider; saving
/// again cancels the check still running.
+3 -1
Переглянути файл
@@ -258,7 +258,8 @@ impl ProjectIndex {
}
/// Bounded file inventory for background plugin indexers; honors the same
/// project/exclude scope as search and never walks the filesystem.
/// project/exclude scope as search, leaves VCS-ignored files out and never
/// walks the filesystem.
pub fn files_with_extensions(&self, extensions: &[String], limit: usize) -> Vec<PathBuf> {
self.shared
.data
@@ -266,6 +267,7 @@ impl ProjectIndex {
.files
.iter()
.flatten()
.filter(|f| !f.ignored)
.filter(|f| f.path.extension().and_then(|e| e.to_str()).is_some_and(|e| extensions.iter().any(|x| x == e)))
.take(limit)
.map(|f| f.path.clone())
+5 -1
Переглянути файл
@@ -895,15 +895,19 @@ fn workspace_scope_excludes_state_from_scans_updates_and_cached_results() {
}
#[test]
fn plugin_inventory_respects_excludes_and_symbols_require_matching_text() {
fn plugin_inventory_respects_excludes_and_ignores_and_symbols_require_matching_text() {
let java = "package demo; interface UserMapper { void find(); }";
let f = Fixture::new(&[
("src/UserMapper.java", java),
("src/mapper.xml", "<mapper/>"),
("target/Generated.java", "class Generated {}"),
("other.txt", "ignored"),
(".gitignore", "gen/\n"),
("gen/Ignored.java", "class Ignored {}"),
]);
let index = f.open();
// Go to File lists the git-ignored file; plugin navigation leaves it out.
assert_eq!(files(&index, "Ignored"), ["gen/Ignored.java"]);
let paths = index.files_with_extensions(&["java".into(), "xml".into()], 100);
assert_eq!(paths.len(), 2);
assert!(paths.iter().all(|p| p.starts_with(f.root.join("src"))));
+16 -1
Переглянути файл
@@ -9,7 +9,8 @@ use crate::LspManager;
use crate::server::{Running, Server};
use ide_core::error::{ErrorData, ErrorKind};
use ide_core::event::LspRefreshKind;
use ide_core::{CancellationToken, IdeError, IdeResult, LanguageId};
use ide_core::{CancellationToken, IdeError, IdeResult, LanguageId, Location, Pos};
use lsp_types as lsp;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use specta::Type;
@@ -20,6 +21,7 @@ use std::time::{Duration, Instant};
pub(crate) const SERVER: &str = "jdtls";
const GENERATED_SOURCES: &str = "openidea.java.generatedSources";
const METHOD_REFERENCE_DEFINITION: &str = "openidea.java.methodReferenceDefinition";
pub(crate) mod configuration;
pub(crate) mod exception_breakpoints;
@@ -771,6 +773,19 @@ impl LspManager {
}
}
/// The declaration of a Java method named by `Type::method` / `expr::method` at `pos`.
/// JDT's selection-based definition can return the functional interface method when the
/// referenced method is inherited; the extension resolves the AST binding instead.
pub(crate) async fn java_method_reference_definition(&self, path: &Path, pos: Pos) -> IdeResult<Vec<Location>> {
let uri = crate::path_to_uri_string(path);
let value = self
.jdtls_command(path, METHOD_REFERENCE_DEFINITION, vec![json!(uri), json!(pos.line), json!(pos.col)])
.await?;
let locations: Vec<lsp::Location> = serde_json::from_value(value).unwrap_or_default();
let conv = self.conv(crate::text::Encoding::Utf16);
Ok(locations.iter().filter_map(|location| conv.location(location)).collect())
}
/// The jdtls instance serving `path` (a module directory or source file),
/// started if needed and waited for.
async fn jdtls(&self, path: &Path, cancel: &CancellationToken) -> IdeResult<(Arc<Server>, Running)> {
+74 -1
Переглянути файл
@@ -327,6 +327,25 @@ fn goto_is_empty(r: &Option<lsp::GotoDefinitionResponse>) -> bool {
}
}
/// Whether the caret is on the method name of a Java method reference (`Type::method`).
/// A method reference can name a functional interface's method through JDT's selection-based
/// definition when the referenced method is inherited, so ask the AST binding command instead.
fn java_method_reference_at(text: &DocText, pos: Pos) -> bool {
let line = text.line(pos.line as usize);
let mut utf16 = 0u32;
let mut at = line.len();
for (i, c) in line.char_indices() {
if utf16 >= pos.col {
at = i;
break;
}
utf16 += c.len_utf16() as u32;
}
let before = line[..at].trim_end();
let Some(colon) = before.rfind("::") else { return false };
before[colon + 2..].trim_start().chars().all(|c| c.is_alphanumeric() || c == '_' || c == '$')
}
fn rpc_err(server: &str, method: &str, e: RpcError) -> IdeError {
match e {
RpcError::Cancelled => IdeError::cancelled(),
@@ -1793,7 +1812,31 @@ impl LspManager {
}
let (method, cap, feature) = goto_method(kind);
let (snap, targets) = self.doc_targets(doc, feature, |c| c.has(cap)).await?;
self.goto_in(&snap, &targets, method, pos, None, None).await
let result = self.goto_in(&snap, &targets, method, pos, None, None).await;
// JDT's selection-based definition can name the functional interface method for an
// inherited method reference. Ask the Java binding command when that is what came back,
// when the caret is on a method reference, or when the server found no target at all.
let method_reference = snap.language.as_str() == "java" && java_method_reference_at(&snap.text, pos);
if kind == GotoKind::Definition
&& snap.language.as_str() == "java"
&& (method_reference
|| result.as_ref().is_ok_and(|locs| {
locs.is_empty()
|| locs.iter().any(|l| {
let path = l.path.to_string_lossy().replace('\\', "/");
let uri = l.uri.as_deref().unwrap_or_default();
path.contains("java/util/function")
|| path.contains("java.util.function")
|| uri.contains("java/util/function")
|| uri.contains("java.util.function")
})
}))
&& let Ok(found) = self.java_method_reference_definition(&snap.path, pos).await
&& !found.is_empty()
{
return Ok(found);
}
result
}
/// Go to Implementation, with the implementations found first passed to `partial` while
@@ -4677,6 +4720,36 @@ mod code_action_tests {
}
}
#[cfg(test)]
mod java_method_reference_tests {
use super::java_method_reference_at;
use crate::text::DocText;
use ide_core::Pos;
#[test]
fn finds_the_method_name_of_a_method_reference() {
let text = DocText::new("wrapper.set(XbkBtbOutNotice::getUpdateTime, now);");
let col = "wrapper.set(XbkBtbOutNotice::get".len() as u32;
assert!(java_method_reference_at(&text, Pos::new(0, col)));
}
#[test]
fn allows_whitespace_around_the_method_reference_operator() {
let text = DocText::new("wrapper.set(XbkBtbOutNotice :: getUpdateTime, now);");
let col = "wrapper.set(XbkBtbOutNotice :: get".len() as u32;
assert!(java_method_reference_at(&text, Pos::new(0, col)));
}
#[test]
fn ignores_regular_calls_and_the_referenced_type() {
let text = DocText::new("wrapper.set(XbkBtbOutNotice::getUpdateTime, now);");
let type_col = "wrapper.set(XbkBtbOutNotice".len() as u32;
assert!(!java_method_reference_at(&text, Pos::new(0, type_col)));
let call = DocText::new("wrapper.set(getUpdateTime(), now);");
assert!(!java_method_reference_at(&call, Pos::new(0, "wrapper.set(get".len() as u32)));
}
}
#[cfg(test)]
mod did_change_content_tests {
use super::*;
+25 -2
Переглянути файл
@@ -613,11 +613,14 @@ impl PluginEngine {
pub fn compile_cached(&self, wasm: &Path, cache_dir: &Path) -> Result<Component, String> {
let bytes = std::fs::read(wasm).map_err(|e| format!("{}: {e}", wasm.display()))?;
let file = cache_dir.join(format!("{}.cwasm", self.cache_key(&bytes)));
if file.is_file() {
// Read into memory rather than `deserialize_file`: that maps the file and makes its pages
// executable, which the hardened runtime of the signed macOS app refuses ("failed to make
// memory executable"), so the cache never hit and every activation compiled again.
if let Ok(precompiled) = std::fs::read(&file) {
// SAFETY: the cache directory belongs to the IDE (inside its plugins
// directory) and is written only by `store_precompiled` below from
// components this engine compiled; a corrupt file fails validation.
match unsafe { Component::deserialize_file(&self.engine, &file) } {
match unsafe { Component::deserialize(&self.engine, &precompiled) } {
Ok(component) => return Ok(component),
Err(e) => {
tracing::info!("discarding precompiled {}: {e}", file.display());
@@ -3035,6 +3038,26 @@ impl Runtime {
mod tests {
use super::*;
/// The second compile of the same component loads the cached one instead of compiling and
/// writing it again (a failed load deletes and rewrites the file).
#[test]
fn a_precompiled_component_is_loaded_from_the_cache() {
let engine = PluginEngine::new().unwrap();
let wasm = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/hello/dist/plugin.wasm");
let cache = tempfile::tempdir().unwrap();
engine.compile_cached(&wasm, cache.path()).unwrap();
let cached = || {
let entries: Vec<_> = std::fs::read_dir(cache.path()).unwrap().flatten().map(|e| e.path()).collect();
assert_eq!(entries.len(), 1, "{entries:?}");
let file = entries[0].clone();
(std::fs::metadata(&file).unwrap().modified().unwrap(), file)
};
let before = cached();
std::thread::sleep(std::time::Duration::from_millis(20));
engine.compile_cached(&wasm, cache.path()).unwrap();
assert_eq!(cached(), before, "loaded, not compiled and stored again");
}
#[test]
fn readonly_field_extensions_are_parsed_and_unknown_or_malformed_fields_are_skipped() {
let fields = [
+1 -1
Переглянути файл
@@ -1629,7 +1629,7 @@ pub fn usages_bundle(data_dir: &Path) -> Option<PathBuf> {
install_bundle(
data_dir,
"java-usages",
"1.19.0",
"1.20.1",
include_bytes!("../../../java/java-usages/openidea-java-usages.jar"),
)
}
+57 -15
Переглянути файл
@@ -464,11 +464,16 @@ fn renamed_from(
Ok(None)
}
/// The log index, locked only around reads and writes: Git runs without it, so commit
/// details and one-commit queries need not wait for a long history walk.
fn lock(index: &std::sync::Mutex<crate::log_index::LogIndex>) -> std::sync::MutexGuard<'_, crate::log_index::LogIndex> {
index.lock().unwrap_or_else(|p| p.into_inner())
}
pub(crate) fn log(r: &Repo, q: &LogQuery, cancel: &CancellationToken) -> IdeResult<Vec<Commit>> {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
let mut index = r.log_index.lock().unwrap_or_else(|p| p.into_inner());
let result = if q.summary_only {
let mut all = q.clone();
all.skip = 0;
@@ -483,14 +488,19 @@ pub(crate) fn log(r: &Repo, q: &LogQuery, cancel: &CancellationToken) -> IdeResu
repo.shallow_commits().map_err(gx)?.map(|ids| ids.iter().copied().collect::<Vec<_>>()).unwrap_or_default();
let shallow: HashSet<ObjectId> = shallow_vec.iter().copied().collect();
let key = format!("{}:{generation}:{shallow_vec:?}", serde_json::to_string(&all).map_err(gx)?);
let cached = index.views.get(&key).cloned();
let cached = lock(&r.log_index).views.get(&key).cloned();
let view = if let Some(cached) = cached {
cached
} else {
// Immutable metadata is reused across roots, filters, merges and ref changes.
all.request = q.request;
let rows =
std::sync::Arc::new(crate::log_index::IndexedView::new(log_indexed_rows(r, &all, cancel, &mut index)?));
let rows = std::sync::Arc::new(crate::log_index::IndexedView::new(log_indexed_rows(
r,
&all,
cancel,
&r.log_index,
)?));
let mut index = lock(&r.log_index);
if index.views.len() >= 4 {
index.views.clear();
}
@@ -512,6 +522,7 @@ pub(crate) fn log(r: &Repo, q: &LogQuery, cancel: &CancellationToken) -> IdeResu
let retain = q.retain_until.as_ref().and_then(|id| find_pos(id)).map(|i| i + 1).unwrap_or(0);
let limit = if q.limit == 0 { usize::MAX } else { (q.limit as usize).max(retain.saturating_sub(start)) };
let total = view.rows.len() as u32;
let mut index = lock(&r.log_index);
let db = index.db().cloned();
let txn = db.as_ref().and_then(|db| db.begin_read().ok());
let table = txn.as_ref().and_then(|t| t.open_table(crate::log_index::COMMITS).ok());
@@ -538,9 +549,9 @@ pub(crate) fn log(r: &Repo, q: &LogQuery, cancel: &CancellationToken) -> IdeResu
}
Ok(result)
} else {
log_indexed(r, q, cancel, &mut index)
log_indexed(r, q, cancel, &r.log_index)
};
index.flush();
lock(&r.log_index).flush();
result
}
@@ -640,7 +651,7 @@ fn log_indexed(
r: &Repo,
q: &LogQuery,
cancel: &CancellationToken,
index: &mut crate::log_index::LogIndex,
shared: &std::sync::Mutex<crate::log_index::LogIndex>,
) -> IdeResult<Vec<Commit>> {
let repo = r.gix()?;
let shallow: HashSet<ObjectId> =
@@ -676,6 +687,8 @@ fn log_indexed(
&& q.since_ms.is_none()
&& q.until_ms.is_none()
{
let mut guard = lock(shared);
let index = &mut *guard;
update_head_reachable(&repo, index, cancel)?;
let id = tips[0];
let record = index.get(&repo, id)?;
@@ -706,7 +719,9 @@ fn log_indexed(
commit.message_truncated = false;
return Ok(vec![commit]);
}
let rows = log_indexed_rows(r, q, cancel, index)?;
let rows = log_indexed_rows(r, q, cancel, shared)?;
let mut guard = lock(shared);
let index = &mut *guard;
let db = index.db().cloned();
let txn = db.as_ref().and_then(|db| db.begin_read().ok());
let table = txn.as_ref().and_then(|t| t.open_table(crate::log_index::COMMITS).ok());
@@ -724,7 +739,7 @@ fn log_indexed_rows(
r: &Repo,
q: &LogQuery,
cancel: &CancellationToken,
index: &mut crate::log_index::LogIndex,
shared: &std::sync::Mutex<crate::log_index::LogIndex>,
) -> IdeResult<Vec<crate::log_index::IndexedRow>> {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
@@ -775,7 +790,7 @@ fn log_indexed_rows(
}
}
}
Some(sort_subset(&repo, ids, q.order, q.first_parent, &shallow, cancel, &index.nodes)?)
Some(sort_shared(&repo, ids, q, &shallow, cancel, shared)?)
} else {
None
};
@@ -802,14 +817,17 @@ fn log_indexed_rows(
};
let authors: Vec<_> =
q.author.iter().chain(&q.authors).map(|a| a.trim().to_lowercase()).filter(|a| !a.is_empty()).collect();
update_head_reachable(&repo, index, cancel)?;
let mut range_ids_set = range_ids.as_ref().map(|ids| ids.iter().copied().collect::<HashSet<_>>());
type Walk<'a> = Box<dyn Iterator<Item = IdeResult<ObjectId>> + 'a>;
let walk: Walk<'_> = if let Some(ids) = range_ids {
Box::new(ids.into_iter().map(Ok))
} else if q.summary_only {
let ids = index.graph(&repo, &tips, &shallow, q.first_parent, cancel)?;
Box::new(sort_subset(&repo, ids, q.order, q.first_parent, &shallow, cancel, &index.nodes)?.into_iter().map(Ok))
// One guard for both: a concurrent query with another shallow set resets `nodes`.
let mut guard = lock(shared);
let ids = guard.graph(&repo, &tips, &shallow, q.first_parent, cancel)?;
let sorted = sort_subset(&repo, ids, q.order, q.first_parent, &shallow, cancel, &guard.nodes)?;
drop(guard);
Box::new(sorted.into_iter().map(Ok))
} else if repo.is_shallow().unwrap_or(false) || q.request.is_some() {
// The process can be interrupted even during indegree preparation. Git also
// respects shallow boundaries while retaining a topological order.
@@ -866,7 +884,7 @@ fn log_indexed_rows(
LogOrder::Topo | LogOrder::Standard => topo::Sorting::TopoOrder,
LogOrder::Date => topo::Sorting::DateOrder,
};
let topo = topo::Builder::from_iters(&repo.objects, tips, None::<Vec<ObjectId>>)
let topo = topo::Builder::from_iters(&repo.objects, tips.clone(), None::<Vec<ObjectId>>)
.sorting(sorting)
.parents(if q.first_parent { Parents::First } else { Parents::All })
.with_commit_graph(graph)
@@ -876,11 +894,20 @@ fn log_indexed_rows(
};
let walk: Walk<'_> = if q.order == LogOrder::Standard {
let ids = walk.collect::<IdeResult<Vec<_>>>()?;
Box::new(sort_subset(&repo, ids, q.order, q.first_parent, &shallow, cancel, &index.nodes)?.into_iter().map(Ok))
Box::new(sort_shared(&repo, ids, q, &shallow, cancel, shared)?.into_iter().map(Ok))
} else {
walk
};
let text = q.text.as_deref().map(|t| TextFilter::new(r, &scopes, q, t, cancel)).transpose()?.flatten();
let mut guard = lock(shared);
let index = &mut *guard;
// Under the guard that builds the rows: a query run meanwhile (after a branch switch)
// may have moved the shared set to another HEAD.
update_head_reachable(&repo, index, cancel)?;
// A query started before a shallow change may have reset `nodes` to its older set.
if index.shallow != shallow {
index.ensure_nodes(&repo, &tips, &shallow, cancel)?;
}
let db = index.db().cloned();
let txn = db.as_ref().and_then(|db| db.begin_read().ok());
let table = txn.as_ref().and_then(|t| t.open_table(crate::log_index::COMMITS).ok());
@@ -952,6 +979,21 @@ fn log_indexed_rows(
Ok(out)
}
/// Sorts with the shared nodes only when they were built for this query's shallow set.
fn sort_shared(
repo: &gix::Repository,
ids: Vec<ObjectId>,
q: &LogQuery,
shallow: &HashSet<ObjectId>,
cancel: &CancellationToken,
shared: &std::sync::Mutex<crate::log_index::LogIndex>,
) -> IdeResult<Vec<ObjectId>> {
let guard = lock(shared);
let empty = HashMap::new();
let nodes = if &guard.shallow == shallow { &guard.nodes } else { &empty };
sort_subset(repo, ids, q.order, q.first_parent, shallow, cancel, nodes)
}
/// A ready-node stack gives incoming merge parents priority, while child counts
/// prevent an ancestor shared with another branch from moving ahead of its children.
fn sort_subset(
+18 -2
Переглянути файл
@@ -311,6 +311,22 @@ fn network_args(r: &Repo) -> Vec<String> {
NETWORK_STAT_CONFIG.iter().flat_map(|(key, value)| ["-c".to_owned(), format!("{key}={value}")]).collect()
}
/// Runs `git status`; when rename detection needs a blob that cannot be fetched (Restricted Mode
/// sets `GIT_NO_LAZY_FETCH`, or the promisor remote is unreachable), retries once without it.
/// The message is stable because `cli::command` pins `LC_ALL=C`.
fn run_status(r: &Repo, mut args: Vec<&str>) -> IdeResult<crate::cli::Output> {
let out = crate::cli::run_raw_env(r.root(), &args, None, &read_only())?;
if out.code == Some(0) {
return Ok(out);
}
if String::from_utf8_lossy(&out.stderr).contains("promisor remote") {
let at = args.iter().position(|a| *a == "status").map_or(args.len(), |i| i + 1);
args.insert(at, "--no-renames");
return crate::cli::run_env(r.root(), &args, None, &read_only());
}
Err(crate::cli::failure(&args, &out.stderr, &out.stdout, out.code))
}
/// `git status --porcelain=v2`: what git lists, unreadable directories skipped.
/// In Restricted Mode git compares content without the repository's clean/process
/// filters and doesn't ask submodules for their own status (which runs their config).
@@ -323,7 +339,7 @@ fn cli_status(r: &Repo, ignored: &IgnoredNames) -> IdeResult<Entries> {
if !crate::execution_allowed() {
args.push("--ignore-submodules=dirty");
}
let out = crate::cli::run_env(r.root(), &args, None, &read_only())?;
let out = run_status(r, args)?;
Ok(parse_porcelain_v2(&String::from_utf8_lossy(&out.stdout), ignored))
}
@@ -340,7 +356,7 @@ fn cli_status_paths(r: &Repo, ignored: &IgnoredNames, paths: &[String]) -> IdeRe
}
args.push("--");
args.extend(paths.iter().map(String::as_str));
let out = crate::cli::run_env(r.root(), &args, None, &read_only())?;
let out = run_status(r, args)?;
Ok(parse_porcelain_v2(&String::from_utf8_lossy(&out.stdout), ignored))
}
+79
Переглянути файл
@@ -0,0 +1,79 @@
//! A long file history walk must not hold the log index while Git runs: commit details and
//! one-commit queries (inline blame, the blame popup) share that index.
#![cfg(unix)]
use ide_vcs::{LogQuery, Repo};
use std::os::unix::fs::PermissionsExt;
use std::path::Path;
use std::process::Command;
use std::time::{Duration, Instant};
fn git(dir: &Path, args: &[&str]) -> String {
let out = Command::new("git")
.current_dir(dir)
.args([
"-c",
"init.defaultBranch=main",
"-c",
"user.name=T",
"-c",
"user.email=t@e",
"-c",
"commit.gpgsign=false",
])
.args(args)
.output()
.unwrap();
assert!(out.status.success(), "{args:?}: {}", String::from_utf8_lossy(&out.stderr));
String::from_utf8_lossy(&out.stdout).trim().to_string()
}
#[test]
fn details_and_one_commit_queries_do_not_wait_for_a_file_history_walk() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path().join("repo");
std::fs::create_dir(&dir).unwrap();
git(&dir, &["init", "-q"]);
for i in 0..3 {
std::fs::write(dir.join("file"), format!("{i}")).unwrap();
git(&dir, &["add", "-A"]);
git(&dir, &["commit", "-qm", &format!("c{i}")]);
}
// A git whose path-limited history walks take seconds.
let real = String::from_utf8(Command::new("sh").args(["-c", "command -v git"]).output().unwrap().stdout).unwrap();
let started = tmp.path().join("walk-started");
let wrapper = tmp.path().join("slow-git");
std::fs::write(
&wrapper,
format!(
"#!/bin/sh\ncase \" $* \" in *\" --full-history \"*) : > '{}'; sleep 3;; esac\nexec '{}' \"$@\"\n",
started.display(),
real.trim()
),
)
.unwrap();
std::fs::set_permissions(&wrapper, std::fs::Permissions::from_mode(0o755)).unwrap();
let repo = Repo::discover(&dir).unwrap().unwrap();
repo.set_execution_allowed(true);
repo.set_git_executable(Some(&wrapper));
std::thread::scope(|scope| {
let walk = scope.spawn(|| {
repo.log(&LogQuery { path: Some("file".into()), follow: true, ..Default::default() }).unwrap().len()
});
let deadline = Instant::now() + Duration::from_secs(20);
while !started.exists() {
assert!(Instant::now() < deadline, "the history walk never started");
std::thread::sleep(Duration::from_millis(20));
}
let asked = Instant::now();
let details = repo.log_details("HEAD").unwrap();
let head = repo.log(&LogQuery { branch: Some("HEAD".into()), limit: 1, ..Default::default() }).unwrap();
let waited = asked.elapsed();
println!("queries waited {waited:?}");
assert_eq!(details.message, "c2");
assert_eq!(head.len(), 1);
assert!(!walk.is_finished(), "the walk ended before the queries ran; the test proves nothing");
assert!(waited < Duration::from_secs(2), "queries waited {waited:?} for the walk");
assert_eq!(walk.join().unwrap(), 3);
});
}
+144
Переглянути файл
@@ -0,0 +1,144 @@
//! Partial clones (`--filter=blob:none`) with a sparse checkout: blobs outside the
//! checkout are never fetched, and gitoxide's status cannot read them.
use ide_vcs::{ChangeKind, LogQuery, Repos};
use std::path::Path;
use std::process::Command;
fn git(dir: &Path, args: &[&str]) {
let out = Command::new("git")
.current_dir(dir)
.args(["-c", "init.defaultBranch=main", "-c", "core.autocrlf=false", "-c", "protocol.file.allow=always"])
.args(args)
.env("GIT_TERMINAL_PROMPT", "0")
.output()
.expect("git runs");
assert!(out.status.success(), "git {args:?}: {}", String::from_utf8_lossy(&out.stderr));
}
fn git_available() -> bool {
Command::new("git").arg("--version").output().is_ok_and(|o| o.status.success())
}
fn file_url(path: &Path) -> String {
let path = path.to_string_lossy().replace('\\', "/");
format!("file:///{}", path.trim_start_matches('/'))
}
/// A blobless, cone-mode sparse clone of a small source repository; `docs/` and `app/` blobs stay remote.
fn blobless_clone(base: &Path) -> std::path::PathBuf {
let source = base.join("source");
std::fs::create_dir_all(source.join("docs")).unwrap();
std::fs::create_dir_all(source.join("app")).unwrap();
git(&source, &["init", "-q"]);
git(&source, &["config", "user.name", "Test User"]);
git(&source, &["config", "user.email", "[email protected]"]);
git(&source, &["config", "commit.gpgsign", "false"]);
std::fs::write(source.join("README.md"), "hello\n").unwrap();
let guide: String = (1..=200).map(|i| format!("line {i}\n")).collect();
std::fs::write(source.join("docs/guide.txt"), &guide).unwrap();
std::fs::write(source.join("app/main.rs"), "fn main() {}\n").unwrap();
git(&source, &["add", "-A"]);
git(&source, &["commit", "-q", "-m", "init"]);
let bare = base.join("bare.git");
git(base, &["clone", "-q", "--bare", "source", "bare.git"]);
git(&bare, &["config", "uploadpack.allowFilter", "true"]);
git(&bare, &["config", "uploadpack.allowAnySHA1InWant", "true"]);
let work = base.join("work");
git(base, &["clone", "-q", "--filter=blob:none", "--sparse", &file_url(&bare), "work"]);
git(&work, &["config", "user.name", "Test User"]);
git(&work, &["config", "user.email", "[email protected]"]);
// A global `status.renames=false` would make the baseline pass without the fix.
git(&work, &["config", "status.renames", "true"]);
assert!(!work.join("app/main.rs").exists(), "app/ is outside the sparse checkout");
work
}
#[test]
fn blobless_sparse_clone_keeps_its_repository_and_status() {
if !git_available() {
eprintln!("git is not available; skipping");
return;
}
let tmp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(tmp.path()).unwrap();
let work = blobless_clone(&base);
let bare = base.join("bare.git");
std::fs::write(work.join("README.md"), "hello\nchanged\n").unwrap();
std::fs::write(work.join("new.txt"), "new\n").unwrap();
// A staged deletion of a never-fetched blob plus a near-identical addition: rename
// detection would have to fetch the missing blob (`git rm --sparse` needs git 2.35+).
git(&work, &["rm", "-q", "--sparse", "docs/guide.txt"]);
let renamed: String = (1..=199).map(|i| format!("line {i}\n")).collect();
std::fs::write(work.join("guide2.txt"), renamed).unwrap();
git(&work, &["add", "guide2.txt"]);
// The promisor remote is gone: status must not need it.
std::fs::rename(&bare, base.join("gone.git")).unwrap();
let repos = Repos::discover(&work, &|_| false).unwrap();
let repo = repos.primary().expect("the partial clone is a repository");
assert_eq!(repo.root(), work);
assert_eq!(repo.branch_info().unwrap().head.as_deref(), Some("main"));
assert_eq!(repo.log(&LogQuery::default()).unwrap().len(), 1);
let status = repos.status().expect("status of a partial clone");
let find = |rel: &str| status.iter().find(|f| f.rel_path == rel);
let readme = find("README.md").expect("README.md listed");
assert_eq!((readme.staged, readme.unstaged), (None, Some(ChangeKind::Modified)));
let new = find("new.txt").expect("new.txt listed");
assert_eq!(new.unstaged, Some(ChangeKind::Untracked));
// Rename detection needs the never-fetched blob, so the retry without it lists an addition.
let moved = find("guide2.txt").expect("guide2.txt listed");
assert_eq!((moved.staged, moved.renamed_from.as_deref()), (Some(ChangeKind::Added), None));
let removed = find("docs/guide.txt").expect("docs/guide.txt listed");
assert_eq!(removed.staged, Some(ChangeKind::Deleted));
// Skip-worktree entries outside the checkout are not missing files.
assert!(find("app/main.rs").is_none(), "{status:?}");
assert_eq!(status.len(), 4, "{status:?}");
// The watcher's scoped refresh (a trusted project's `git status` with a pathspec) retries the
// same way.
repo.set_execution_allowed(true);
let scoped = repo.status_paths(&[work.join("guide2.txt"), work.join("docs/guide.txt")]).expect("scoped status");
let find = |rel: &str| scoped.iter().find(|f| f.rel_path == rel);
let moved = find("guide2.txt").expect("guide2.txt listed");
assert_eq!((moved.staged, moved.renamed_from.as_deref()), (Some(ChangeKind::Added), None));
assert_eq!(find("docs/guide.txt").expect("docs/guide.txt listed").staged, Some(ChangeKind::Deleted));
assert_eq!(scoped.len(), 2, "{scoped:?}");
}
#[test]
fn blobless_clone_still_detects_a_rename_between_local_blobs() {
if !git_available() {
eprintln!("git is not available; skipping");
return;
}
let tmp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(tmp.path()).unwrap();
let work = blobless_clone(&base);
// README.md is inside the cone, so both sides of the rename are local blobs.
git(&work, &["mv", "README.md", "README2.md"]);
let repos = Repos::discover(&work, &|_| false).unwrap();
let repo = repos.primary().expect("the partial clone is a repository");
let status = repos.status().expect("status of a partial clone");
let moved = status.iter().find(|f| f.rel_path == "README2.md").expect("README2.md listed");
assert_eq!(
(moved.staged, moved.renamed_from.as_deref()),
(Some(ChangeKind::Renamed), Some("README.md")),
"{status:?}"
);
repo.set_execution_allowed(true);
let scoped = repo.status_paths(&[work.join("README2.md"), work.join("README.md")]).expect("scoped status");
let moved = scoped.iter().find(|f| f.rel_path == "README2.md").expect("README2.md listed");
assert_eq!(
(moved.staged, moved.renamed_from.as_deref()),
(Some(ChangeKind::Renamed), Some("README.md")),
"{scoped:?}"
);
}
+36 -6
Переглянути файл
@@ -99,7 +99,9 @@ impl FileMoves {
/// Applies `edit` (paths as before the move, as `workspace/willRenameFiles`
/// returns them), then performs `moves`. Edited files are snapshotted in
/// Local History first. On failure everything done so far is rolled back.
/// Local History first. `apply_edit` must be transactional: on error it leaves none of
/// its own changes behind, so a rejected edit keeps external changes. A failed
/// file move rolls back the applied edits.
/// Returns the id for [`undo`](Self::undo).
pub fn perform(
&self,
@@ -134,11 +136,8 @@ impl FileMoves {
}
before.push(text);
}
if !paths.is_empty()
&& let Err(e) = apply_edit(edit)
{
restore(documents, &paths, &before);
return Err(e);
if !paths.is_empty() {
apply_edit(edit)?;
}
if let Err(e) = crate::file_ops::move_files(moves) {
restore(documents, &paths, &before);
@@ -305,6 +304,37 @@ mod tests {
assert_eq!(fs::read_to_string(root.join("Use.java")).unwrap(), "Bar f; // edited\n");
}
#[test]
fn rejected_reference_edits_preserve_changes_after_the_snapshot() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
fs::write(root.join("source.ts"), "source\n").unwrap();
fs::write(root.join("main.ts"), "old\n").unwrap();
let docs = documents();
let mut edit = WorkspaceEdit {
files: vec![FileEdit::Edit {
path: root.join("main.ts").into(),
version: None,
edits: vec![TextEdit { range: Range::new(Pos::new(0, 0), Pos::new(0, 3)), new_text: "updated".into() }],
}],
..Default::default()
};
docs.prepare_workspace_edit(&mut edit).unwrap();
let apply_edit = |edit: &WorkspaceEdit| {
// An external writer lands after perform captured its rollback text.
fs::write(root.join("main.ts"), "external edit after snapshot\n").unwrap();
docs.apply_file_move_edits(edit)
};
let moves = FileMoves::new();
let mv = vec![FileMove { from: root.join("source.ts").into(), to: root.join("renamed.ts").into() }];
let error = moves.perform(&docs, None, &mv, &edit, "Move", &apply_edit).unwrap_err();
assert_eq!(error.kind, ide_core::error::ErrorKind::OutOfSync);
assert_eq!(fs::read_to_string(root.join("main.ts")).unwrap(), "external edit after snapshot\n");
assert_eq!(fs::read_to_string(root.join("source.ts")).unwrap(), "source\n");
assert!(!root.join("renamed.ts").exists());
assert_eq!(moves.last(), None);
}
#[test]
fn moved_paths() {
let mv = vec![FileMove { from: "/p/a".into(), to: "/p/b/a".into() }];
+2
Переглянути файл
@@ -145,6 +145,8 @@ Tab placement, the tab limit and what happens when it is reached, the preview ta
With tabs placed left or right, the tab column is as wide as its longest name, up to a limit. Drag the column's inner edge (or focus it and press `←` / `→`) to change the limit; it applies to every editor group and is remembered.
Double-click a tab, or the empty part of the tab strip, to maximize the editor: all tool windows are hidden, and doing it again brings them back. Double-clicking a preview tab keeps it open as a regular tab instead.
## Split editors
| Action | macOS | Windows / Linux |
+2
Переглянути файл
@@ -143,6 +143,8 @@ description: "多光标与选区、行编辑、剪贴板历史、代码折叠、
标签页放在左侧或右侧时,标签页列的宽度随最长的名称变化,但不超过一个上限。拖动该列靠近编辑器的边缘(或聚焦后按 `←` / `→`)可以调整上限;调整对所有编辑器组生效,并会被记住。
双击标签页或标签页栏的空白处可以最大化编辑器:隐藏所有工具窗口,再双击一次即恢复。双击预览标签页则会把它转为常规标签页。
## 拆分编辑器
| 操作 | macOS | Windows / Linux |
+48
Переглянути файл
@@ -242,3 +242,51 @@ for (const theme of ["dark", "light"] as const) {
}
}
}
test("a long agent form scrolls above the composer instead of being cut off", async ({ workbench: page }) => {
await page.setViewportSize({ width: 1000, height: 520 });
const fields = Array.from({ length: 5 }, (_, q) => ({
name: `q${q + 1}`,
title: `Question ${q + 1}`,
kind: "choice" as const,
required: true,
options: Array.from({ length: 4 }, (_, o) => ({ value: `a${o + 1}`, label: `Answer ${q + 1}.${o + 1}` })),
}));
await page.evaluate(
async ({ task, fields }) => {
const storePath = "/src/features/agents/store.ts";
const store: typeof AgentStore = await import(storePath);
store.useAgents.setState({
loaded: true,
tasks: new Map([[task.id, task]]),
entries: new Map([
[
task.id,
[{ type: "permission", id: 1, title: "Plan the change", options: [], chosen: null, form: { fields } }],
],
]),
});
store.openTaskInEditorLocation(task.id);
},
{ task, fields },
);
const card = page.getByRole("form", { name: "Plan the change" });
await expect(card).toBeVisible();
const composer = page.getByRole("textbox", { name: "Message", exact: true });
await expect(composer).toBeInViewport();
for (let q = 1; q <= 5; q++) {
const last = card.getByRole("radio", { name: `Answer ${q}.4` });
await last.scrollIntoViewIfNeeded();
const box = (await last.boundingBox())!;
const hit = await page.evaluate(
({ x, y }) => document.elementFromPoint(x, y)?.closest("label")?.textContent ?? null,
{ x: box.x + box.width / 2, y: box.y + box.height / 2 },
);
expect(hit).toContain(`Answer ${q}.4`);
await last.check();
}
const submit = card.getByRole("button", { name: "Submit", exact: true });
await submit.scrollIntoViewIfNeeded();
await expect(submit).toBeInViewport({ ratio: 1 });
await expect(submit).toBeEnabled();
});
+87
Переглянути файл
@@ -202,6 +202,93 @@ test("File Structure prefers matches inside the caret symbol", async ({ workbenc
await expect(tree.getByRole("treeitem", { name: "load", exact: true })).toHaveAttribute("aria-selected", "false");
});
test("File Structure auto-enables temporary filters without saving them", async ({ workbench: page }) => {
await openFromTree(page, "build.gradle.kts");
await stubDesktop(page);
await page.evaluate(async () => {
const optionsPath = "/src/features/search/structure/store.ts";
const { useStructureOptions } = await import(/* @vite-ignore */ optionsPath);
useStructureOptions.setState({ showFields: false, showNonPublic: false, showInherited: false, narrowDown: true });
const range = { start: { line: 0, col: 0 }, end: { line: 1, col: 1 } };
const symbol = (name: string, kind: string, visibility?: string) => ({
name,
kind,
visibility,
range,
selection_range: range,
children: [],
});
window.__ipc.handlers.doc_outline = () => [
{
...symbol("Container", "class"),
children: [
symbol("hiddenField", "field"),
symbol("hiddenMethod", "method", "private"),
symbol("visible", "method"),
],
},
];
window.__ipc.handlers.lsp_type_hierarchy = () => [];
const actionsPath = "/src/platform/actions.ts";
const { executeAction } = await import(/* @vite-ignore */ actionsPath);
await executeAction("navigate.fileStructure");
});
const dialog = page.getByRole("dialog", { name: "File Structure" });
const filter = dialog.getByRole("textbox", { name: "Filter symbols" });
const tree = dialog.getByRole("tree", { name: "Symbols" });
const fields = dialog.getByRole("checkbox", { name: "Show fields" });
const nonPublic = dialog.getByRole("checkbox", { name: "Show non-public" });
const readOptions = () =>
page.evaluate(async () => {
const path = "/src/features/search/structure/store.ts";
const { useStructureOptions } = await import(/* @vite-ignore */ path);
const { showFields, showNonPublic, showInherited } = useStructureOptions.getState();
return { showFields, showNonPublic, showInherited };
});
await expect(fields).not.toBeChecked();
await expect(nonPublic).not.toBeChecked();
await filter.fill("hiddenField");
await expect(fields).toBeChecked();
await expect(nonPublic).not.toBeChecked();
await expect(tree.getByRole("treeitem", { name: "hiddenField", selected: true })).toBeVisible();
expect(await readOptions()).toEqual({ showFields: false, showNonPublic: false, showInherited: false });
await nonPublic.check();
expect(await readOptions()).toEqual({ showFields: false, showNonPublic: true, showInherited: false });
const saved = await page.evaluate(() => localStorage.getItem("openidea.structure.options.v1"));
await filter.press("End");
await filter.press("Backspace");
await expect(filter).toHaveValue("hiddenFiel");
await expect(fields).not.toBeChecked();
await expect(nonPublic).toBeChecked();
await expect(tree.getByRole("treeitem", { name: "hiddenField", exact: true })).toBeHidden();
expect(await readOptions()).toEqual({ showFields: false, showNonPublic: true, showInherited: false });
await filter.fill("hiddenField");
await expect(fields).toBeChecked();
await fields.uncheck();
await expect(fields).not.toBeChecked();
await filter.press("Escape");
await expect(filter).toHaveValue("");
await expect(fields).not.toBeChecked();
await filter.press("Escape");
await expect(dialog).toBeHidden();
expect(await readOptions()).toEqual({ showFields: false, showNonPublic: true, showInherited: false });
expect(await page.evaluate(() => localStorage.getItem("openidea.structure.options.v1"))).toBe(saved);
await page.evaluate(async () => {
const path = "/src/platform/actions.ts";
const { executeAction } = await import(/* @vite-ignore */ path);
await executeAction("navigate.fileStructure");
});
await expect(dialog).toBeVisible();
await expect(dialog.getByRole("checkbox", { name: "Show fields" })).not.toBeChecked();
await expect(dialog.getByRole("checkbox", { name: "Show non-public" })).toBeChecked();
expect(await page.evaluate(() => localStorage.getItem("openidea.structure.options.v1"))).toBe(saved);
});
test("F4 jumps to the filtered File Structure symbol", async ({ workbench: page }) => {
await openFromTree(page, "build.gradle.kts");
await stubDesktop(page);
+1 -1
Переглянути файл
@@ -2,7 +2,7 @@ Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: OpenIDEA Java usages
Bundle-SymbolicName: ai.openidea.usages;singleton:=true
Bundle-Version: 1.19.0
Bundle-Version: 1.20.1
Bundle-RequiredExecutionEnvironment: JavaSE-21
Require-Bundle: org.eclipse.jdt.ls.core,org.eclipse.jdt.core,
org.eclipse.jdt.core.manipulation,org.eclipse.core.runtime,
+10 -1
Переглянути файл
@@ -6,6 +6,10 @@ The app-owned OSGi command `openidea.java.usages` returns `{location, kind, acce
`kind` retains field/getter/setter/unknown identity for compatibility. Optional
`access` is read/write/readWrite/unknown. Missing access metadata is unknown;
old servers and ordinary LSP locations remain visible under either filter.
`openidea.java.methodReferenceDefinition(uri, line, column)` resolves the method name
of a `Type::method` or `expr::method` reference through its AST binding and returns the
declaring method's location. This keeps inherited methods on their parent declaration
where JDT's selection-based definition may return the functional interface method.
An absent or failing extension command uses standard LSP references, without access
classification or toolbar controls. This includes errors during scope widening.
The Rust bridge logs the failure once per project session. Cancelled requests and
@@ -88,7 +92,7 @@ is not a claim of full IntelliJ feature parity.
## Rebuild and delivery
The checked-in jar is embedded by ide-sdk `include_bytes!`, installed as
`java-usages-1.18.0.jar`, and added alongside existing initialization bundles.
`java-usages-1.20.1.jar`, and added alongside existing initialization bundles.
Users need no compiler, Maven or Python. Manifest/install version must change
when replacing the bundle because OSGi caches bundles.
@@ -142,6 +146,10 @@ protobuf and gRPC stubs on the project classpath; its reproducible SHA-256 is
Version 1.17.0 adds `openidea.java.exceptionType`, the exception class at a caret for the exception
breakpoint intention; its reproducible SHA-256 is
`d1c596b37dcb6bd402ad48b214fd2a7651dbd4472eeea49e2ce992ea2f1363e9`.
Version 1.20.1 adds `openidea.java.methodReferenceDefinition`, which resolves inherited Java method
references from their AST binding instead of JDT's selection result. Lombok-generated accessors
without a source range fall back to their field or declaring type; its reproducible SHA-256 is
`a111a9359b8f13dcd06e14e72fa287943cfe953325bff6f940912cae199caec7`.
```sh
export PATH=/path/to/jdk25/bin:$PATH
@@ -173,6 +181,7 @@ OPENIDEA_USAGES_INDEX_STRESS=1 python3 java/java-usages/tests/read-write.py /pat
python3 java/java-usages/tests/hierarchy.py /path/to/jdtls
python3 java/java-usages/tests/implementations.py /path/to/jdtls
python3 java/java-usages/tests/exception-type.py /path/to/jdtls
python3 java/java-usages/tests/method-reference.py /path/to/jdtls
```
The harnesses select the JDT LS configuration for the current platform. The first
Бінарний файл не відображається.
+3
Переглянути файл
@@ -27,6 +27,9 @@
<delegateCommandHandler class="ai.openidea.implementations.ImplementationTargetsCommand">
<command id="openidea.java.implementationLocations"/>
</delegateCommandHandler>
<delegateCommandHandler class="ai.openidea.navigation.MethodReferenceDefinitionCommand">
<command id="openidea.java.methodReferenceDefinition"/>
</delegateCommandHandler>
<delegateCommandHandler class="ai.openidea.hierarchy.HierarchyCommand">
<command id="openidea.java.hierarchy.members"/>
<command id="openidea.java.hierarchy.refactor"/>
+131
Переглянути файл
@@ -0,0 +1,131 @@
package ai.openidea.navigation;
import ai.openidea.Documents;
import java.util.List;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jdt.core.IField;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.ITypeRoot;
import org.eclipse.jdt.core.dom.ASTNode;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.ExpressionMethodReference;
import org.eclipse.jdt.core.dom.IMethodBinding;
import org.eclipse.jdt.core.dom.ITypeBinding;
import org.eclipse.jdt.core.dom.MethodReference;
import org.eclipse.jdt.core.dom.NodeFinder;
import org.eclipse.jdt.core.dom.SimpleName;
import org.eclipse.jdt.core.dom.SuperMethodReference;
import org.eclipse.jdt.core.dom.TypeMethodReference;
import org.eclipse.jdt.core.manipulation.CoreASTProvider;
import org.eclipse.jdt.ls.core.internal.IDelegateCommandHandler;
import org.eclipse.jdt.ls.core.internal.JDTUtils;
import org.eclipse.jdt.ls.core.internal.handlers.JsonRpcHelpers;
import org.eclipse.lsp4j.Location;
/**
* Resolves a method reference (for example {@code Child::getGoodsSpace}) to the declaration
* of the referenced method. JDT's selection-based definition request can return the
* functional interface method ({@code Function.apply}) when the method is inherited;
* bindings retain the actual method identity instead.
*/
public final class MethodReferenceDefinitionCommand implements IDelegateCommandHandler {
@Override
public Object executeCommand(String command, List<Object> arguments, IProgressMonitor monitor) throws Exception {
Documents.awaitChanges(monitor);
String uri = (String) arguments.get(0);
int line = ((Number) arguments.get(1)).intValue();
int column = ((Number) arguments.get(2)).intValue();
ITypeRoot root = JDTUtils.resolveTypeRoot(uri);
if (root == null || !root.exists()) return List.of();
CompilationUnit ast = CoreASTProvider.getInstance().getAST(root, CoreASTProvider.WAIT_YES, monitor);
if (ast == null) return List.of();
int offset = JsonRpcHelpers.toOffset(root, line, column);
if (offset < 0) return List.of();
MethodReference reference = enclosingReference(ast, offset);
if (reference == null) return List.of();
SimpleName name = methodName(reference);
if (name == null) return List.of();
int start = name.getStartPosition();
if (offset < start || offset > start + name.getLength()) return List.of();
IMethodBinding binding = reference.resolveMethodBinding();
if (binding == null) return List.of();
IMethodBinding declaration = binding.getMethodDeclaration();
if (declaration == null) return List.of();
Location location = locationOf(declaration);
return location == null ? List.of() : List.of(location);
}
/**
* The declaration's source location. Lombok-generated accessors have a binding and a Java
* element but no source range; then the field the accessor reads (or the declaring type)
* is the closest source declaration. Without this fallback the standard definition request
* stays at the functional interface method.
*/
private static Location locationOf(IMethodBinding declaration) throws Exception {
var element = declaration.getJavaElement();
Location location = element == null ? null : JDTUtils.toLocation(element);
if (location != null) return location;
if (element instanceof IMember member && member.getClassFile() != null)
return JDTUtils.toLocation(member.getClassFile());
ITypeBinding owner = declaration.getDeclaringClass();
if (owner == null) return null;
var ownerElement = owner.getJavaElement();
if (!(ownerElement instanceof IType type) || !type.exists()) return null;
for (IMethod method : type.getMethods()) {
if (!method.getElementName().equals(declaration.getName())) continue;
if (method.getNumberOfParameters() != declaration.getParameterTypes().length) continue;
location = JDTUtils.toLocation(method);
if (location != null) return location;
}
String fieldName = propertyName(declaration.getName());
if (fieldName != null) {
IField field = type.getField(fieldName);
if (field.exists()) {
location = JDTUtils.toLocation(field);
if (location != null) return location;
}
}
return JDTUtils.toLocation(type);
}
/** The field name of a bean accessor (`getUpdateTime` / `setUpdateTime` / `isEnabled`). */
private static String propertyName(String methodName) {
String rest;
if (methodName.startsWith("get") || methodName.startsWith("set")) {
rest = methodName.substring(3);
} else if (methodName.startsWith("is")) {
rest = methodName.substring(2);
} else {
return null;
}
if (rest.isEmpty()) return null;
if (rest.length() > 1 && Character.isUpperCase(rest.charAt(0)) && Character.isUpperCase(rest.charAt(1))) {
return rest;
}
return Character.toLowerCase(rest.charAt(0)) + rest.substring(1);
}
private static MethodReference enclosingReference(CompilationUnit ast, int offset) {
ASTNode leaf = new NodeFinder(ast, offset, 1).getCoveringNode();
for (ASTNode node = leaf; node != null; node = node.getParent()) {
if (node instanceof MethodReference reference) return reference;
}
return null;
}
private static SimpleName methodName(MethodReference reference) {
return switch (reference) {
case TypeMethodReference type -> type.getName();
case ExpressionMethodReference expression -> expression.getName();
case SuperMethodReference superReference -> superReference.getName();
default -> null;
};
}
}
+167
Переглянути файл
@@ -0,0 +1,167 @@
"""Go to Definition on a method reference, against a real JDT LS. Arguments: jdtls home, optional bundle jar.
Each case puts the caret on a method reference's name and checks that
`openidea.java.methodReferenceDefinition` answers the referenced method's declaration (an inherited
method on its parent, not the functional interface method), and nothing elsewhere.
"""
import json
import pathlib
import platform
import queue
import subprocess
import sys
import tempfile
import threading
import time
home = pathlib.Path(sys.argv[1]).resolve()
bundle = pathlib.Path(sys.argv[2]).resolve() if len(sys.argv) > 2 else pathlib.Path(__file__).resolve().parents[1] / 'openidea-java-usages.jar'
work = pathlib.Path(tempfile.mkdtemp(prefix='openidea-method-reference-'))
config = work / 'config'
config.mkdir()
system, machine = platform.system(), platform.machine().lower()
config_name = {'Windows': 'config_win', 'Darwin': 'config_mac'}.get(system, 'config_linux')
config_names = ([config_name + '_arm'] if machine in ('arm64', 'aarch64') else []) + [config_name]
config_source = next(home / name / 'config.ini' for name in config_names if (home / name / 'config.ini').is_file())
(config / 'config.ini').write_bytes(config_source.read_bytes())
project = work / 'project'
(project / 'src/app').mkdir(parents=True)
(project / '.project').write_text('<projectDescription><name>app</name><buildSpec><buildCommand><name>org.eclipse.jdt.core.javabuilder</name></buildCommand></buildSpec><natures><nature>org.eclipse.jdt.core.javanature</nature></natures></projectDescription>')
(project / '.classpath').write_text('<classpath><classpathentry kind="src" path="src"/><classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/><classpathentry kind="output" path="bin"/></classpath>')
sources = {
'Parent.java': '''package app;
public class Parent {
public String getGoodsSpace() {
return "space";
}
public static String describe(Object o) {
return String.valueOf(o);
}
}
''',
'Child.java': '''package app;
public class Child extends Parent {
public int own() {
return 1;
}
}
''',
'Main.java': '''package app;
import java.util.List;
import java.util.function.Function;
public class Main {
void run(List<Child> children) {
Function<Child, String> inherited = Child::getGoodsSpace;
Function<Child, Integer> own = Child::own;
Function<Object, String> statics = Child::describe;
children.forEach(System.out::println);
String plain = new Child().getGoodsSpace();
}
}
''',
}
for name, text in sources.items():
(project / 'src/app' / name).write_text(text)
uri = lambda name: (project / 'src/app' / name).as_uri()
log = (work / 'stderr.log').open('w')
proc = subprocess.Popen(['java', '-Declipse.application=org.eclipse.jdt.ls.core.id1', '-Dosgi.bundles.defaultStartLevel=4', '-Declipse.product=org.eclipse.jdt.ls.core.product', '-Xmx1G', '--add-modules=ALL-SYSTEM', '--add-opens', 'java.base/java.util=ALL-UNNAMED', '--add-opens', 'java.base/java.lang=ALL-UNNAMED', '-jar', str(next((home / 'plugins').glob('org.eclipse.equinox.launcher_*.jar'))), '-configuration', str(config), '-data', str(work / 'metadata')], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=log)
messages = queue.Queue()
lock = threading.Lock()
def send(message):
data = json.dumps(message).encode()
with lock:
proc.stdin.write(f'Content-Length: {len(data)}\r\n\r\n'.encode() + data)
proc.stdin.flush()
def read():
while True:
headers = {}
while True:
line = proc.stdout.readline()
if not line:
return
if line == b'\r\n':
break
k, v = line.decode().split(':', 1)
headers[k.lower()] = v.strip()
message = json.loads(proc.stdout.read(int(headers['content-length'])))
if 'method' in message and 'id' in message:
send({'jsonrpc': '2.0', 'id': message['id'], 'result': [] if message['method'] == 'workspace/configuration' else None})
else:
messages.put(message)
threading.Thread(target=read, daemon=True).start()
seq = 0
def request(method, params):
global seq
seq += 1
send({'jsonrpc': '2.0', 'id': seq, 'method': method, 'params': params})
deadline = time.monotonic() + 180
while time.monotonic() < deadline:
msg = messages.get(timeout=max(1, deadline - time.monotonic()))
if msg.get('id') == seq:
if 'error' in msg:
raise RuntimeError(msg['error'])
return msg.get('result')
raise TimeoutError(method)
def where(loc):
return (loc['uri'].rsplit('/', 1)[-1], loc['range']['start']['line'])
def line_of(file, needle):
return next(i for i, t in enumerate(sources[file].splitlines()) if needle in t)
CASES = [
('Child::getGoodsSpace', 'getGoodsSpace', 3, [('Parent.java', line_of('Parent.java', 'getGoodsSpace'))]),
('Child::own', 'own', 1, [('Child.java', line_of('Child.java', 'own()'))]),
('Child::describe', 'describe', 2, [('Parent.java', line_of('Parent.java', 'describe'))]),
('Child::getGoodsSpace', 'Child', 2, []),
('new Child().getGoodsSpace', 'getGoodsSpace', 2, []),
]
try:
init = request('initialize', {'processId': None, 'rootUri': project.as_uri(), 'workspaceFolders': [{'uri': project.as_uri(), 'name': 'app'}], 'capabilities': {}, 'initializationOptions': {'bundles': [str(bundle)], 'settings': {'java': {'import': {'gradle': {'enabled': False}, 'maven': {'enabled': False}}}}}})
commands = init['capabilities']['executeCommandProvider']['commands']
assert 'openidea.java.methodReferenceDefinition' in commands, commands
send({'jsonrpc': '2.0', 'method': 'initialized', 'params': {}})
for name, text in sources.items():
send({'jsonrpc': '2.0', 'method': 'textDocument/didOpen', 'params': {'textDocument': {'uri': uri(name), 'languageId': 'java', 'version': 1, 'text': text}}})
request('java/buildWorkspace', True)
failed = []
lines = sources['Main.java'].splitlines()
for line_needle, needle, at, expected in CASES:
line = next(i for i, t in enumerate(lines) if line_needle in t)
column = lines[line].index(needle, lines[line].index(line_needle)) + at
got = request('workspace/executeCommand', {'command': 'openidea.java.methodReferenceDefinition', 'arguments': [uri('Main.java'), line, column]})
got = [where(l) for l in got or []]
ok = got == expected
if not ok:
failed.append((line_needle, needle))
print('OK' if ok else 'FAIL', repr(line_needle), 'at', repr(needle), got)
# The functional interface's method is what the standard request answers for the inherited case.
line = next(i for i, t in enumerate(lines) if 'Child::getGoodsSpace' in t)
std = request('textDocument/definition', {'textDocument': {'uri': uri('Main.java')}, 'position': {'line': line, 'character': lines[line].index('getGoodsSpace') + 3}})
print('standard definition:', std)
assert not failed, failed
print('method-reference: all cases passed')
finally:
proc.terminate()
proc.wait(timeout=20)
print('Evidence:', work, file=sys.stderr)
+1 -1
Переглянути файл
@@ -105,7 +105,7 @@ dependencies = [
[[package]]
name = "openidea-plugin-openidea-ai-completion"
version = "0.1.0"
version = "0.1.1"
dependencies = [
"openidea-plugin",
"serde_json",
+1 -1
Переглянути файл
@@ -1,6 +1,6 @@
[package]
name = "openidea-plugin-openidea-ai-completion"
version = "0.1.0"
version = "0.1.1"
edition = "2024"
publish = false
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
fbaa75cf43cf1188b6b5f7621a94739a0f91ba4c8bd13b94fe78a2e8aa17bcc9
385b624ee9593d759a2ce22d4427edc0f06954d0e98f458a77d780e5a3dbe92a
+7 -2
Переглянути файл
@@ -1,10 +1,10 @@
id = "openidea.ai-completion"
name = "AI Completion"
version = "0.1.0"
version = "0.1.1"
description = "Inline code suggestions (ghost text) from a local model (Ollama) or OpenAI, as you type."
authors = ["OpenIDEA contributors"]
license = "Apache-2.0"
change-notes = "0.1.0 — first release: local (Ollama) and OpenAI backends; the key stays in the system keychain."
change-notes = "0.1.1 — say why no suggestions appear (network access, missing model, Ollama not running) and choose the model with AI Completion: Set Model. 0.1.0 — first release: local (Ollama) and OpenAI backends; the key stays in the system keychain."
categories = ["ai"]
engines.openidea = "^1.0"
wasm = "dist/plugin.wasm"
@@ -43,3 +43,8 @@ category = "AI Completion"
id = "set-endpoint"
title = "AI Completion: Set Endpoint URL"
category = "AI Completion"
[[contributes.commands]]
id = "set-model"
title = "AI Completion: Set Model"
category = "AI Completion"
+114 -6
Переглянути файл
@@ -22,6 +22,8 @@ const SUFFIX_CHARS: usize = 1000;
pub struct AiCompletion {
/// Why the last request failed, so it is logged once rather than per keystroke.
last_error: Option<String>,
/// The last failure shown to the user, so a notice is not repeated.
last_notice: Option<String>,
}
struct Config {
@@ -48,6 +50,34 @@ fn config() -> Config {
Config { endpoint, model, openai, enabled: get("enabled").as_deref() != Some("false") }
}
/// What to tell the user about a failed request: why, and what to do.
pub fn advice(endpoint: &str, model: &str, openai: bool, failure: &Result<String, Error>) -> String {
match failure {
Err(Error::Denied(_)) => format!(
"AI Completion may not connect to {endpoint}. Allow its network access in Settings › Plugins › AI Completion."
),
Ok(text) if !openai && text.starts_with("HTTP 404") => format!(
"The model {model} is not available at {endpoint}. Run `ollama pull {model}`, or choose an installed model with AI Completion: Set Model."
),
Err(Error::Failed(e)) if e.contains("timed out") => format!(
"{endpoint} took too long to answer; the model may still be loading, or be too large for this machine."
),
Err(Error::Failed(e)) if !openai => format!("Could not reach Ollama at {endpoint} ({e}). Is it running?"),
Ok(text) => format!("{endpoint} answered {text}"),
Err(e) => format!("Could not reach {endpoint}: {e}"),
}
}
/// The command's argument, or what the user types (pre-filled with `current`);
/// `None` when dismissed.
fn arg_or_input(arg: Option<&str>, prompt: &str, current: &str) -> Result<Option<String>, Error> {
let value = match arg {
Some(a) => Some(a.to_owned()),
None => host::input(prompt, Some(current))?,
};
Ok(value.map(|v| v.trim().to_owned()).filter(|v| !v.is_empty()))
}
/// The last `max` characters of `s` (on a char boundary).
fn tail(s: &str, max: usize) -> &str {
match s.char_indices().rev().nth(max.saturating_sub(1)) {
@@ -112,14 +142,21 @@ impl Providers for AiCompletion {
// Superseded by the next keystroke: nothing to report.
Err(Error::Cancelled) => None,
other => {
let msg = match other {
Ok(r) => format!("HTTP {}: {}", r.status, head(&r.text(), 200)),
let failure = other.map(|r| format!("HTTP {}: {}", r.status, head(&r.text(), 200)));
let msg = match &failure {
Ok(m) => m.clone(),
Err(e) => e.to_string(),
};
if self.last_error.as_ref() != Some(&msg) {
host::log(LogLevel::Warn, &format!("{}: {msg}", c.endpoint));
self.last_error = Some(msg);
}
// Otherwise a failure only shows in the IDE log, where nobody looks.
let notice = advice(&c.endpoint, &c.model, c.openai, &failure);
if self.last_notice.as_ref() != Some(&notice) {
host::notify(NotificationLevel::Warning, "AI Completion", &notice);
self.last_notice = Some(notice);
}
None
}
}
@@ -144,11 +181,23 @@ impl Plugin for AiCompletion {
}
}
"set-endpoint" => {
let url = arg.map(str::trim).filter(|u| u.starts_with("http://") || u.starts_with("https://"));
let url = url.ok_or("give the endpoint URL, e.g. http://localhost:11434")?;
storage::set("endpoint", url)?;
let Some(url) = arg_or_input(arg, "Endpoint URL (e.g. http://localhost:11434)", &config().endpoint)?
else {
return Ok(None);
};
if !(url.starts_with("http://") || url.starts_with("https://")) {
return Err("give the endpoint URL, e.g. http://localhost:11434".into());
}
storage::set("endpoint", &url)?;
format!("Using {url}.")
}
"set-model" => {
let Some(model) = arg_or_input(arg, "Model (as `ollama list` shows it)", &config().model)? else {
return Ok(None);
};
storage::set("model", &model)?;
format!("Using the model {model}.")
}
"toggle" => {
let enabled = !config().enabled;
storage::set("enabled", if enabled { "true" } else { "false" })?;
@@ -156,6 +205,8 @@ impl Plugin for AiCompletion {
}
_ => return Err(Error::NotFound(format!("command {id}"))),
};
// A new setting may fix (or change) the failure: tell again.
self.last_notice = None;
host::notify(NotificationLevel::Info, "AI Completion", &msg);
Ok(Some(msg))
}
@@ -228,7 +279,7 @@ mod tests {
}
#[test]
fn quiet_when_cancelled_denied_or_mid_word() {
fn quiet_when_cancelled_or_mid_word() {
let host = MockHost::install().with_capabilities(&["storage"]);
let mut p = AiCompletion::default();
assert!(p.inline_completion(&doc("let x = "), Position::new(0, 8)).is_none(), "net denied");
@@ -243,4 +294,61 @@ mod tests {
assert!(p.inline_completion(&doc("x"), Position::new(0, 1)).is_none());
assert_eq!(host2.requests().len(), 1, "disabled: no request");
}
#[test]
fn tells_the_user_why_once_and_what_to_do() {
// Installed without the optional network permission (the default for it).
let host = MockHost::install().with_capabilities(&["storage"]);
let mut p = AiCompletion::default();
assert!(p.inline_completion(&doc("let x = "), Position::new(0, 8)).is_none());
assert!(p.inline_completion(&doc("let x = 1"), Position::new(0, 9)).is_none());
let notes = host.notifications();
assert_eq!(notes.len(), 1, "once, not per keystroke: {notes:?}");
assert!(notes[0].body.contains("Settings › Plugins › AI Completion"), "{}", notes[0].body);
// A model that is not pulled: Ollama answers 404.
let host = MockHost::install().with_capabilities(&["storage", "net:localhost"]);
host.on_fetch(|_| {
Ok(HttpResponse {
status: 404,
headers: vec![],
body: br#"{"error":{"message":"model \"qwen2.5-coder:1.5b\" not found, try pulling it first"}}"#
.to_vec(),
})
});
assert!(p.inline_completion(&doc("let x = "), Position::new(0, 8)).is_none());
let body = &host.notifications()[0].body;
assert!(body.contains("ollama pull qwen2.5-coder:1.5b") && body.contains("Set Model"), "{body}");
// Ollama not running.
host.on_fetch(|_| Err(Error::Failed("connection refused".into())));
assert!(p.inline_completion(&doc("let x = "), Position::new(0, 8)).is_none());
assert!(host.notifications()[1].body.contains("Is it running?"));
host.on_fetch(|_| Err(Error::Failed("error sending request: operation timed out".into())));
assert!(p.inline_completion(&doc("let x = "), Position::new(0, 8)).is_none());
assert!(host.notifications()[2].body.contains("took too long"));
}
#[test]
fn set_model_takes_an_argument_or_asks() {
let host = MockHost::install().with_capabilities(&["storage", "net:localhost"]);
host.on_fetch(|_| {
Ok(HttpResponse { status: 200, headers: vec![], body: br#"{"choices":[{"text":"x"}]}"#.to_vec() })
});
let mut p = AiCompletion::default();
p.run_command("set-model", &host.invocation(), Some(" qwen2.5-coder:7b ")).unwrap();
assert_eq!(config().model, "qwen2.5-coder:7b");
// From the command palette: no argument, so it asks.
host.answer_next_prompt(Some(&["codellama:7b-code"]));
p.run_command("set-model", &host.invocation(), None).unwrap();
p.inline_completion(&doc("let x = "), Position::new(0, 8)).unwrap();
let body: Value = serde_json::from_slice(host.requests()[0].body.as_ref().unwrap()).unwrap();
assert_eq!(body["model"], "codellama:7b-code");
// Dismissed: nothing changes.
assert_eq!(p.run_command("set-model", &host.invocation(), None).unwrap(), None);
assert_eq!(config().model, "codellama:7b-code");
host.answer_next_prompt(Some(&["http://127.0.0.1:11434"]));
p.run_command("set-endpoint", &host.invocation(), None).unwrap();
assert_eq!(config().endpoint, "http://127.0.0.1:11434");
}
}
+64
Переглянути файл
@@ -0,0 +1,64 @@
// @vitest-environment node
import { describe, expect, it } from "vitest";
import { NIGHTLY_ENDPOINT, msiVersion, nightlyVersion, setNightlyConfig } from "./nightly-prepare.ts";
describe("nightlyVersion", () => {
it("is the next patch's nightly once the current version is released", () => {
expect(nightlyVersion("0.1.55", true, "20261130", new Set(["v0.1.55"]))).toBe("0.1.56-nightly.20261130");
});
it("is the current version's nightly while that is not released", () => {
expect(nightlyVersion("0.1.56", false, "20261130", new Set())).toBe("0.1.56-nightly.20261130");
});
it("numbers further nightlies of the same day, which sort after the first", () => {
const tags = new Set(["v0.1.56-nightly.20261130", "v0.1.56-nightly.20261130.2"]);
expect(nightlyVersion("0.1.55", true, "20261130", tags)).toBe("0.1.56-nightly.20261130.3");
});
it("refuses a malformed date or version", () => {
expect(() => nightlyVersion("0.1.55", true, "2026-11-30", new Set())).toThrow();
expect(() => nightlyVersion("0.1", true, "20261130", new Set())).toThrow();
});
});
describe("msiVersion", () => {
it("is the last release with the build number", () => {
expect(msiVersion("0.1.55", true, 42)).toBe("0.1.55.42");
expect(msiVersion("0.1.56", false, 42)).toBe("0.1.55.42");
expect(msiVersion("0.2.0", false, 42)).toBe("0.2.0.42");
});
it("refuses a build number MSI cannot hold", () => {
expect(() => msiVersion("0.1.55", true, 65536)).toThrow();
expect(() => msiVersion("0.1.55", true, Number.NaN)).toThrow();
});
});
describe("setNightlyConfig", () => {
it("sets the version, the nightly manifest and the MSI version, keeping the rest", () => {
const json = JSON.stringify(
{
version: "0.1.55",
bundle: { targets: "all", macOS: { minimumSystemVersion: "11.0" } },
plugins: { updater: { pubkey: "key", endpoints: ["https://example.com/latest.json"] } },
},
null,
2,
);
const config = JSON.parse(setNightlyConfig(json, "0.1.56-nightly.20261130", "0.1.55.42"));
expect(config.version).toBe("0.1.56-nightly.20261130");
expect(config.plugins.updater).toEqual({ pubkey: "key", endpoints: [NIGHTLY_ENDPOINT] });
expect(config.bundle).toEqual({
targets: "all",
macOS: { minimumSystemVersion: "11.0" },
windows: { wix: { version: "0.1.55.42" } },
});
});
it("refuses a config without the updater", () => {
expect(() =>
setNightlyConfig(JSON.stringify({ version: "0.1.55" }), "0.1.56-nightly.20261130", "0.1.55.1"),
).toThrow();
});
});
+107
Переглянути файл
@@ -0,0 +1,107 @@
/**
* Prepares a nightly build commit (nightly.yml): `node scripts/nightly-prepare.ts --date 20261130
* --build 42` sets the app version to the next patch's nightly, `0.1.56-nightly.20261130` (`.2`,
* `.3`… when that tag already exists), in Cargo.toml, package.json and tauri.conf.json, points the
* updater at the nightly channel's manifest, gives the MSI installer a numeric version, refreshes
* Cargo.lock and the plugin API snapshot, and prints the version (also `version=` in
* $GITHUB_OUTPUT). The next patch is the current version's when that is already released (its
* `v` tag exists), else the current version itself.
*/
import { spawnSync } from "node:child_process";
import { appendFileSync, readFileSync } from "node:fs";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import {
cargoVersion,
edit,
parseVersion,
setCargoVersion,
setJsonVersion,
syncApiSnapshot,
} from "./release-prepare.ts";
/** The nightly channel's updater manifest: the rolling `nightly` release (nightly.yml). */
export const NIGHTLY_ENDPOINT = "https://github.com/l0ng-ai/openidea/releases/download/nightly/latest.json";
function bump(version: string): string {
const [major, minor, patch] = version.split(".").map(Number);
return `${major}.${minor}.${patch! + 1}`;
}
/** The nightly's version: the first of `<next>-nightly.<date>`, `….2`, `….3` whose tag is not in `tags`. */
export function nightlyVersion(current: string, released: boolean, date: string, tags: Set<string>): string {
if (!/^\d{8}$/.test(date)) throw new Error(`expected a date like 20261130, got ${date}`);
const base = `${released ? bump(parseVersion(current)) : parseVersion(current)}-nightly.${date}`;
for (let n = 1; ; n++) {
const version = n === 1 ? base : `${base}.${n}`;
if (!tags.has(`v${version}`)) return version;
}
}
/**
* The MSI ProductVersion (`major.minor.patch.build`, numbers only): the last released version
* with the build number, so a nightly sorts after that release and before the next.
*/
export function msiVersion(current: string, released: boolean, build: number): string {
if (!Number.isInteger(build) || build < 0 || build > 65535) throw new Error(`build ${build} is not 0–65535`);
const [major, minor, patch] = parseVersion(current).split(".").map(Number);
const last = released || patch === 0 ? patch : patch! - 1;
return `${major}.${minor}.${last}.${build}`;
}
/** tauri.conf.json for a nightly: its version, the nightly updater manifest and the MSI version. */
export function setNightlyConfig(json: string, version: string, msi: string): string {
const config = JSON.parse(setJsonVersion(json, version)) as {
plugins?: { updater?: { endpoints?: string[] } };
bundle?: { windows?: { wix?: { version?: string } } };
};
if (!config.plugins?.updater) throw new Error("tauri.conf.json: no plugins.updater");
config.plugins.updater.endpoints = [NIGHTLY_ENDPOINT];
config.bundle ??= {};
config.bundle.windows ??= {};
config.bundle.windows.wix = { ...config.bundle.windows.wix, version: msi };
return `${JSON.stringify(config, null, 2)}\n`;
}
function arg(name: string): string {
const index = process.argv.indexOf(`--${name}`);
const value = index >= 0 ? process.argv[index + 1] : undefined;
if (!value) throw new Error(`missing --${name}`);
return value;
}
function git(root: string, ...args: string[]): string {
const result = spawnSync("git", args, { cwd: root, encoding: "utf8" });
if (result.status !== 0) throw new Error(`git ${args.join(" ")}: ${result.stderr}`);
return result.stdout;
}
function main() {
const root = fileURLToPath(new URL("..", import.meta.url));
const date = arg("date");
const build = Number(arg("build"));
const current = cargoVersion(readFileSync(join(root, "Cargo.toml"), "utf8"));
const tags = new Set(git(root, "tag", "--list", "v*").split("\n").filter(Boolean));
const released = tags.has(`v${current}`);
const version = nightlyVersion(current, released, date, tags);
const msi = msiVersion(current, released, build);
edit(join(root, "Cargo.toml"), (text) => setCargoVersion(text, version));
edit(join(root, "package.json"), (text) => setJsonVersion(text, version));
edit(join(root, "src-tauri/tauri.conf.json"), (text) => setNightlyConfig(text, version, msi));
const cargo = spawnSync("cargo", ["update", "--workspace"], { cwd: root, stdio: "inherit" });
if (cargo.status !== 0) throw new Error("cargo update --workspace failed");
syncApiSnapshot(root);
if (process.env.GITHUB_OUTPUT) appendFileSync(process.env.GITHUB_OUTPUT, `version=${version}\n`);
console.log(version);
}
if (process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]) {
try {
main();
} catch (error) {
console.error(`nightly-prepare: ${error instanceof Error ? error.message : String(error)}`);
process.exit(1);
}
}
+2
Переглянути файл
@@ -26,6 +26,8 @@ impl ApplicationFocus {
pub fn changed(app: &tauri::AppHandle, focused: bool) {
let generation = app.state::<ApplicationFocus>().changed(focused);
if focused {
#[cfg(target_os = "macos")]
crate::window_groups::detach_deferred(app);
return;
}
let app = app.clone();
+29 -8
Переглянути файл
@@ -636,11 +636,18 @@ fn config_endpoints<R: tauri::Runtime>(app: &AppHandle<R>) -> Vec<String> {
.unwrap_or_default()
}
/// Nightly builds (`x.y.z-nightly.…`, nightly.yml) update from the nightly channel's manifest
/// only: the CNB mirror carries stable releases.
fn is_nightly(version: &str) -> bool {
version.contains("-nightly.")
}
/// The endpoints tried in order: `source` first, the other source when it fails or has
/// no manifest. Bundles are signed, so either source's manifest and downloads verify.
/// No official endpoint (a build without updates) means no mirror either.
fn source_endpoints(official: Vec<String>, source: UpdateSource) -> Vec<String> {
if official.is_empty() {
/// No official endpoint (a build without updates) means no mirror either, and a nightly
/// build of `version` has no mirror.
fn source_endpoints(official: Vec<String>, source: UpdateSource, version: &str) -> Vec<String> {
if official.is_empty() || is_nightly(version) {
return official;
}
let mirror = vec![CNB_ENDPOINT.to_string()];
@@ -669,7 +676,7 @@ pub(crate) fn updater(app: &AppHandle, source: UpdateSource) -> IdeResult<Option
}
let endpoints = match update_endpoint_env() {
Some(url) => vec![url],
None => source_endpoints(config_endpoints(app), source),
None => source_endpoints(config_endpoints(app), source, env!("CARGO_PKG_VERSION")),
};
let endpoints = endpoints
.iter()
@@ -867,7 +874,7 @@ pub async fn app_release_notes(
) -> IdeResult<Option<BTreeMap<String, String>>> {
let endpoints = match update_endpoint_env() {
Some(url) => vec![url],
None => source_endpoints(config_endpoints(&app), source),
None => source_endpoints(config_endpoints(&app), source, env!("CARGO_PKG_VERSION")),
};
let client = ide_http::client::shared()?;
for endpoint in endpoints {
@@ -1005,10 +1012,24 @@ mod tests {
#[test]
fn chosen_source_is_tried_first_and_the_other_after_it() {
let github = "https://github.com/l0ng-ai/openidea/releases/latest/download/latest.json".to_string();
assert_eq!(source_endpoints(vec![github.clone()], UpdateSource::Github), [github.clone(), CNB_ENDPOINT.into()]);
assert_eq!(source_endpoints(vec![github.clone()], UpdateSource::Cnb), [CNB_ENDPOINT.into(), github]);
assert_eq!(
source_endpoints(vec![github.clone()], UpdateSource::Github, "0.1.55"),
[github.clone(), CNB_ENDPOINT.into()]
);
assert_eq!(source_endpoints(vec![github.clone()], UpdateSource::Cnb, "0.1.55"), [CNB_ENDPOINT.into(), github]);
// A build without an update endpoint stays without one.
assert!(source_endpoints(Vec::new(), UpdateSource::Cnb).is_empty());
assert!(source_endpoints(Vec::new(), UpdateSource::Cnb, "0.1.55").is_empty());
}
#[test]
fn nightly_builds_update_from_the_nightly_manifest_only() {
let nightly = "https://github.com/l0ng-ai/openidea/releases/download/nightly/latest.json".to_string();
for source in [UpdateSource::Github, UpdateSource::Cnb] {
assert_eq!(
source_endpoints(vec![nightly.clone()], source, "0.1.56-nightly.20261130"),
std::slice::from_ref(&nightly)
);
}
}
#[test]
+10
Переглянути файл
@@ -114,6 +114,16 @@ pub fn sync_tab_group(
})
}
pub fn fullscreen_in_background(window: &WebviewWindow) -> bool {
let target = window.clone();
on_main(window, move || {
let active =
MainThreadMarker::new().is_some_and(|mtm| objc2_app_kit::NSApplication::sharedApplication(mtm).isActive());
!active && native(&target).is_some_and(|w| w.styleMask().contains(objc2_app_kit::NSWindowStyleMask::FullScreen))
})
.unwrap_or(false)
}
/// Takes `window` out of its tab group into a window of its own; in full screen, a Space of its own.
pub fn move_tab_to_new_window(window: &WebviewWindow) -> tauri::Result<()> {
let target = window.clone();
+18
Переглянути файл
@@ -201,9 +201,19 @@ pub fn merge(app: &AppHandle, caller: &str) -> IdeResult<()> {
select(app, caller, caller)
}
#[cfg(target_os = "macos")]
static DEFERRED_DETACH: parking_lot::Mutex<Vec<String>> = parking_lot::Mutex::new(Vec::new());
pub fn detach(app: &AppHandle, caller: &str) -> IdeResult<()> {
let err = |e: tauri::Error| IdeError::internal(e.to_string());
let state = app.state::<WindowsState>();
#[cfg(target_os = "macos")]
if state.groups.lock().group(caller).is_some()
&& app.get_webview_window(caller).is_some_and(|w| crate::macos::fullscreen_in_background(&w))
{
DEFERRED_DETACH.lock().push(caller.to_owned());
return Ok(());
}
let Some(next) = state.groups.lock().detach(caller) else {
changed(app);
return Ok(());
@@ -234,6 +244,14 @@ pub fn detach(app: &AppHandle, caller: &str) -> IdeResult<()> {
Ok(())
}
#[cfg(target_os = "macos")]
pub fn detach_deferred(app: &AppHandle) {
let labels = std::mem::take(&mut *DEFERRED_DETACH.lock());
for label in labels {
let _ = detach(app, &label);
}
}
pub fn destroyed(app: &AppHandle, caller: &str) {
let Some(state) = app.try_state::<WindowsState>() else { return };
let next = state.groups.lock().detach(caller);
+6
Переглянути файл
@@ -11748,6 +11748,12 @@ export type NavigationFiles = {
paths: IpcPath[],
indexing: boolean,
extensions: string[],
/**
* In-scope files matching `extensions`; `paths` holds the first
* `MAX_NAVIGATION_FILES` of them.
*/
total: number,
truncated: boolean,
};
export type NavigationResult = {
+5
Переглянути файл
@@ -918,6 +918,11 @@ function outsideProject(path: string): boolean {
/** Files outside the project that code navigation opened: library sources, shown read-only. */
const navigatedLibraryFiles = new Set<string>();
/** Marks `path` as a library source again, for a tab restored from a saved session. */
export function markLibraryFile(path: string): void {
navigatedLibraryFiles.add(path);
}
/**
* Opens a code location a language server or the index answered (a declaration, an
* implementation, a documentation link) and selects `selection`. A file outside the project is a
+70
Переглянути файл
@@ -3,8 +3,10 @@ import { EditorSelection, EditorState, Transaction, type Extension } from "@code
import { indentService, indentUnit } from "@codemirror/language";
import { EditorView } from "@codemirror/view";
import { commands } from "@/platform/ipc";
import { usePlatform } from "@/platform/platformInfo";
import { EDITOR_EXTRA_DEFAULTS, type LineClipboardOptions } from "@/platform/editorSettings";
import { isRemoteWindow } from "@/platform/remote";
import { useWebConnection } from "@/platform/webBridge";
import {
clearClipboardHistory,
clipboardHistory,
@@ -27,6 +29,7 @@ const views: EditorView[] = [];
beforeEach(() => {
clearClipboardHistory();
vi.stubGlobal("__TAURI_INTERNALS__", {});
usePlatform.setState({ os: "windows" }); // the WebView menu path; macOS reads natively
Object.defineProperty(document, "execCommand", { configurable: true, value: vi.fn(() => false) });
Object.defineProperty(document, "queryCommandSupported", { configurable: true, value: vi.fn(() => false) });
});
@@ -211,6 +214,73 @@ it.each([
expect(create.mock.calls[0]![0]).toMatch(hasFile ? /assets\/image\.png$/ : /assets\/image-\d{8}-\d{6}\.png$/);
});
describe("macOS menu paste into Markdown reads the clipboard natively", () => {
// WebKit's execCommand("paste") from a menu makes macOS show a "Paste" callout.
function markdownView() {
usePlatform.setState({ os: "macos" });
const view = new EditorView({
extensions: [
clipboardDocumentPath.of("/p/a.md"),
clipboardFilesExtension,
markdownImages({ path: "/p/a.md", folder: "assets", pattern: "image-{timestamp}" }),
],
parent: document.body,
});
views.push(view);
vi.mocked(document.queryCommandSupported).mockReturnValue(true);
return view;
}
it("saves a copied image without the webview's paste", async () => {
vi.spyOn(commands, "clipboardFileList").mockResolvedValue({ status: "ok", data: [] });
vi.spyOn(commands, "clipboardImage").mockResolvedValue({ status: "ok", data: "data:image/png;base64,iVBORw==" });
const create = vi.spyOn(commands, "fsCreateFileBytes").mockResolvedValue({ status: "ok", data: null });
const view = markdownView();
await pasteEditorClipboard(view);
await vi.waitFor(() => expect(view.state.doc.toString()).toMatch(/^!\[\]\(assets\/image-\d{8}-\d{6}\.png\)$/));
expect(create.mock.calls[0]![1]).toBe("iVBORw==");
expect(document.execCommand).not.toHaveBeenCalled();
});
it("keeps the execCommand paste in web mode, where the backend has no clipboard", async () => {
useWebConnection.setState({ active: true });
try {
const list = vi.spyOn(commands, "clipboardFileList");
vi.mocked(document.execCommand).mockReturnValue(true);
await pasteEditorClipboard(markdownView());
expect(document.execCommand).toHaveBeenCalledWith("paste");
expect(list).not.toHaveBeenCalled();
} finally {
useWebConnection.setState({ active: false });
}
});
it("pastes the text when the clipboard holds no image", async () => {
vi.spyOn(commands, "clipboardFileList").mockResolvedValue({ status: "ok", data: [] });
vi.spyOn(commands, "clipboardImage").mockResolvedValue({ status: "ok", data: null });
vi.spyOn(commands, "clipboardText").mockResolvedValue({ status: "ok", data: "plain" });
const view = markdownView();
await pasteEditorClipboard(view);
expect(view.state.doc.toString()).toBe("plain");
expect(document.execCommand).not.toHaveBeenCalled();
});
it("embeds a copied image file like the paste event, not as a path", async () => {
vi.spyOn(commands, "clipboardFileList").mockResolvedValue({ status: "ok", data: ["/src/pic.png"] });
const image = vi.spyOn(commands, "clipboardImage");
vi.stubGlobal("__TAURI_INTERNALS__", {
invoke: vi.fn(async () => "data:image/png;base64,iVBORw=="),
});
const create = vi.spyOn(commands, "fsCreateFileBytes").mockResolvedValue({ status: "ok", data: null });
const view = markdownView();
await pasteEditorClipboard(view);
await vi.waitFor(() => expect(view.state.doc.toString()).toBe("![](assets/pic.png)"));
expect(create.mock.calls[0]![0]).toMatch(/assets\/pic\.png$/);
expect(image).not.toHaveBeenCalled();
expect(document.execCommand).not.toHaveBeenCalled();
});
});
it("does not insert into a read-only editor", async () => {
const list = vi.spyOn(commands, "clipboardFileList");
const view = new EditorView({ extensions: [clipboardFilesExtension, EditorState.readOnly.of(true)] });
+15 -2
Переглянути файл
@@ -1,10 +1,13 @@
import { EditorSelection, Facet, Prec, type EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { pasteClipboardFiles, readClipboardText } from "@/platform/clipboard";
import { call, commands, isTauri } from "@/platform/ipc";
import { usePlatform } from "@/platform/platformInfo";
import { isWebMode } from "@/platform/webBridge";
import type { LinePasteMode } from "@/platform/editorSettings";
import { isRemoteWindow } from "@/platform/remote";
import { isLinewiseClipboardText } from "../clipboardHistory";
import { isMarkdown, relativeImagePath } from "./markdownImages";
import { isMarkdown, pasteMarkdownImages, relativeImagePath } from "./markdownImages";
export const clipboardDocumentPath = Facet.define<string, string>({ combine: (paths) => paths[0] ?? "" });
@@ -125,9 +128,19 @@ export function pasteEditorText(view: EditorView, text: string) {
export async function pasteEditorClipboard(view: EditorView) {
if (!view.dom.isConnected || view.state.readOnly) return;
const markdown = isMarkdown(view.state.facet(clipboardDocumentPath));
// macOS WebKit asks the user to confirm execCommand("paste") from the editor context menu with a "Paste" callout
// (the app-menu Edit > Paste is a native paste: selector and never gets here); the
// backend reads the image (or copied image files) without asking, so text then takes the native path below.
const native = markdown && isTauri() && !isWebMode() && usePlatform.getState().os === "macos";
try {
if (native) {
const paths: string[] = await call(commands.clipboardFileList()).catch(() => []);
const image = paths.length ? null : await call(commands.clipboardImage()).catch(() => null);
if (pasteMarkdownImages(view, image ?? paths)) return;
}
// Successful native paste preserves image blobs and may complete after execCommand returns.
if (isMarkdown(view.state.facet(clipboardDocumentPath)) && document.queryCommandSupported("paste")) {
if (markdown && !native && document.queryCommandSupported("paste")) {
view.focus();
if (document.execCommand("paste")) return;
}
+42 -2
Переглянути файл
@@ -1,12 +1,12 @@
import { EditorSelection, EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { insertNewlineAndIndent } from "@codemirror/commands";
import { LanguageDescription, type Language } from "@codemirror/language";
import { LanguageDescription, indentUnit, type Language } from "@codemirror/language";
import { describe, expect, it } from "vitest";
import { getIndentation } from "@codemirror/language";
import { highlightTree, tagHighlighter, tags as t } from "@lezer/highlight";
import { logWarning } from "./highlight";
import { fencedCodeMode, findLanguageDescription, loadSupport } from "./languages";
import { commentTokens, fencedCodeMode, findLanguageDescription, loadSupport } from "./languages";
describe("language modes", () => {
it("highlights Julia declarations, calls, types, macros and literals without semantic tokens", async () => {
@@ -765,3 +765,43 @@ describe("language modes", () => {
expect(found).not.toContain("yes:keyword");
});
});
describe("Slint indentation", () => {
it("indents element blocks by their braces under the C highlighting mode", async () => {
const support = await loadSupport(findLanguageDescription("C", "/p/app.slint")!);
const slint = commentTokens({
id: "slint",
name: "Slint",
extensions: ["slint"],
uiMode: "C",
lineComment: "//",
blockComment: ["/*", "*/"],
indent: { tabSize: 4, insertSpaces: true },
});
const enter = (doc: string, at = doc.length) => {
const view = new EditorView({
state: EditorState.create({
doc,
selection: EditorSelection.cursor(at),
extensions: [support!, slint, indentUnit.of(" ")],
}),
parent: document.body,
});
insertNewlineAndIndent(view);
const out = view.state.doc.toString();
view.destroy();
return out;
};
const app = "export component App inherits Window {";
expect(enter(app)).toBe(`${app}\n `);
expect(enter(`${app}}`, app.length)).toBe(`${app}\n \n}`);
expect(enter(`${app}\n width: 100px;`)).toBe(`${app}\n width: 100px;\n `);
// After a child element closes, the next line stays at the child's level.
expect(enter(`${app}\n Text {\n text: "hi";\n }`)).toBe(
`${app}\n Text {\n text: "hi";\n }\n `,
);
expect(enter(`${app}\n Text {\n }\n Rectangle {`)).toBe(
`${app}\n Text {\n }\n Rectangle {\n `,
);
});
});
+8 -1
Переглянути файл
@@ -740,6 +740,13 @@ const NO_INDENT_LANGS = new Set([
"gitattributes",
]);
/**
* Languages highlighted by a borrowed mode whose own indentation doesn't fit them: Slint's
* element blocks (`Text { … }` without a `;`) read as unfinished C statements, so Enter after
* one lands at the wrong column. These use the brace-based fallback indentation instead.
*/
const BRACE_INDENT_OVER_MODE = new Set(["slint"]);
function opensBlock(code: string, language: string | undefined): boolean {
if (!code) return false;
if (/[{([]$/.test(code)) return true;
@@ -779,7 +786,7 @@ function indentationCode(text: string, lineComment: string | undefined): string
*/
export function fallbackIndent(language?: string): Extension {
return indentService.of((cx, pos) => {
if (cx.state.facet(languageFacet)) return undefined;
if (cx.state.facet(languageFacet) && !BRACE_INDENT_OVER_MODE.has(language ?? "")) return undefined;
const lineComment = cx.state.languageDataAt<{ line?: string }>("commentTokens", pos)[0]?.line;
const stripComment = (text: string) => indentationCode(text, lineComment);
+28 -9
Переглянути файл
@@ -111,6 +111,29 @@ interface ImageOptions {
pattern: string;
}
type ImageSource = () => Promise<{ blob: Blob | string; name: string }>;
// OS paths belong to this client even in a remote project.
const fileSource =
(path: string): ImageSource =>
async () => ({ blob: await invokeLocal<string>("fs_read_image", { path }), name: path.replace(/^.*[\\/]/, "") });
const imageInserters = new WeakMap<EditorView, (sources: ImageSource[]) => void>();
/**
* Saves and links images the menu Paste read natively, as a paste event would: image files by path, or a
* raw clipboard image as a PNG data URL. False when `view` does not take images (not Markdown, read-only,
* or not image files).
*/
export function pasteMarkdownImages(view: EditorView, images: string[] | string): boolean {
const insert = imageInserters.get(view);
if (!insert || view.state.readOnly) return false;
if (typeof images === "string") insert([async () => ({ blob: images, name: "" })]);
else if (images.length && images.every((p) => IMAGE_FILE.test(p))) insert(images.map(fileSource));
else return false;
return true;
}
export function markdownImages(options: ImageOptions): Extension {
if (!isMarkdown(options.path)) return [];
return ViewPlugin.fromClass(
@@ -118,7 +141,9 @@ export function markdownImages(options: ImageOptions): Extension {
alive = true;
pending = new Set<{ from: number; to: number }>();
unregister: () => void;
readonly insertSources = (sources: ImageSource[]) => this.insert(sources);
constructor(readonly view: EditorView) {
imageInserters.set(view, this.insertSources);
this.unregister = registerFileDropHandler((paths, x, y) => {
const rect = view.dom.getBoundingClientRect();
if (
@@ -130,14 +155,7 @@ export function markdownImages(options: ImageOptions): Extension {
view.state.readOnly
)
return false;
this.insert(
paths.map((path) => async () => {
// OS paths belong to this client even in a remote project.
const url = await invokeLocal<string>("fs_read_image", { path });
return { blob: url, name: path.replace(/^.*[\\/]/, "") };
}),
view.posAtCoords({ x, y }) ?? view.state.selection.main.head,
);
this.insert(paths.map(fileSource), view.posAtCoords({ x, y }) ?? view.state.selection.main.head);
return true;
});
}
@@ -150,8 +168,9 @@ export function markdownImages(options: ImageOptions): Extension {
destroy() {
this.alive = false;
this.unregister();
if (imageInserters.get(this.view) === this.insertSources) imageInserters.delete(this.view);
}
insert(sources: Array<() => Promise<{ blob: Blob | string; name: string }>>, position?: number) {
insert(sources: ImageSource[], position?: number) {
const selection = this.view.state.selection.main;
const range = { from: position ?? selection.from, to: position ?? selection.to };
this.pending.add(range);
+13 -2
Переглянути файл
@@ -21,6 +21,8 @@ import {
_provideOpenEditorPaths,
_setActiveEditor,
focusedCellEditor,
isLibraryPath,
markLibraryFile,
shownLine,
type NavigationLocation,
} from "@/editor/api";
@@ -114,7 +116,14 @@ import {
import { EditorSlot, type SlotHost } from "./model/slot";
import { NavigationHistory } from "./model/navHistory";
import { EditHistory } from "./model/editHistory";
import { loadSession, restoreTabsState, serializeSession, storeSession, type FileViewState } from "./model/session";
import {
loadSession,
restoreTabsState,
serializeSession,
sessionLibraryFiles,
storeSession,
type FileViewState,
} from "./model/session";
import { docBackend, type DocBackend } from "./backend";
import { isClassFile } from "@/platform/classFiles";
import { isVirtualUri, virtualDocument } from "@/platform/virtualDocs";
@@ -663,7 +672,7 @@ export class EditorController implements SlotHost {
const kinds = useContributions.getState().editorKinds;
storeSession(
root,
serializeSession(useTabs.getState(), files, (input) => !!kinds.get(input.kind)?.restorable),
serializeSession(useTabs.getState(), files, (input) => !!kinds.get(input.kind)?.restorable, isLibraryPath),
);
}
@@ -700,6 +709,8 @@ export class EditorController implements SlotHost {
if (this.forgottenSessions.delete(root)) return;
const session = loadSession(root);
if (!session) return;
// Before the documents open: a library source opens read-only.
for (const path of sessionLibraryFiles(session)) markLibraryFile(path);
const state = restoreTabsState(session, fileKey);
const kinds = useContributions.getState().editorKinds;
for (const pane of Object.values(state.panes))
+12
Переглянути файл
@@ -14,6 +14,7 @@ import {
parseSession,
restoreTabsState,
serializeSession,
sessionLibraryFiles,
slashPath,
storeSession,
type EditorSession,
@@ -59,6 +60,17 @@ describe("editor session", () => {
expect(r.layout).toMatchObject({ kind: "split", dir: "column" });
});
it("remembers which file tabs are library sources", () => {
let s = initialTabsState();
s = open(s, "/p/main.swift");
s = open(s, "/tmp/sk/Swift.String.swiftinterface");
const library = (path: string) => path.endsWith(".swiftinterface");
const session = serializeSession(s, {}, undefined, library)!;
const parsed = parseSession(JSON.parse(JSON.stringify(session)))!;
expect(sessionLibraryFiles(parsed)).toEqual(["/tmp/sk/Swift.String.swiftinterface"]);
expect(sessionLibraryFiles(parseSession(JSON.parse(JSON.stringify(serializeSession(s, {})!)))!)).toEqual([]);
});
it("saves tabs of restorable editor kinds with their input", () => {
let s = initialTabsState();
s = open(s, "/p/a.ts");
+19 -1
Переглянути файл
@@ -18,6 +18,8 @@ export interface SessionTab {
input?: EditorInput;
pinned?: boolean;
preview?: boolean;
/** A library source (read-only), e.g. an SDK interface code navigation opened outside the project. */
library?: boolean;
}
export type SessionLayout =
@@ -43,11 +45,15 @@ const STORAGE_PREFIX = "openidea.editorSession.v1:";
const isFileTab = (t: Tab) => t.input.kind === "file" && !!t.input.path;
/** `restorable`: whether a non-file tab is saved (its kind asked for it). */
/**
* `restorable`: whether a non-file tab is saved (its kind asked for it). `library`: whether a
* file tab shows a library source, so it opens read-only again.
*/
export function serializeSession(
s: TabsState,
files: Record<string, FileViewState>,
restorable: (input: EditorInput) => boolean = () => false,
library: (path: string) => boolean = () => false,
): EditorSession | null {
const saved = (t: Tab) => isFileTab(t) || (t.input.kind !== "file" && restorable(t.input));
const walk = (n: LayoutNode): SessionLayout | null => {
@@ -66,6 +72,7 @@ export function serializeSession(
...(isFileTab(t) ? { path: t.input.path! } : { input: { ...t.input } }),
...(t.pinned ? { pinned: true } : {}),
...(t.preview ? { preview: true } : {}),
...(isFileTab(t) && library(t.input.path!) ? { library: true } : {}),
})),
active,
};
@@ -151,6 +158,17 @@ export function parseSession(raw: unknown): EditorSession | null {
};
}
/** Paths of the file tabs saved as library sources. */
export function sessionLibraryFiles(session: EditorSession): string[] {
const out: string[] = [];
const walk = (l: SessionLayout) =>
l.kind === "pane"
? l.tabs.forEach((t) => t.library === true && t.path && out.push(t.path))
: l.children.forEach(walk);
walk(session.layout);
return out;
}
let seq = 0;
const id = (p: string) => `${p}r${++seq}`;
+2
Переглянути файл
@@ -399,6 +399,8 @@ function PaneView({ paneId }: { paneId: string }) {
onCloseOthers={(id) => void ctrl.closeOthers(paneId, id)}
onTogglePin={(id) => ctrl.togglePin(paneId, id)}
closeOnShiftClick
// IDEA: a double click on the strip's empty part maximizes the editor, as on a tab.
onBlankDoubleClick={() => void executeAction("toolwindow.hideAll")}
onDoubleClick={(id) => {
// IDEA: a preview tab becomes a regular one; any other tab maximizes the editor.
if (pane.tabs.find((t) => t.id === id)?.preview) ctrl.keepTab(paneId, id);
+57
Переглянути файл
@@ -283,6 +283,63 @@ describe("applying completions", () => {
expect(view.state.selection.main.head).toBe(14);
});
it.each([
{ doc: " @Over|\n", prefix: "Over", label: "Override", expected: " @Override|\n" },
{ doc: '@Supp|("unused")', prefix: "Supp", label: "SuppressWarnings", expected: '@SuppressWarnings|("unused")' },
{ doc: "@java.lang.Over|", prefix: "Over", label: "Override", expected: "@java.lang.Override|" },
{
doc: "@Over| public void run() {}",
prefix: "Over",
label: "Override",
expected: "@Override| public void run() {}",
},
{
doc: "@Over|public void run() {}",
prefix: "Over",
label: "Override",
expected: "@Override |public void run() {}",
},
{ doc: "implements Run|\n", prefix: "Run", label: "Runnable", expected: "implements Runnable |\n" },
])("applies a Java interface completion in $doc", ({ doc, prefix, label, expected }) => {
const { view, req, pos } = setup(doc);
const suggestion = item({ label, kind: "interface", insertText: `${label} `, isSnippet: true });
apply(view, makeCompletion(suggestion, { ...req, language: "java" }), pos - prefix.length);
expect(view.state.doc.toString()).toBe(expected.replace("|", ""));
expect(view.state.selection.main.head).toBe(expected.indexOf("|"));
});
it("replaces a Java annotation name before its existing arguments with Tab", () => {
const { view, req, pos } = setup('@Sup|pressWarnings("unused")');
const suggestion = item({
label: "SuppressWarnings",
kind: "interface",
insertText: "SuppressWarnings ",
isSnippet: true,
replaceRange: { start: { line: 0, col: 1 }, end: { line: 0, col: pos } },
replaceRangeTab: { start: { line: 0, col: 1 }, end: { line: 0, col: 17 } },
});
applyLspCompletion(view, makeCompletion(suggestion, { ...req, language: "java" }), 1, pos, "replace");
expect(view.state.doc.toString()).toBe('@SuppressWarnings("unused")');
expect(view.state.selection.main.head).toBe(17);
});
it("keeps spacing in a Java annotation attribute completion", () => {
const { view, req } = setup("@Tag(va|)");
const suggestion = item({ label: "value", kind: "field", insertText: "value = ", isSnippet: true });
apply(view, makeCompletion(suggestion, { ...req, language: "java" }), 5);
expect(view.state.doc.toString()).toBe("@Tag(value = )");
expect(view.state.selection.main.head).toBe(13);
});
it("accounts for what follows each Java annotation when completing at several carets", () => {
const { view, req } = setup("@Ov|\n@Ovpublic void run() {}", "", [EditorState.allowMultipleSelections.of(true)]);
view.dispatch({ selection: EditorSelection.create([EditorSelection.cursor(3), EditorSelection.cursor(7)]) });
const suggestion = item({ label: "Override", kind: "interface", insertText: "Override ", isSnippet: true });
applyLspCompletion(view, makeCompletion(suggestion, { ...req, language: "java" }), 1, 3, "insert");
expect(view.state.doc.toString()).toBe("@Override\n@Override public void run() {}");
expect(view.state.selection.ranges.map((r) => r.head)).toEqual([9, 20]);
});
it("lets Tab step out of the parentheses a completion inserted", () => {
const { view, req } = setup("service.cr|", "", [tabOut]);
applyLspCompletion(view, makeCompletion(item(), req), 8, 10, "insert");
+24 -4
Переглянути файл
@@ -245,6 +245,23 @@ function applyLsp(view: EditorView, completion: Completion, from: number, to: nu
applyLspCompletion(view, completion, from, to, replaceMode ? "replace" : "insert");
}
function completionInsertText(
item: CompletionItem,
language: string | null,
doc: Text,
from: number,
to: number,
): string {
const { insertText } = item;
// JDT LS can append a space to a bare annotation name. It is useful only as a separator.
if (language !== "java" || item.kind !== "interface" || insertText !== `${item.label} `) return insertText;
const line = doc.lineAt(from);
const before = line.text.slice(0, from - line.from);
const after = doc.sliceString(to, to + 2);
if (!/@(?:[\p{L}\p{N}\p{M}_$]+\.)*$/u.test(before) || identifierEnd(after, 0) > 0) return insertText;
return item.label;
}
/** ↵ (`insert`) or ⇥ (`replace`: also overwrites the rest of the identifier). */
export function applyLspCompletion(
view: EditorView,
@@ -291,6 +308,7 @@ export function applyLspCompletion(
return;
}
const insertText = completionInsertText(item, req.language, state.doc, start, end);
let insertedParens: ReturnType<typeof callParens> = null;
let bareCall: number | null = null;
if (item.isSnippet) {
@@ -300,7 +318,7 @@ export function applyLspCompletion(
start = tr.changes.mapPos(start, 1);
end = tr.changes.mapPos(end, 1);
}
const source = lspSnippetToCm(item.insertText, snippetVariables(req.path));
const source = lspSnippetToCm(insertText, snippetVariables(req.path));
applySnippet(view, [{ from: start, to: end, snippet: source }], completion);
// A call snippet without a stop (`ArrayList<>()`): the caret goes inside until
// signature help says there is nothing to pass.
@@ -320,7 +338,7 @@ export function applyLspCompletion(
? callParens(item, state.doc.lineAt(start), start, end)
: null;
insertedParens = parens;
const changes = state.changes([...extra, { from: start, to: end, insert: item.insertText + (parens ? "()" : "") }]);
const changes = state.changes([...extra, { from: start, to: end, insert: insertText + (parens ? "()" : "") }]);
const caret = changes.mapPos(end, 1) - (parens === "inside" ? 1 : 0);
view.dispatch({
changes,
@@ -391,11 +409,13 @@ function applyAtCarets(
// Parentheses depend on what follows each site: `a.cr|` gets them, `b.cr|()` does not.
const textAt = (site: { from: number; to: number }): { text: string; caret: number } => {
if (item.isSnippet) return lspSnippetToPlainWithCaret(item.insertText, snippetVariables(completion.req.path));
const { language, path } = completion.req;
const insertText = completionInsertText(item, language, state.doc, site.from, site.to);
if (item.isSnippet) return lspSnippetToPlainWithCaret(insertText, snippetVariables(path));
const parens = editorPrefs().completion.insertParentheses
? callParens(item, state.doc.lineAt(site.from), site.from, site.to)
: null;
const text = item.insertText + (parens ? "()" : "");
const text = insertText + (parens ? "()" : "");
return { text, caret: text.length - (parens === "inside" ? 1 : 0) };
};
const texts = sites.map(textAt);
+15 -1
Переглянути файл
@@ -1,7 +1,7 @@
import { describe, expect, it, vi } from "vitest";
import { EditorState, Text } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { viewShown, type EditorDocContext } from "@/editor/api";
import { setLibraryRoots, viewShown, type EditorDocContext } from "@/editor/api";
import { lspDoc } from "./lsp";
import type { Diagnostic } from "@/bindings";
import {
@@ -60,6 +60,20 @@ describe("editor diagnostics store", () => {
expect(calls).toBe(3);
off();
});
it("keeps no diagnostics for library sources", () => {
const dispose = setLibraryRoots("test", ["/sdk"]);
const stop = installDiagnosticsEvents();
emitLocalIdeEvent({
type: "diagnostics",
path: "/sdk/Swift.String.swiftinterface",
source: "sk",
items: [d(0, 0, 1)],
});
setFileDiagnostics("/sdk/Swift.String.swiftinterface", "local", [d(1, 0, 1)]);
expect(diagnosticsFor("/sdk/Swift.String.swiftinterface")).toEqual([]);
stop();
dispose();
});
});
describe("toLintDiagnostics", () => {
+4 -1
Переглянути файл
@@ -12,7 +12,7 @@ import type { Diagnostic, Severity } from "@/bindings";
import { commands, ideEventsReady, isTauri, onIdeEvent } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { publishLocalDiagnostics } from "@/platform/localDiagnostics";
import { intentionsChanged, scrollbarMarks, shownAgain, type ScrollbarMark } from "@/editor/api";
import { intentionsChanged, isLibraryPath, scrollbarMarks, shownAgain, type ScrollbarMark } from "@/editor/api";
import { rangeToOffsets } from "./positions";
import { lspDoc } from "./lsp";
import { showHint } from "./hint";
@@ -54,6 +54,9 @@ export function setFileDiagnostics(path: string, source: string, items: Diagnost
}
function storeDiagnostics(path: string, source: string, items: Diagnostic[], published = false) {
// A library source opens read-only: errors a server reports in it (an SDK interface it
// generated, a dependency's code) are not the user's to fix.
if (isLibraryPath(path)) items = [];
let sources = byPath.get(path);
if (!items.length) {
if (!sources?.delete(source) && !published) return;
+98 -8
Переглянути файл
@@ -66,6 +66,8 @@ import {
isDeclarationName,
isSelfTarget,
localHighlights,
projectIndexDefinitions,
usageRole,
type DeclarationTarget,
} from "./syntaxFallback";
import { showHint, showPendingHint } from "./hint";
@@ -112,6 +114,27 @@ export async function navigateTo(loc: Location) {
await openCodeLocation(loc.path, { line: loc.range.start.line, col: loc.range.start.col });
}
const CLANGD_LANGUAGES = new Set(["c", "cpp", "objective-c", "objective-cpp"]);
const CLANGD_SYNTAX_NOTE = "Based on syntax and the project index";
const C_HEADER = /\.(?:h|hh|hpp|hxx|h\+\+)$/i;
/** `pki_check_bin` for `.../pki_check_bin.h`: the stem a source counterpart shares. */
function fileStem(path: string): string {
const name = path.slice(Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\")) + 1);
const dot = name.lastIndexOf(".");
return (dot > 0 ? name.slice(0, dot) : name).toLowerCase();
}
/**
* `pki_check_bin.c` for `pki_check_bin.h`, or every source when no stem matches: the same
* declaration can be implemented in another component (a kernel tree holds many copies).
*/
function counterpartSources(header: string, sources: readonly DeclarationTarget[]): readonly DeclarationTarget[] {
const stem = fileStem(header);
const own = sources.filter((l) => fileStem(l.path) === stem);
return own.length ? own : sources;
}
const NOT_FOUND: Record<GotoKind, string> = {
definition: "Cannot find declaration to go to",
declaration: "Cannot find declaration to go to",
@@ -373,6 +396,18 @@ async function onDeclarationName(view: EditorView, offset: number): Promise<bool
return isDeclarationName(at);
}
/** Whether the caret is on a function call, not a declaration whose self-target is legitimate. */
async function onCallName(doc: EditorDocContext, pos: Pos): Promise<boolean> {
const at = await structure.nodeAt(doc.doc, { start: pos, end: pos }).catch(() => null);
return usageRole(at) === "call";
}
/** A C-family member must come from its receiver's type, not a project-wide bare-name lookup. */
async function onMemberName(doc: EditorDocContext, pos: Pos): Promise<boolean> {
const at = await structure.nodeAt(doc.doc, { start: pos, end: pos }).catch(() => null);
return at?.node.kind === "field_identifier" || at?.node.kind === "property_identifier";
}
/**
* Go to Implementation targets for Python from the IDE's inheritance graph: its servers
* declare no type hierarchy and analyse one root, so the graph also knows the attached
@@ -400,7 +435,20 @@ async function implementationFallbackTargets(
pos: Pos,
): Promise<readonly DeclarationTarget[]> {
const declaration = await requestNavigation(view, offset, "definition").catch(() => []);
return declaration.filter((l) => !isSelfTarget([l], path, pos));
const targets = declaration.filter((l) => !isSelfTarget([l], path, pos));
if (targets.length) return targets;
const doc = docOf(view);
if (!doc || !CLANGD_LANGUAGES.has(doc.language)) return targets;
// Without a compilation database clangd only sees this header. Look the name up in the
// project index for a source definition; never offer another header declaration.
const name = nameAt(view, offset) ?? (offset > 0 ? nameAt(view, offset - 1) : null);
if (!name) return targets;
const indexed = await projectIndexDefinitions(path, name, "call").catch(() => []);
const sources = indexed.filter((l) => !isSelfTarget([l], path, pos) && !C_HEADER.test(l.path));
if (!sources.length) return targets;
// The caret's own header names the source that implements it: its stem picks that source
// among same-name definitions elsewhere instead of turning the jump into a chooser.
return C_HEADER.test(path) ? counterpartSources(path, sources) : sources;
}
/** Whether `line` (0-based) of `text` is an import statement. */
@@ -495,6 +543,7 @@ async function gotoResolved(
const pos = offsetToPos(view.state.doc, offset);
let locs: DeclarationTarget[];
let fromSyntax = false;
let syntaxNote = SYNTAX_NOTE;
const declaration = kind === "definition" || kind === "declaration";
// A segment of an import path names a file — possibly in a dependency project, which
// neither the single-root server nor the name index resolves.
@@ -580,6 +629,35 @@ async function gotoResolved(
const declarationTargets = await implementationFallbackTargets(view, offset, doc.path, pos);
if (superseded()) return;
locs = dedupeLocations(declarationTargets);
if (declarationTargets.some((target) => target.name && target.kind)) {
fromSyntax = true;
syntaxNote = CLANGD_SYNTAX_NOTE;
}
}
// Without a compilation database clangd may not resolve nested #include files. Its empty
// answer is not authoritative for these languages; the project index still has the local
// declarations. An implicit C declaration can also point at the call itself: replace that
// pseudo target only when syntax and the index provide a real target elsewhere.
if (declaration && !fromSyntax && CLANGD_LANGUAGES.has(doc.language)) {
const selfTargets = locs.length > 0 && locs.every((l) => isSelfTarget([l], doc.path, pos));
if (!locs.length || (selfTargets && (await onCallName(doc, pos)))) {
const fallback = await gotoFallback(view, doc, pos, false);
if (fallback?.length) {
if (!locs.length) {
locs = fallback;
fromSyntax = true;
syntaxNote = CLANGD_SYNTAX_NOTE;
} else {
const elsewhere = fallback.filter((l) => !isSelfTarget([l], doc.path, pos));
if (elsewhere.length) {
locs = elsewhere;
fromSyntax = true;
syntaxNote = CLANGD_SYNTAX_NOTE;
}
}
}
}
if (superseded()) return;
}
if (!locs.length) {
// The server has no definition here: a link (`href`, `#include`, Markdown) or a file path.
@@ -600,8 +678,12 @@ async function gotoResolved(
}
// The server only resolves what it sees: answer from the project index, which also
// covers attached dependency projects (an unresolved import into them). Never for a
// module path: a segment is not a symbol name.
if (declaration && !fromSyntax && !moduleName) {
// module path: a segment is not a symbol name. A C-family member needs its receiver's
// type, so a bare-name dependency lookup would be a guess here too.
const clangMember =
declaration && !fromSyntax && CLANGD_LANGUAGES.has(doc.language) && (await onMemberName(doc, pos));
if (superseded()) return;
if (declaration && !fromSyntax && !moduleName && !clangMember) {
const name = nameAt(view, offset);
const targets = name ? await indexDefinitions(doc.path, name).catch(() => []) : [];
if (targets.length) {
@@ -687,7 +769,7 @@ async function gotoResolved(
setTimeout(() => {
if (superseded()) return;
const target = activeEditor()?.view;
if (target) showHint(target, SYNTAX_NOTE, { timeout: 2500 });
if (target) showHint(target, syntaxNote, { timeout: 2500 });
}, 150);
return;
}
@@ -775,11 +857,16 @@ async function followReferenceAt(
}
/** Declaration targets from the structure service; null when it cannot answer for this file. */
async function gotoFallback(view: EditorView, doc: EditorDocContext, pos: Pos): Promise<DeclarationTarget[] | null> {
async function gotoFallback(
view: EditorView,
doc: EditorDocContext,
pos: Pos,
allowMember = true,
): Promise<DeclarationTarget[] | null> {
try {
await whenSynced(view);
const text = view.state.doc;
const fb = await declarationFallback(doc, text, pos);
const fb = await declarationFallback(doc, text, pos, undefined, allowMember);
return fb.kind === "unsupported" ? null : fb.targets;
} catch (e) {
console.debug("[syntax] declaration fallback", e);
@@ -936,11 +1023,14 @@ async function probeNavigation(
navigable = !!(await gotoFallback(view, doc, pos))?.length;
fromSyntax = true;
}
if (!navigable && !fromSyntax && CLANGD_LANGUAGES.has(doc.language))
navigable = !!(await gotoFallback(view, doc, pos, false))?.length;
if (!navigable && WEB_LANGUAGES.has(doc.language) && !doc.virtual)
navigable = !!(await lspRequest(() => commands.webGoto(doc.doc, pos)).catch(() => null))?.targets.length;
// The index answers across dependency roots too (unresolved imports), but a module path
// segment is a file rather than a name.
if (!navigable && !fromSyntax) {
// segment is a file rather than a name. Keep member probing consistent with the click path.
const clangMember = !fromSyntax && CLANGD_LANGUAGES.has(doc.language) && (await onMemberName(doc, pos));
if (!navigable && !fromSyntax && !clangMember) {
const moduleName = importModuleName(view, doc, offset);
if (moduleName) navigable = !!(await moduleFile(doc, moduleName).catch(() => null));
else {
+104 -2
Переглянути файл
@@ -3,9 +3,11 @@ import { EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import type { commands, Location } from "@/platform/ipc";
const { lspGoto, lspGotoImplementation } = vi.hoisted(() => ({
const { lspGoto, lspGotoImplementation, findSymbols, navIndexDefinitions } = vi.hoisted(() => ({
lspGoto: vi.fn<typeof commands.lspGoto>(),
lspGotoImplementation: vi.fn<typeof commands.lspGotoImplementation>(),
findSymbols: vi.fn<typeof commands.findSymbols>(),
navIndexDefinitions: vi.fn<typeof commands.navIndexDefinitions>(),
}));
vi.mock("@/platform/ipc", async (orig) => {
const real = await orig<typeof import("@/platform/ipc")>();
@@ -17,7 +19,15 @@ vi.mock("@/platform/ipc", async (orig) => {
return {
...real,
isTauri: () => true,
commands: { ...real.commands, lspGoto, lspGotoImplementation, fsReadText, navInheritance },
commands: {
...real.commands,
lspGoto,
lspGotoImplementation,
findSymbols,
navIndexDefinitions,
fsReadText,
navInheritance,
},
};
});
vi.mock("@tauri-apps/api/core", async (orig) => ({
@@ -60,6 +70,8 @@ beforeEach(() => {
invalidateConfigurationNavigation();
lspGoto.mockResolvedValue(ok([]));
lspGotoImplementation.mockResolvedValue(ok([]));
findSymbols.mockResolvedValue({ status: "ok", data: [] });
navIndexDefinitions.mockResolvedValue({ status: "ok", data: [] });
view = editor(TEXT, "go", "/p/store.go");
});
afterEach(() => {
@@ -154,4 +166,94 @@ describe("Go to Implementation on a symbol nothing implements", () => {
await gotoTargets(view, "implementation", text.lastIndexOf("Order") + 2);
expect(openFile).toHaveBeenCalledWith("/p/order.py", { selection: { line: 0, col: 6 }, focus: true });
});
it("finds a C source definition from the project index when clangd only returns the header", async () => {
const name = "verify_firmware";
const text = `int ${name}(const char *signed_fw_path);\n`;
const col = text.indexOf(name);
const range = { start: { line: 0, col }, end: { line: 0, col: col + name.length } };
const symbol = (path: string, line: number) => ({
name,
kind: "function" as const,
container: null,
path,
relPath: path.slice(1),
range: { start: { line, col }, end: { line, col: col + name.length } },
score: 1,
indices: [],
});
view.destroy();
view = editor(text, "c", "/p/pki_check_bin.h");
lspGoto.mockResolvedValue(ok([{ path: "/p/pki_check_bin.h", range }]));
findSymbols.mockResolvedValue({
status: "ok",
data: [symbol("/p/pki_check_bin.h", 0), symbol("/p/pki_check_bin.c", 190)],
});
await gotoTargets(view, "implementation", col + 2);
expect(findSymbols).toHaveBeenCalledWith(name, "all", 500);
expect(openFile).toHaveBeenCalledWith("/p/pki_check_bin.c", { selection: { line: 190, col }, focus: true });
expect(navIndexDefinitions).not.toHaveBeenCalled();
});
it("does not treat another header declaration as a C implementation", async () => {
const name = "verify_firmware";
const text = `int ${name}(const char *signed_fw_path);\n`;
const col = text.indexOf(name);
const range = { start: { line: 0, col }, end: { line: 0, col: col + name.length } };
view.destroy();
view = editor(text, "c", "/p/pki_check_bin.h");
lspGoto.mockResolvedValue(ok([{ path: "/p/pki_check_bin.h", range }]));
findSymbols.mockResolvedValue({
status: "ok",
data: [
{
name,
kind: "function" as const,
container: null,
path: "/p/other.h",
relPath: "p/other.h",
range,
score: 1,
indices: [],
},
],
});
await gotoTargets(view, "implementation", col + 2);
expect(openFile).not.toHaveBeenCalled();
expect(document.querySelector(".cm-lsp-hint")?.textContent).toBe("No implementations found");
});
it("prefers the header's own source among same-name definitions elsewhere", async () => {
const name = "verify_firmware";
const text = `int ${name}(const char *signed_fw_path);\n`;
const col = text.indexOf(name);
const range = { start: { line: 0, col }, end: { line: 0, col: col + name.length } };
const symbol = (path: string, line: number) => ({
name,
kind: "function" as const,
container: null,
path,
relPath: path.slice(1),
range: { start: { line, col }, end: { line, col: col + name.length } },
score: 1,
indices: [],
});
view.destroy();
view = editor(text, "c", "/p/pki_check_bin.h");
lspGoto.mockResolvedValue(ok([{ path: "/p/pki_check_bin.h", range }]));
findSymbols.mockResolvedValue({
status: "ok",
data: [
symbol("/p/pki_check_bin.h", 0),
symbol("/p/pki_check_bin.c", 190),
symbol("/kernel/5.15/gvt/firmware.c", 149),
symbol("/kernel/5.4/gvt/firmware.c", 154),
],
});
await gotoTargets(view, "implementation", col + 2);
expect(openFile).toHaveBeenCalledExactlyOnceWith("/p/pki_check_bin.c", {
selection: { line: 190, col },
focus: true,
});
});
});
+200
Переглянути файл
@@ -48,6 +48,8 @@ const { gotoTargets, navigationExtension, highlightUsages } = await import("./na
const { registerNavigationProvider } = await import("@/editor/navigationProviders");
const { startRename, renameNamePart } = await import("./rename");
const { lspDoc } = await import("./lsp");
const { usePlatform } = await import("@/platform/platformInfo");
const { resetNavigationModifier } = await import("@/platform/navigationModifier");
const { invalidateConfigurationNavigation } = await import("./configurationNavigation");
const { useLspPopup, closePopup } = await import("./popupStore");
const { inplaceRenameExtension, inplaceSession } = await import("./inplaceRename");
@@ -211,6 +213,36 @@ describe("declarationFallback", () => {
expect(res).toMatchObject({ kind: "targets", ambiguous: true });
});
it("can reject a member reported by locals without querying the index", async () => {
cmd.syntaxLocals.mockReturnValueOnce(ok({ status: "notLocal", name: "foo", range: r(1, 6, 9), reason: "member" }));
const res = await fb.declarationFallback(doc, text, { line: 1, col: 7 }, undefined, false);
expect(res).toEqual({ kind: "targets", targets: [], ambiguous: false });
expect(cmd.syntaxNodeAt).not.toHaveBeenCalled();
expect(cmd.findSymbols).not.toHaveBeenCalled();
});
it("can reject a C field node when locals are unavailable", async () => {
cmd.syntaxSupport.mockReturnValueOnce(ok({ tree: true, locals: false }));
cmd.syntaxNodeAt.mockReturnValueOnce(ok({ node: node("field_identifier", r(1, 6, 9)), ancestors: [] }));
const res = await fb.declarationFallback(
{ ...doc, language: "c-fields" },
text,
{ line: 1, col: 7 },
undefined,
false,
);
expect(res).toEqual({ kind: "targets", targets: [], ambiguous: false });
expect(cmd.findSymbols).not.toHaveBeenCalled();
});
it("keeps a no-identifier answer empty outside macro replacement bodies", async () => {
cmd.syntaxLocals.mockReturnValueOnce(ok({ status: "noIdentifier" }));
cmd.syntaxNodeAt.mockReturnValueOnce(ok({ node: node("identifier", r(1, 6, 9)), ancestors: [] }));
const res = await fb.declarationFallback(doc, text, { line: 1, col: 7 });
expect(res).toEqual({ kind: "targets", targets: [], ambiguous: false });
expect(cmd.findSymbols).not.toHaveBeenCalled();
});
it("uses the node text for languages without locals, and gives up without a grammar", async () => {
cmd.syntaxSupport.mockReturnValueOnce(ok({ tree: true, locals: false }));
cmd.syntaxNodeAt.mockReturnValueOnce(ok({ node: node("identifier", r(1, 6, 9)), ancestors: [] }));
@@ -345,6 +377,174 @@ describe("navigation wiring", () => {
expect(document.querySelector(".cm-lsp-hint")?.textContent).toBe("Cannot find declaration to go to");
});
function clangCall(language: string, name = "indirect_call") {
const text = `#include "direct.h"\nint main(void) { return ${name}(); }\n`;
const path = language === "cpp" || language === "objective-cpp" ? "/p/main.cpp" : "/p/main.c";
const col = text.split("\n")[1]!.indexOf(name);
const range = r(1, col, col + name.length);
const at: NodeAt = {
node: node("identifier", range, "function"),
ancestors: [node("call_expression", r(1, 0, text.split("\n")[1]!.length))],
};
cmd.syntaxLocals.mockReturnValueOnce(ok({ status: "notLocal", name, range, reason: "topLevel" }));
cmd.syntaxNodeAt.mockReturnValueOnce(ok(at));
const view = editor(text, language, text.indexOf(name) + 2, path);
return { view, path, range, at, name };
}
it.each(["c", "cpp", "objective-c", "objective-cpp"])(
"uses the local project index when clangd cannot resolve a nested include in %s",
async (language) => {
cmd.lspGoto.mockReturnValueOnce(ok([]));
const { view, name } = clangCall(language);
cmd.findSymbols.mockReturnValueOnce(ok([sym(name, "function", "/p/include/indirect.h")]));
await gotoTargets(view, "definition");
expect(openFile).toHaveBeenCalledWith("/p/include/indirect.h", { selection: { line: 3, col: 4 }, focus: true });
expect(cmd.navIndexDefinitions).not.toHaveBeenCalled();
},
);
it("resolves a function name inside a C macro replacement body", async () => {
const name = "sys_util_read_content";
const text = `#define jy_read_country(buf, len) ${name}(FACTORY_DIR "country_code", buf, len)\n`;
const col = text.indexOf(name);
cmd.lspGoto.mockReturnValueOnce(ok([]));
cmd.syntaxLocals.mockReturnValueOnce(ok({ status: "noIdentifier" }));
cmd.syntaxNodeAt.mockReturnValueOnce(
ok({
node: node("preproc_arg", r(0, col, text.length - 1), "value"),
ancestors: [node("preproc_function_def", r(0, 0, text.length - 1))],
}),
);
cmd.findSymbols.mockReturnValueOnce(ok([sym(name, "function", "/p/jtutil/jt_sys_util.h")]));
const view = editor(text, "c", col + 2, "/p/jy_lib.h");
await gotoTargets(view, "definition");
expect(openFile).toHaveBeenCalledWith("/p/jtutil/jt_sys_util.h", {
selection: { line: 3, col: 4 },
focus: true,
});
expect(cmd.navIndexDefinitions).not.toHaveBeenCalled();
});
it("underlines a nested-include call when the hover probe uses the same index fallback", async () => {
cmd.lspGoto.mockReturnValueOnce(ok([]));
const { view, name } = clangCall("c");
cmd.findSymbols.mockReturnValueOnce(ok([sym(name, "function", "/p/include/indirect.h")]));
const os = usePlatform.getState().os;
usePlatform.setState({ os: "macos" });
resetNavigationModifier();
const offset = view.state.doc.toString().indexOf(name) + 2;
vi.spyOn(view, "posAtCoords").mockReturnValue(offset);
try {
view.contentDOM.dispatchEvent(new MouseEvent("mousemove", { bubbles: true, metaKey: true }));
await vi.waitFor(() => expect(view.dom.querySelector(".cm-lsp-link")).not.toBeNull());
} finally {
resetNavigationModifier();
usePlatform.setState({ os });
}
});
it("replaces clangd's implicit-declaration self target with the indexed declaration", async () => {
const { view, path, range, at, name } = clangCall("c");
cmd.lspGoto.mockReturnValueOnce(ok([{ path, range }]));
cmd.syntaxNodeAt.mockReturnValueOnce(ok(at));
cmd.findSymbols.mockReturnValueOnce(ok([sym(name, "function", "/p/jtutil/jt_sys_util.h")]));
executeAction.mockClear();
await gotoTargets(view, "definition");
expect(openFile).toHaveBeenCalledWith("/p/jtutil/jt_sys_util.h", {
selection: { line: 3, col: 4 },
focus: true,
});
expect(executeAction).not.toHaveBeenCalled();
});
it("keeps a legitimate declaration self target instead of replacing it from the index", async () => {
const name = "indirect_call";
const range = r(0, 4, 4 + name.length);
const path = "/p/main.c";
cmd.lspGoto.mockReturnValueOnce(ok([{ path, range }]));
cmd.syntaxNodeAt.mockReturnValueOnce(
ok({
node: node("identifier", range, "declarator"),
ancestors: [node("function_declarator", r(0, 0, 4 + name.length + 8))],
}),
);
const view = editor(`int ${name}(void) { return 0; }\n`, "c", 6, path);
executeAction.mockClear();
await gotoTargets(view, "definition");
expect(executeAction).toHaveBeenCalledWith("find.showUsages");
expect(cmd.findSymbols).not.toHaveBeenCalled();
expect(openFile).not.toHaveBeenCalled();
});
it("keeps clangd's original self target when the local index has no better answer", async () => {
const { view, path, range, at } = clangCall("c");
cmd.lspGoto.mockReturnValueOnce(ok([{ path, range }]));
cmd.syntaxNodeAt.mockReturnValueOnce(ok(at));
executeAction.mockClear();
await gotoTargets(view, "definition");
expect(executeAction).toHaveBeenCalledWith("find.showUsages");
expect(openFile).not.toHaveBeenCalled();
});
it("does not guess a C member declaration from unrelated project symbols", async () => {
cmd.lspGoto.mockReturnValueOnce(ok([]));
const range = r(0, 3, 10);
const at: NodeAt = { node: node("field_identifier", range, "field"), ancestors: [] };
cmd.syntaxLocals.mockReturnValueOnce(ok({ status: "notLocal", name: "handler", range, reason: "member" }));
cmd.syntaxNodeAt.mockReturnValueOnce(ok(at)).mockReturnValueOnce(ok(at));
cmd.navIndexDefinitions.mockReturnValue(ok([sym("handler", "method", "/p/other.c")]));
try {
const view = editor("s->handler();\n", "c", 5, "/p/main.c");
await gotoTargets(view, "definition");
expect(cmd.findSymbols).not.toHaveBeenCalled();
expect(cmd.navIndexDefinitions).not.toHaveBeenCalled();
expect(openFile).not.toHaveBeenCalled();
} finally {
cmd.navIndexDefinitions.mockReturnValue(ok([]));
}
});
it("does not underline a C member from a bare-name dependency candidate", async () => {
const range = r(0, 3, 10);
const at: NodeAt = { node: node("field_identifier", range, "field"), ancestors: [] };
cmd.lspGoto.mockReturnValue(ok([]));
cmd.syntaxLocals.mockReturnValue(ok({ status: "notLocal", name: "handler", range, reason: "member" }));
cmd.syntaxNodeAt.mockReturnValue(ok(at));
cmd.navIndexDefinitions.mockReturnValue(ok([sym("handler", "method", "/p/other.c")]));
const view = editor("s->handler();\n", "c", 5, "/p/main.c");
const os = usePlatform.getState().os;
usePlatform.setState({ os: "macos" });
resetNavigationModifier();
vi.spyOn(view, "posAtCoords").mockReturnValue(5);
try {
view.contentDOM.dispatchEvent(new MouseEvent("mousemove", { bubbles: true, metaKey: true }));
await vi.waitFor(() => expect(cmd.syntaxNodeAt).toHaveBeenCalled());
expect(view.dom.querySelector(".cm-lsp-link")).toBeNull();
expect(cmd.navIndexDefinitions).not.toHaveBeenCalled();
expect(openFile).not.toHaveBeenCalled();
} finally {
resetNavigationModifier();
usePlatform.setState({ os });
cmd.lspGoto.mockReturnValue(unavailable());
cmd.syntaxLocals.mockReturnValue(ok({ status: "noIdentifier" }));
cmd.syntaxNodeAt.mockReturnValue(ok(null));
cmd.navIndexDefinitions.mockReturnValue(ok([]));
}
});
it("shows ambiguous nested-include declarations as syntax-based candidates", async () => {
cmd.lspGoto.mockReturnValueOnce(ok([]));
const { view, name } = clangCall("c");
cmd.findSymbols.mockReturnValueOnce(ok([sym(name, "function", "/p/a.c"), sym(name, "function", "/p/include/a.h")]));
await gotoTargets(view, "definition");
const popup = useLspPopup.getState().popup;
expect(popup?.kind).toBe("list");
if (popup?.kind !== "list") return;
expect(popup.title).toBe(`Choose Declaration of ${name} (2 found, based on syntax)`);
expect(openFile).not.toHaveBeenCalled();
});
it("answers from the index when the server cannot resolve an import into a dependency project", async () => {
cmd.lspGoto.mockReturnValueOnce(ok([]));
cmd.navIndexDefinitions.mockReturnValueOnce(ok([sym("ParallelDims", "class", "/deps/engine/model.py")]));
+35 -10
Переглянути файл
@@ -154,6 +154,20 @@ export async function indexDefinitions(path: string, name: string): Promise<Decl
);
}
/** Exact-name declarations from the whole project index, filtered by use and language family. */
export async function projectIndexDefinitions(
path: string,
name: string,
role: UsageRole,
): Promise<DeclarationTarget[]> {
const matches = await call(commands.findSymbols(name, "all", SYMBOL_LIMIT));
const symbols = filterSymbols(matches, name, role).filter((s) => compatibleFiles(path, s.path));
return rankTargets(
symbols.map((s) => ({ path: s.path, range: s.range, name: s.name, kind: s.kind, container: s.container })),
path,
);
}
/**
* Go to Declaration without a language server: a certain local definition,
* otherwise project index symbols with exactly that name (filtered by the
@@ -164,32 +178,43 @@ export async function declarationFallback(
text: Text,
pos: Pos,
signal?: AbortSignal,
allowMember = true,
): Promise<DeclarationFallback> {
const support = await structure.support(doc.language);
if (!support.tree) return { kind: "unsupported" };
let locals: Locals | null = null;
if (support.locals) locals = await structure.locals(doc.doc, pos, { signal });
if (locals?.status === "noIdentifier") return { kind: "targets", targets: [], ambiguous: false };
if (locals?.status === "local") return { kind: "targets", ...localTargets(doc.path, locals.symbol) };
if (!allowMember && locals?.status === "notLocal" && locals.reason === "member")
return { kind: "targets", targets: [], ambiguous: false };
const at = await structure.nodeAt(doc.doc, { start: pos, end: pos }, { signal });
const name = locals?.status === "notLocal" ? locals.name : identifierText(text, at);
if (locals?.status === "noIdentifier" && at?.node.kind !== "preproc_arg")
return { kind: "targets", targets: [], ambiguous: false };
if (!allowMember && at?.node.kind === "field_identifier") return { kind: "targets", targets: [], ambiguous: false };
const name = locals?.status === "notLocal" ? locals.name : identifierText(text, at, pos);
if (!name) return { kind: "targets", targets: [], ambiguous: false };
// A member (`obj.name`) can be any member of that name; only a plain name has a syntactic role.
const role = locals?.status === "notLocal" && locals.reason === "member" ? "other" : usageRole(at);
const matches = await call(commands.findSymbols(name, "all", SYMBOL_LIMIT));
const symbols = filterSymbols(matches, name, role).filter((s) => compatibleFiles(doc.path, s.path));
const targets = rankTargets(
symbols.map((s) => ({ path: s.path, range: s.range, name: s.name, kind: s.kind, container: s.container })),
doc.path,
);
const targets = await projectIndexDefinitions(doc.path, name, role);
return { kind: "targets", targets, ambiguous: targets.length > 1 };
}
const IDENT = /^[\p{L}_$][\p{L}\p{N}_$]*$/u;
const IDENT_PART = /[\p{L}\p{N}_$]/u;
/** Name of a leaf identifier node (languages without `locals.scm`). */
function identifierText(text: Text, at: NodeAt | null): string | null {
/** Name of a leaf identifier node, or the identifier at `pos` in a macro replacement body. */
function identifierText(text: Text, at: NodeAt | null, pos: Pos): string | null {
if (at?.node.kind === "preproc_arg") {
if (pos.line >= text.lines) return null;
const line = text.line(pos.line + 1).text;
let from = Math.min(pos.col, line.length);
let to = from;
while (from > 0 && IDENT_PART.test(line[from - 1]!)) from--;
while (to < line.length && IDENT_PART.test(line[to]!)) to++;
const name = line.slice(from, to);
return IDENT.test(name) ? name : null;
}
if (!at || !/identifier|^name$|^constant$|^word$/.test(at.node.kind)) return null;
const { from, to } = rangeToOffsets(text, at.node.range);
const name = text.sliceString(from, to);
+7 -4
Переглянути файл
@@ -13,7 +13,8 @@
* The cache outlives the editor view (switching tabs remounts it) until other
* files change, a language server settles or its classpath changes: on some servers (jdtls) every
* implementation search walks the whole workspace, so asking again is costly.
* Library sources ask no inheritors from the server (`isLibrarySource`).
* Library sources ask no inheritors from the server (`isLibrarySource`); explicit
* Go to Implementation still answers.
*/
import { RangeSet, StateEffect, StateField, type EditorState, type Extension, type Text } from "@codemirror/state";
import { EditorView, GutterMarker, ViewPlugin, type ViewUpdate } from "@codemirror/view";
@@ -826,11 +827,13 @@ class MarkersPlugin {
}
/**
* In a library every method's overriders would be searched for across the whole project,
* one search per visible method: only its classes and interfaces get ↓ markers.
* Library symbols are referenced everywhere, so an inheritor search walks the whole
* project and its dependencies (jdtls builds a full type hierarchy). A JDK interface
* such as `java.util.function.Function` then keeps the status bar at "Creating type
* hierarchy" and times out. Keep super-method markers, but ask for no inheritors.
*/
export function libraryCandidates(candidates: readonly MarkerCandidate[]): MarkerCandidate[] {
return candidates.map((c) => (c.method && c.inheritable ? { ...c, inheritable: false } : c));
return candidates.map((c) => ({ ...c, inheritable: false, implicit: false }));
}
/** LSP access for one pass: this document's outline as known, others' opened on demand, each asked once. */
+10 -6
Переглянути файл
@@ -517,18 +517,22 @@ describe("library sources", () => {
[`${SHAPE_PATH}:1`]: [loc("/p/Circle.java", 2, 18), loc("/p/Square.java", 1, 18)],
};
it("ask for the inheritors of types only, not one project-wide search per method", async () => {
it("ask for no inheritors: a library type's search walks the whole project and its dependencies", async () => {
const { deps, calls } = server(shapeImpls, {});
const candidates = libraryCandidates(markerCandidates(SHAPE_OUTLINE, lines(SHAPE)));
const cache = emptyCache();
await fillMarkers(SHAPE_PATH, candidates, ALL, deps(SHAPE_PATH), cache);
expect(calls.implementations).toEqual([[{ line: 0, col: 17 }]]);
expect(cachedMarkers(candidates, ALL, cache).map((m) => [m.line, m.kind, m.tooltip])).toEqual([
[0, "implemented", "Is implemented by Circle, Square"],
]);
expect(calls.implementations).toEqual([]);
expect(calls.subtypes).toBe(0);
expect(cachedMarkers(candidates, ALL, cache)).toEqual([]);
});
it("still ask the server for inheritors and subtypes", async () => {
it("also drops Go's implicit interface queries", () => {
const candidates = libraryCandidates(markerCandidates(GO_OUTLINE, lines(GO), { implicitInterfaces: true }));
expect(candidates.some((c) => c.inheritable || c.implicit)).toBe(false);
});
it("keeps super-method queries available without enabling inheritor searches", async () => {
const off = setLibraryRoots("test", ["/venv/site-packages"]);
try {
const library = {
+16 -5
Переглянути файл
@@ -162,7 +162,7 @@ describe("Agents selection", () => {
vi.mocked(openTask).mockClear();
context("two");
expect(selectedTasks()).toEqual(["one", "two", "three"]);
expect(screen.getByRole("menuitem", { name: "Delete (3)…" })).toBeTruthy();
expect(screen.getByRole("menuitem", { name: /^Delete \(3\)…/ })).toBeTruthy();
expect(openTask).not.toHaveBeenCalled();
});
@@ -298,9 +298,20 @@ describe("Agents docked view", () => {
setup();
expect(screen.queryByRole("button", { name: "Open in Editor" })).toBeNull();
select("two");
expect(openTask).toHaveBeenCalledWith("two");
expect(openTask).toHaveBeenCalledWith("two", { focus: false });
expect(dockTask).not.toHaveBeenCalled();
});
it("keeps focus in the list when a click opens a task, so Delete deletes that task", async () => {
setup();
const tree = screen.getByRole("tree", { name: "Agent tasks" });
tree.focus();
select("two");
expect(openTask).toHaveBeenCalledWith("two", { focus: false });
// The shortcut runs the action without an argument: it takes the list's selection.
await taskActions.find((a) => a.id === "agents.deleteTasks")!.run({ ctx: {}, arg: undefined });
await waitFor(() => expect(deleteTask).toHaveBeenCalledExactlyOnceWith("two", false));
});
});
describe("Agents bulk actions", () => {
@@ -311,7 +322,7 @@ describe("Agents bulk actions", () => {
select("one");
select("three", { shiftKey: true });
context("two");
fireEvent.click(screen.getByRole("menuitem", { name: "Delete (3)…" }));
fireEvent.click(screen.getByRole("menuitem", { name: /^Delete \(3\)…/ }));
await waitFor(() => expect(deleteTask).toHaveBeenCalledTimes(3));
expect(confirmChecked).toHaveBeenCalledTimes(1);
expect(confirmChecked).toHaveBeenCalledWith(
@@ -329,7 +340,7 @@ describe("Agents bulk actions", () => {
select("one");
select("two", { shiftKey: true });
context("four");
fireEvent.click(screen.getByRole("menuitem", { name: "Delete…" }));
fireEvent.click(screen.getByRole("menuitem", { name: /^Delete…/ }));
await waitFor(() => expect(deleteTask).toHaveBeenCalledExactlyOnceWith("four", false));
});
@@ -784,6 +795,6 @@ describe("Agents pinned and grouped tasks", () => {
expect(openTask).not.toHaveBeenCalled();
fireEvent.pointerUp(window, { button: 0, clientX: 10, clientY: 104 });
fireEvent.click(sourceSpan, { button: 0 });
expect(openTask).toHaveBeenCalledWith("two");
expect(openTask).toHaveBeenCalledWith("two", { focus: false });
});
});
+44 -10
Переглянути файл
@@ -52,8 +52,8 @@ import {
openHome,
pinTasks,
refreshExternalSessions,
reorderTask,
reorderTaskGroup,
reorderTasks,
showImportSessions,
useAgents,
} from "./store";
@@ -238,6 +238,8 @@ export function AgentsView() {
searchingRef.current = matches !== null;
}, [matches]);
const cancelDragRef = useRef<(() => void) | undefined>(undefined);
/** Every task the current drag carries, in list order; set when it starts. */
const draggedIdsRef = useRef<string[]>([]);
const [tasksEl, setTasksEl] = useState<HTMLDivElement | null>(null);
const [dropIndicator, setDropIndicator] = useState<DropIndicator | null>(null);
useEffect(() => {
@@ -266,11 +268,18 @@ export function AgentsView() {
const { tasks, organize } = useAgents.getState();
const source = tasks.get(data.payload);
if (!source) return null;
// Dragging a selected task moves the whole selection.
const ids = draggedIdsRef.current.includes(source.id) ? draggedIdsRef.current : [source.id];
const sources = ids.flatMap((id) => {
const task = tasks.get(id);
return task ? [task] : [];
});
const sourceIds = sources.map((t) => t.id);
if (targetKey === PINNED_SECTION) {
return {
indicator: { kind: "section", key: targetKey } as DropIndicator,
apply: () => pinTasks([source.id], true),
apply: () => pinTasks(sourceIds, true),
};
}
if (targetKey.startsWith("ug:")) {
@@ -278,23 +287,33 @@ export function AgentsView() {
if (!organize.groups.some((g) => g.id === groupId)) return null;
return {
indicator: { kind: "section", key: targetKey } as DropIndicator,
apply: () => moveTasksToGroup([source.id], groupId),
apply: () => moveTasksToGroup(sourceIds, groupId),
};
}
if (targetKey.startsWith("g:")) {
if (sectionOfTask(source, organize) === targetKey) return null;
if (statusSection(taskGroupStatus(source)) !== targetKey) return null;
// A status group takes the tasks of its status that are elsewhere.
const movable = sources.filter(
(t) => sectionOfTask(t, organize) !== targetKey && statusSection(taskGroupStatus(t)) === targetKey,
);
if (!movable.length) return null;
return {
indicator: { kind: "section", key: targetKey } as DropIndicator,
apply: () => moveTasksToStatusGroup([source.id]),
apply: () => moveTasksToStatusGroup(movable.map((t) => t.id)),
};
}
if (searchingRef.current) return null;
const target = tasks.get(targetKey);
if (!target || !canReorderTask(source, target, organize)) return null;
if (!target || sourceIds.includes(target.id)) return null;
const movable = sources.filter((t) => canReorderTask(t, target, organize));
if (!movable.length) return null;
return {
indicator: { kind: "row", key: targetKey, position } as DropIndicator,
apply: () => reorderTask(source.id, target.id, position),
apply: () =>
reorderTasks(
movable.map((t) => t.id),
target.id,
position,
),
};
};
const update = () => {
@@ -383,11 +402,26 @@ export function AgentsView() {
setHistoryOpen(false);
void executeAction("agents.openTask", task);
};
// A click or arrow key in the list opens the session but keeps focus in the list, so its
// shortcuts (Delete) still act on the selection; Enter and double-click focus the session.
const previewTask = (task: string) => {
if (inline) showTask(task);
else void executeAction("agents.openTask", { task, focus: false });
};
const dockedTitle = docked ? (tasks.get(docked)?.title ?? docked) : null;
const dragTask = (e: ReactPointerEvent<HTMLElement>, task: string, source: HTMLElement = e.currentTarget) => {
suppressClickRef.current = false;
if (e.button !== 0 || e.ctrlKey || e.metaKey || e.shiftKey) return;
cancelDragRef.current?.();
// A selected row drags the whole selection, in list order.
const current = selectedRef.current;
draggedIdsRef.current =
current.size > 1 && current.has(task)
? roots
.flatMap((n) => (n.kind === "group" ? n.group.tasks : n.kind === "task" ? [n.task] : n.tasks))
.map((t) => t.id)
.filter((id, i, all) => current.has(id) && all.indexOf(id) === i)
: [task];
cancelDragRef.current = startPointerDrag(
e,
source,
@@ -478,7 +512,7 @@ export function AgentsView() {
if (e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey) return;
if ((e.target as Element).closest("button, input, textarea, [data-tree-toggle]")) return;
const key = (e.target as Element).closest<HTMLElement>("[data-tree-key]")?.dataset.treeKey;
if (key && tasks.has(key)) showTask(key);
if (key && tasks.has(key)) previewTask(key);
}}
onFocus={() => setFocusedTaskList(() => [...selectedRef.current])}
onBlur={(e) => {
@@ -554,7 +588,7 @@ export function AgentsView() {
lead?.kind === "task" &&
sel.has(lead.task.id)
)
showTask(lead.task.id);
previewTask(lead.task.id);
}}
onActivate={(n) => n.kind === "task" && showTask(n.task.id)}
onContextMenu={(n, sel, e) => {
+2 -1
Переглянути файл
@@ -1,4 +1,5 @@
import { useId, useState } from "react";
import clsx from "clsx";
import type { AgentForm, AgentFormField, AgentTask } from "@/bindings";
import { Button, Checkbox, Input, Radio, T } from "@/ui";
import type { PermissionEntry } from "./permission";
@@ -48,7 +49,7 @@ export function FormCard({ task, entry, form }: { task: AgentTask; entry: Permis
};
return (
<form
className={styles.questionCard}
className={clsx(styles.questionCard, styles.questionCardPinned)}
aria-label={entry.title}
onSubmit={(event) => {
event.preventDefault();
+4 -2
Переглянути файл
@@ -1632,9 +1632,11 @@
font-size: var(--agent-fs-ui, var(--fs-ui));
container: question-card / inline-size;
}
/* A question that outlived its turn waits above the composer, at the composer's width. */
/* A question that outlived its turn waits above the composer, at the composer's width. It scrolls within at most
half the window, and less when the session is shorter, so the composer and the card's buttons stay in view. */
.questionCardPinned {
flex: none;
flex: 0 1 auto;
min-height: 0;
max-height: 50vh;
overflow-y: auto;
width: 100%;
+27 -8
Переглянути файл
@@ -57,6 +57,7 @@ import { withQuote } from "./conversation";
import {
EMPTY_ORGANIZE,
PINNED_SECTION,
canReorderTask,
compactOrder,
customSection,
loadOrganize,
@@ -1184,7 +1185,8 @@ export function useAgentCommands(
return extra.length > 0 ? [...filtered, ...extra] : filtered;
}
export function openTask(task: string) {
/** Opens the task's session; `focus: false` opens it in the editor without taking focus (a click in the task list). */
export function openTask(task: string, options: { focus?: boolean } = {}) {
if (routeToWindow(task)) return;
forgetClosed(task);
if (useAgents.getState().sessionLocation === "toolWindow") {
@@ -1192,13 +1194,13 @@ export function openTask(task: string) {
return;
}
useAgents.setState({ lastTask: task, homeOpen: false, lastComposer: task });
openTaskInEditor(task);
openTaskInEditor(task, options.focus ?? true);
}
function openTaskInEditor(task: string) {
function openTaskInEditor(task: string, focus = true) {
// The title rides along so a restored tab has it before the tasks load.
const title = useAgents.getState().tasks.get(task)?.title;
void editorService().openInput({ kind: SESSION_KIND, key: sessionKey(task), data: { task, title } }, { focus: true });
void editorService().openInput({ kind: SESSION_KIND, key: sessionKey(task), data: { task, title } }, { focus });
}
function showDockedTask(task: string) {
@@ -2189,10 +2191,27 @@ export function moveTasksToStatusGroup(tasks: readonly string[]) {
});
}
/** Places `sourceId` before or after `targetId` (moving it into the target's section when needed). */
export function reorderTask(sourceId: string, targetId: string, position: "before" | "after") {
const tasks = useAgents.getState().tasks.values();
changeOrganize((organize) => reorderTaskInOrganize(organize, tasks, sourceId, targetId, position));
/**
* Places `sourceIds` (in list order) before or after `targetId`, keeping their relative order.
* Tasks that can't go beside the target (another status than its status group) stay where they are.
*/
export function reorderTasks(sourceIds: readonly string[], targetId: string, position: "before" | "after") {
const tasks = [...useAgents.getState().tasks.values()];
changeOrganize((organize) => {
let next = organize;
// Before: each goes right before the target. After: each goes after the one placed last.
let anchor = targetId;
const byId = new Map(tasks.map((t) => [t.id, t]));
for (const id of sourceIds) {
if (id === targetId) continue;
const source = byId.get(id);
const target = byId.get(anchor);
if (!source || !target || !canReorderTask(source, target, next)) continue;
next = reorderTaskInOrganize(next, tasks, id, anchor, position);
if (position === "after") anchor = id;
}
return next;
});
}
/** Reorders a custom group before or after another custom group. */
+7
Переглянути файл
@@ -285,6 +285,11 @@ export const taskActions: Action[] = [
hidden: true,
run: ({ arg }) => {
if (typeof arg === "string") openTask(arg);
// `{ task, focus: false }`: a click in the task list opens the session and keeps focus there.
else if (arg && typeof arg === "object" && typeof (arg as { task?: unknown }).task === "string") {
const { task, focus } = arg as { task: string; focus?: unknown };
openTask(task, { focus: focus !== false });
}
},
},
{
@@ -396,6 +401,8 @@ export const taskActions: Action[] = [
title: "Delete Agent Tasks",
category: "Agents",
hidden: true,
// Without an argument the shortcut deletes the task list's selection.
keyWhen: "agentTaskListFocus",
run: ({ arg }) => confirmDelete(resolveTasks(arg)),
},
{
+68
Переглянути файл
@@ -276,6 +276,74 @@ describe("build feature", () => {
});
});
it("keeps output the channel delivers after the build result (an >8 KiB line is fetched late)", async () => {
// Tauri sends a channel message over 8 KiB through an async fetch and holds every later message
// back to keep their order, so the command's result can arrive before the rest of the output.
const run = startBuild("build");
await act(async () => {});
const long = `${"w".repeat(8_307)}`;
const warning = warn("/p/src/B.java", 2);
await act(async () => {
fake.emit!({ kind: "output", text: "short\n", stderr: false });
fake.resolve(result([warning], true));
await run;
});
expect(useBuildRun.getState().status).toBe("success");
await act(async () => {
fake.emit!({ kind: "output", text: `${long}\n`, stderr: false });
fake.emit!({ kind: "output", text: "stream-done\n", stderr: false });
fake.emit!({ kind: "message", message: warning });
fake.emit!({ kind: "progress", message: "late", fraction: null });
fake.emit!({ kind: "output", text: "\nProcess finished with exit code 0\n", stderr: false });
await new Promise((r) => setTimeout(r, 30));
});
const s = useBuildRun.getState();
expect(s.lines.map((l) => l.text)).toEqual(["short", long, "stream-done", "", "Process finished with exit code 0"]);
// The result already carries every message; a late one is not added twice.
expect(s.messages).toEqual([warning]);
expect(s.message).toBeNull();
// A newer build owns the console: the old channel's stragglers are dropped.
const stale = fake.emit!;
const second = startBuild("build");
await act(async () => {});
await act(async () => {
stale({ kind: "output", text: "stale\n", stderr: false });
await new Promise((r) => setTimeout(r, 30));
});
expect(useBuildRun.getState().lines.map((l) => l.text)).not.toContain("stale");
await act(async () => {
fake.resolve(result([], true));
await second;
});
});
it("drops a finished build's late events once a launch build owns the Build window", async () => {
const run = startBuild("build");
await act(async () => {});
const late = fake.emit!;
await act(async () => {
fake.resolve(result([], true));
await run;
});
const follower = followLaunchBuild(44 as never, "Build before launch: App");
follower.onEvent({ kind: "started", system: "maven", title: "launch" });
await act(async () => {
late({ kind: "step", command: "stale-step", cwd: "/stale" });
late({ kind: "output", text: "stale\n", stderr: false });
await new Promise((r) => setTimeout(r, 30));
});
const s = useBuildRun.getState();
expect(s.lines.map((l) => l.text)).not.toContain("stale");
expect(s.stepCwd).toBeNull();
follower.finish("success");
await act(async () => {
late({ kind: "output", text: "stale2\n", stderr: false });
await new Promise((r) => setTimeout(r, 30));
});
expect(useBuildRun.getState().lines.map((l) => l.text)).not.toContain("stale2");
});
it("streams a failing build into the tree and console, then notifies and clears next time", async () => {
const run = startBuild("build");
await act(async () => {});
+20 -4
Переглянути файл
@@ -237,6 +237,9 @@ export async function startCompileFile(file: string, activate = true): Promise<B
);
}
/** The latest build: its channel may still deliver output after its result (see `executeBuild`). */
let currentBuild: RequestId | null = null;
/** Streams one backend build into the Build tool window until it finishes. */
async function executeBuild(
request: RequestId,
@@ -246,6 +249,13 @@ async function executeBuild(
cancel: () => void,
): Promise<BuildResult | null> {
const ownsBuild = () => useBuildRun.getState().request === request;
currentBuild = request;
// Tauri delivers a channel message over 8 KiB through an async fetch and holds the later ones back
// to keep their order, so output can still arrive after the command's result. It belongs to this
// build until another build (or a launch build) takes the window; messages and progress are complete
// in the result by then.
const accepts = () => currentBuild === request;
let finished = false;
await maybeEditorService()
?.saveAll()
.catch(() => undefined);
@@ -258,15 +268,17 @@ async function executeBuild(
timer = undefined;
const events = queue;
queue = [];
if (!ownsBuild() || !events.length) return;
if (!accepts() || !events.length) return;
let s = useBuildRun.getState();
for (const e of events) s = { ...s, ...applyBuildEvent(s, e) };
for (const e of events) {
if (!finished || e.kind === "output" || e.kind === "step") s = { ...s, ...applyBuildEvent(s, e) };
}
useBuildRun.setState(s);
if (s.message)
if (!finished && s.message)
upsertTask({ id: BUILD_TASK_ID, title: taskTitle, message: s.message, fraction: null, done: false, cancel });
};
const onEvent = (e: BuildEvent) => {
if (!ownsBuild()) return;
if (!accepts()) return;
queue.push(e);
timer ??= setTimeout(flush, 16);
};
@@ -276,6 +288,7 @@ async function executeBuild(
result = await invoke(useBuildRun.getState().files, onEvent);
if (!ownsBuild()) return null;
flush();
finished = true;
const status: BuildStatus = result.success ? "success" : "failed";
useBuildRun.setState({
status,
@@ -311,6 +324,7 @@ async function executeBuild(
} catch (e) {
if (!ownsBuild()) return null;
flush();
finished = true;
if (isCancelled(e)) {
useBuildRun.setState({ status: "cancelled", files: [], message: null });
} else {
@@ -385,6 +399,7 @@ export function followLaunchBuild(
const take = () => {
if (owned || isBuilding()) return;
owned = true;
currentBuild = null;
const previous = useBuildRun.getState().files;
useBuildRun.setState({ ...INITIAL, request, kind: "build", title, status: "running", files: previous });
setContext(BUILD_LAST_STATUS, null);
@@ -458,6 +473,7 @@ export function rerunBuild() {
}
export function resetBuildRun() {
currentBuild = null;
stopBuild();
removeTask(BUILD_TASK_ID);
setContext(BUILD_RUNNING, false);
+13
Переглянути файл
@@ -1,5 +1,6 @@
import { beforeEach, describe, expect, it } from "vitest";
import type { Diagnostic } from "@/bindings";
import { setLibraryRoots } from "@/editor/api";
import { useProject } from "@/platform/project";
import {
applyDiagnosticsEvent,
@@ -300,3 +301,15 @@ describe("incremental bookkeeping", () => {
}
});
});
describe("library sources", () => {
beforeEach(() => clearProblems());
it("are not the project's problems", () => {
const dispose = setLibraryRoots("test", ["/sdk"]);
applyDiagnosticsEvent("/sdk/Foundation.swiftinterface", "sk", [d(1)]);
applyDiagnosticsEvent("/p/main.swift", "sk", [d(2)]);
expect([...useProblems.getState().map.keys()]).toEqual(["/p/main.swift"]);
dispose();
});
});
+3
Переглянути файл
@@ -5,6 +5,7 @@
*/
import { create } from "zustand";
import type { Diagnostic, Severity } from "@/bindings";
import { isLibraryPath } from "@/editor/api";
import { onIdeEvent } from "@/platform/ipc";
import { onLocalDiagnostics } from "@/platform/localDiagnostics";
import {
@@ -256,6 +257,8 @@ function applyTo(snapshot: ProblemsSnapshot, path: string, source: string, items
}
export function applyDiagnosticsEvent(path: string, source: string, items: readonly Diagnostic[]) {
// Library sources (an SDK interface, a dependency's code) are not the project's problems.
if (isLibraryPath(path)) items = [];
useProblems.setState((s) => {
// The file's sources map is replaced, not changed, so this is the list before the event.
const before = mergedSources(s.map.get(path));
+4
Переглянути файл
@@ -245,7 +245,11 @@ describe("remote attach requests", () => {
port: 9229,
localRoot: "/p",
remoteRoot: "/usr/src/app",
autoAttachChildProcesses: false,
});
// Without a remote root the program may be local, and its child processes are followed.
const local = JSON.parse(remoteAttachConfig(configOf(nodeRemoteType), "/p")!.extraJson!);
expect(local).not.toHaveProperty("autoAttachChildProcesses");
});
it("Attach to Node.js reconnects automatically only when the option is on", () => {
+5 -1
Переглянути файл
@@ -502,7 +502,11 @@ export function remoteAttachConfig(rc: RunConfig, root: string): LaunchConfig |
type: "pwa-node",
address: host,
port: portOf(p, 9229),
...(map ? { localRoot: map.local, remoteRoot: map.remote } : {}),
// On a loopback address (a published container port, an SSH tunnel) js-debug makes the
// program require its child-process bootloader by a path on this machine. Behind a
// remote root that path is missing: tsx's esbuild worker dies of it and the program
// waits for that worker forever.
...(map ? { localRoot: map.local, remoteRoot: map.remote, autoAttachChildProcesses: false } : {}),
skipFiles: skip ? ["<node_internals>/**", "**/node_modules/**"] : [],
...(p.restart === "true" ? { restart: true } : {}),
});
+28 -1
Переглянути файл
@@ -5,7 +5,8 @@ import { useProject } from "@/platform/project";
import { usePlugins } from "./store";
import { useEditorRegistry } from "@/editor/api";
import { lspDoc } from "@/editor/lsp/lsp";
import { synchronizeDocumentIndexes } from "@/workbench/contributions";
import { notifications, provideNotificationService, synchronizeDocumentIndexes } from "@/workbench/contributions";
import { setLocale, txTemplate, useI18n } from "@/platform/i18n";
const mocks = vi.hoisted(() => ({
files: vi.fn(),
@@ -215,3 +216,29 @@ it("keeps unrelated language-server queries available when plugin discovery fail
await expect(synchronizeDocumentIndexes("/project/notes.txt", "refactor")).resolves.toBe(true);
expect(mocks.index).not.toHaveBeenCalled();
});
it("indexes the first files of a large project and says how many it covers, in one sentence", async () => {
mocks.files.mockResolvedValue({
status: "ok",
data: { paths: ["/project/A.java"], indexing: false, extensions: ["java"], total: 28684, truncated: true },
});
useProject.setState({ project: { root: "/project", name: "big-demo", trusted: true } as never });
const notify = vi.fn();
const previous = notifications();
const locale = useI18n.getState().locale;
provideNotificationService({ notify } as never);
try {
await setLocale("zh");
off = startPluginNavigation();
await vi.advanceTimersByTimeAsync(250);
expect(mocks.index.mock.calls[0]?.[0]).toEqual(["/project/A.java"]);
expect(notify).toHaveBeenCalledTimes(1);
const body = notify.mock.calls[0]![0].body;
expect(body).toBe("插件导航仅覆盖 big-demo 中 28,684 个文件里的 1 个;可排除文件夹以缩小范围");
// The balloon and the OS toast look the text up again: it stays whole.
expect(txTemplate(body)).toBe(body);
} finally {
provideNotificationService(previous);
await setLocale(locale);
}
});
+15
Переглянути файл
@@ -47,6 +47,19 @@ export function startPluginNavigation(): () => void {
body: String(error),
});
}
let reportedTruncated = false;
function reportTruncated(count: number, total: number) {
if (reportedTruncated) return;
reportedTruncated = true;
const project = useProject.getState().project;
const name = project?.displayName || project?.name || "";
notifications().notify({
group: "plugins",
level: "warning",
title: "Plugin navigation indexing incomplete",
body: tx`Plugin navigation covers ${count.toLocaleString()} of ${total.toLocaleString()} files in ${name}; exclude folders to narrow it`,
});
}
let fileExtensions = new Set<string>();
const extensions = () => fileExtensions;
const eligible = (path: string) => extensions().has(path.split(".").pop() ?? "");
@@ -142,6 +155,7 @@ export function startPluginNavigation(): () => void {
inventory.paths.forEach((p) => known.add(p));
queue(fresh);
queue([...views.values()], true);
if (inventory.truncated) reportTruncated(inventory.paths.length, inventory.total);
} catch (error) {
discovered = false;
discoveryFailed = true;
@@ -165,6 +179,7 @@ export function startPluginNavigation(): () => void {
discoveryFailed = false;
discovery = null;
reportedError = false;
reportedTruncated = false;
notify();
if (ready())
void call(commands.pluginNavigationInvalidate(null))
+2 -2
Переглянути файл
@@ -100,9 +100,9 @@ export function ProjectHeaderActions() {
{!alwaysSelect && (
<IconButton
icon="locate"
action="navigate.selectInProjectView"
action="project.selectOpenedFile"
title="Select Opened File"
shortcut={shortcutLabel("navigate.selectInProjectView")}
shortcut={shortcutLabel("project.selectOpenedFile")}
size="small"
/>
)}
+23
Переглянути файл
@@ -7,6 +7,7 @@ import { applyKeymapSettings, installKeyboardDispatcher, useKeymap } from "@/pla
import { usePlatform } from "@/platform/platformInfo";
import {
provideEditorService,
registerExternalFileOpenHandler,
registerProjectViewRoot,
setFileDecorations,
type EditorService,
@@ -493,6 +494,28 @@ describe("ProjectView", () => {
expect(openFile).toHaveBeenLastCalledWith("/w/acme/README.md", { preview: undefined, focus: true });
});
it("selects a file opened externally on single click and opens it on double click", async () => {
fs = new MemoryFs({ "/w/acme/notes.docx": "x" }, ROOT);
setProjectFsForTests(fs, ROOT);
initProjectTree(ROOT, "acme");
const disposeExternal = registerExternalFileOpenHandler({
id: "test.external",
matches: (path) => path.endsWith(".docx"),
open: vi.fn(async () => true),
});
try {
const { row, rows } = setup();
await waitFor(() => expect(rows()).toContain("notes.docx"));
const content = row("notes.docx").querySelector("[data-project-path]")!;
fireEvent.click(content, { detail: 1 });
expect(openFile).not.toHaveBeenCalled();
fireEvent.doubleClick(row("notes.docx"));
expect(openFile).toHaveBeenLastCalledWith("/w/acme/notes.docx", { preview: undefined, focus: true });
} finally {
disposeExternal();
}
});
it("opens a selected file in a read-only Quick Preview with Space without creating an editor tab", async () => {
dispatchViaKeymap();
ipc.fsReadText.mockResolvedValue(ok("# Preview\n\nRead without opening a tab."));
+2
Переглянути файл
@@ -34,6 +34,7 @@ import { macStroke, strokeOf } from "@/platform/keymap";
import {
OWNS_FILE_DROP,
getFileDecoration,
opensExternally,
prepareMenuGroups,
useFileDecoration,
useFileDecorations,
@@ -718,6 +719,7 @@ export function ProjectView() {
if (o.singleClickExpand) toggleExpanded(node);
return;
}
if (opensExternally(node.path)) return;
if (!o.singleClickOpen && !previewTabEnabled()) return;
const opts = { preview: o.singleClickOpen ? undefined : true, focus: false };
if (node.member) void revealRange(node.path, { start: node.member.selection_range.start }, opts);
+10
Переглянути файл
@@ -254,6 +254,16 @@ export function registerProjectActions(): () => void {
keywords: ["locate", "reveal", "scroll from source", "select opened file"],
run: ({ arg }) => void selectInProjectView(typeof arg === "string" ? arg : null),
},
{
// IDEA's SelectOpenedFileInProjectView: the Project view toolbar's locate button.
id: "project.selectOpenedFile",
title: "Select Opened File",
category: "Project View",
icon: "locate",
when: OPEN,
keywords: ["locate", "reveal", "scroll from source", "select in project view"],
run: () => void selectInProjectView(null),
},
{
id: "project.reveal",
title: "Reveal in Project View",
+12
Переглянути файл
@@ -152,6 +152,18 @@ describe("Select In (⌥F1)", () => {
expect(useContextMenuStore.getState().menu).toBeNull();
});
it("Select Opened File is a Project View action of its own, as in IDEA's keymap", async () => {
const { IDEA_ACTIONS } = await import("@/platform/ideaActions");
disposers.push(registerProjectActions(), () => setContext("projectOpen", false));
setContext("projectOpen", true);
expect(getAction("project.selectOpenedFile")).toMatchObject({
title: "Select Opened File",
category: "Project View",
});
expect(IDEA_ACTIONS.SelectOpenedFileInProjectView).toBe("project.selectOpenedFile");
expect(IDEA_ACTIONS.SelectInProjectView).toBe("navigate.selectInProjectView");
});
it("expands an in-project folder when expand is true and reveals out-of-project folders in the file manager", async () => {
const { useProjectTree } = await import("./store");
const prev = useProjectTree.getState();
+79
Переглянути файл
@@ -0,0 +1,79 @@
import { afterEach, beforeEach, expect, it, vi } from "vitest";
import type { RunConfig } from "@/platform/ipc";
const ipc = vi.hoisted(() => ({
runStart: vi.fn(async (_config: RunConfig) => ({ status: "ok", data: 1 })),
runStop: vi.fn(async () => ({ status: "ok", data: null })),
}));
vi.mock("@/platform/ipc", async (importOriginal) => {
const real = await importOriginal<typeof import("@/platform/ipc")>();
return { ...real, isTauri: () => true, commands: { ...real.commands, ...ipc } };
});
vi.mock("@tauri-apps/api/core", async (importOriginal) => ({
...(await importOriginal<typeof import("@tauri-apps/api/core")>()),
Channel: class {
onmessage: ((m: unknown) => void) | null = null;
},
}));
import { provideToolWindowService, type ToolWindowService } from "@/workbench/contributions";
import { nodeDuration, nodeOutput, nodeStatus } from "./testing";
import { clearConsole, resetRuns, runtime, startRun } from "./store";
const SEP = "\u0000";
const config: RunConfig = {
id: "junit:CartTest",
name: "CartTest",
kind: "shell",
command: "true",
args: [],
cwd: null,
env: {},
detected: false,
isTest: true,
debugAdapter: null,
};
const cls = ["CartTest"];
const total = ["CartTest", "total"];
beforeEach(() => provideToolWindowService({ show: vi.fn(), hide: vi.fn() } as unknown as ToolWindowService));
afterEach(() => resetRuns());
async function testRun() {
const session = (await startRun(config, undefined, undefined, { prepared: true }))!;
const rt = runtime(session.id)!;
rt.console.append({ kind: "stdout", text: "before all\nprinted by total\n" });
rt.tests!.apply([
{ type: "output", path: cls, line: "before all" },
{ type: "output", path: total, line: "printed by total" },
{ type: "result", path: total, status: "failed", durationMs: 12 },
]);
return { id: session.id, rt, tests: rt.tests! };
}
it("Clear All empties the full console and every test node's output, keeping the results (#6975)", async () => {
const { id, rt, tests } = await testRun();
const leaf = tests.get(total.join(SEP))!;
const group = tests.get(cls.join(SEP))!;
expect(nodeOutput(group)).toEqual(["before all", "printed by total"]);
clearConsole(id);
expect(rt.console.text()).toBe("");
expect(nodeOutput(leaf)).toEqual([]);
expect(nodeOutput(group)).toEqual([]);
expect(nodeStatus(leaf)).toBe("failed");
expect(nodeDuration(group)).toBe(12);
expect(tests.roots.map((r) => r.children.map((c) => c.name))).toEqual([["total"]]);
});
it("output printed after Clear All shows in the console and on its test", async () => {
const { id, rt, tests } = await testRun();
clearConsole(id);
rt.console.append({ kind: "stdout", text: "after clear\n" });
tests.apply([{ type: "output", path: total, line: "after clear" }]);
expect(rt.console.text()).toBe("after clear");
expect(nodeOutput(tests.get(total.join(SEP))!)).toEqual(["after clear"]);
expect(nodeOutput(tests.get(cls.join(SEP))!)).toEqual(["after clear"]);
});
+5 -2
Переглянути файл
@@ -1940,8 +1940,11 @@ export async function closeStdin(sessionId: string): Promise<void> {
}
export function clearConsole(sessionId: string) {
runtimes.get(sessionId)?.console.clear();
runtimes.get(sessionId)?.terminal?.clear();
const rt = runtimes.get(sessionId);
rt?.console.clear();
rt?.terminal?.clear();
// A selected test shows its own captured output, so that goes too (as in IDEA).
rt?.tests?.clearOutput();
bump(sessionId);
}
+6
Переглянути файл
@@ -101,6 +101,12 @@ export class TestResults {
this.version++;
}
/** Console Clear All: drops every node's captured output; statuses, durations and the tree stay. */
clearOutput() {
for (const n of this.byId.values()) n.output = [];
this.version++;
}
/** Finds a test by a suffix of its path (pytest failure headers name `Class.test`). */
findBySuffix(suffix: string[]): TestNode | undefined {
let best: TestNode | undefined;
+34
Переглянути файл
@@ -62,6 +62,7 @@ vi.mock("../find/windowStore", async (orig) => ({
const contributions = await import("@/workbench/contributions");
const { commands, emitLocalIdeEvent } = await import("@/platform/ipc");
const { ContextMenuHost } = await import("@/ui");
const { RecentPopupsOverlay } = await import("../recent/RecentPopups");
const { cycleSwitcher, showRecentPopup, hideRecentPopup, useRecentPopup } = await import("../recent/store");
const { openLocation } = await import("../common/open");
@@ -448,6 +449,39 @@ function clickOption(index: number, modifiers = {}) {
fireEvent.click(row, modifiers);
}
describe("Search Everywhere result actions", () => {
it.each(["keyboard", "right click"] as const)("selects a file in the Project view from the %s menu", async (how) => {
const run = vi.fn();
const project = useProject.getState().project;
useProject.setState({ project: { root: "/p", name: "p", isGit: false } as never });
const dispose = registerAction({
id: "navigate.selectInProjectView",
title: "Select in Project View",
run: ({ arg }) => run(arg),
});
try {
render(
<>
<SearchEverywhereOverlay />
<ContextMenuHost />
</>,
);
act(() => showSearchEverywhere("files", { query: "order" }));
await tick();
if (how === "keyboard") fireEvent.keyDown(screen.getByLabelText("Search query"), { key: "Enter", altKey: true });
else fireEvent.contextMenu(resultOptions()[0]!);
await tick();
fireEvent.click(screen.getByRole("menuitem", { name: /Select in Project View/ }));
await tick();
expect(run).toHaveBeenCalledExactlyOnceWith("/p/src/OrderController.kt");
expect(useSearchEverywhere.getState().open).toBe(false);
} finally {
dispose();
useProject.setState({ project });
}
});
});
describe("Search Everywhere multi-selection", () => {
it("extends, shrinks, crosses the anchor and clamps Shift selection; plain arrows select one", async () => {
const input = await showDuplicateFiles();
+149 -2
Переглянути файл
@@ -1,4 +1,4 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
import type { OutlineItem } from "@/platform/ipc";
@@ -16,10 +16,17 @@ const { FileStructureOverlay, useFileStructurePopup } = await import("../structu
const { useOutline, useStructureOptions } = await import("../structure/store");
const { useTracking } = await import("../common/tracking");
const item = (name: string, kind: OutlineItem["kind"], line: number, children: OutlineItem[] = []): OutlineItem => ({
const item = (
name: string,
kind: OutlineItem["kind"],
line: number,
children: OutlineItem[] = [],
visibility?: OutlineItem["visibility"],
): OutlineItem => ({
name,
detail: null,
kind,
visibility,
range: { start: { line, col: 0 }, end: { line: line + 1, col: 1 } },
selection_range: { start: { line, col: 4 }, end: { line, col: 4 + name.length } },
children,
@@ -61,6 +68,19 @@ function openFunctions(narrowDown: boolean) {
return input;
}
beforeEach(() => {
useStructureOptions.setState({
alphabetical: false,
narrowDown: true,
showFields: true,
showNonPublic: true,
showInherited: false,
sortByVisibility: false,
showOnlyWidgets: false,
});
useOutline.setState({ inheritedSupported: false, inherited: null, flutter: null });
});
afterEach(() => {
act(() => useFileStructurePopup.setState({ open: false }));
useTracking.setState({ caret: null });
@@ -186,6 +206,133 @@ describe("File Structure popup", () => {
expect(useFileStructurePopup.getState().open).toBe(false);
});
describe("temporary filters", () => {
const filteredItems = () => [
item("Container", "class", 0, [
item("hiddenField", "field", 2),
item("hiddenMethod", "method", 4, [], "private"),
item("visible", "method", 6),
]),
];
it("auto-enables only the applicable filter needed for a match, without persisting it", () => {
useStructureOptions.setState({ showFields: false, showNonPublic: false });
const saved = localStorage.getItem("openidea.structure.options.v1");
const input = open(filteredItems());
const fields = screen.getByRole("checkbox", { name: "Show fields" });
const nonPublic = screen.getByRole("checkbox", { name: "Show non-public" });
expect(fields).not.toBeChecked();
expect(nonPublic).not.toBeChecked();
fireEvent.change(input, { target: { value: "hiddenField" } });
expect(fields).toBeChecked();
expect(nonPublic).not.toBeChecked();
expect(screen.getByRole("treeitem", { name: "hiddenField", selected: true })).toBeVisible();
expect(useStructureOptions.getState()).toMatchObject({ showFields: false, showNonPublic: false });
expect(localStorage.getItem("openidea.structure.options.v1")).toBe(saved);
fireEvent.keyDown(input, { key: "Escape" });
expect(fields).not.toBeChecked();
fireEvent.keyDown(input, { key: "Escape" });
expect(useFileStructurePopup.getState().open).toBe(false);
act(() => useFileStructurePopup.setState({ open: true }));
expect(screen.getByLabelText("Filter symbols")).toHaveValue("");
expect(screen.getByRole("checkbox", { name: "Show fields" })).not.toBeChecked();
expect(useStructureOptions.getState().showFields).toBe(false);
});
it("tries unchecked filters one at a time until a match appears, then restores all on Escape", () => {
useStructureOptions.setState({ showFields: false, showNonPublic: false });
const input = open(filteredItems());
const fields = screen.getByRole("checkbox", { name: "Show fields" });
const nonPublic = screen.getByRole("checkbox", { name: "Show non-public" });
fireEvent.change(input, { target: { value: "hiddenMethod" } });
expect(fields).toBeChecked();
expect(nonPublic).toBeChecked();
expect(screen.getByRole("treeitem", { name: "hiddenMethod", selected: true })).toBeVisible();
expect(useStructureOptions.getState()).toMatchObject({ showFields: false, showNonPublic: false });
fireEvent.keyDown(input, { key: "Escape" });
expect(input).toHaveValue("");
expect(fields).not.toBeChecked();
expect(nonPublic).not.toBeChecked();
expect(screen.getByRole("treeitem", { name: "visible" })).toBeVisible();
});
it("does not immediately re-enable a restored filter after backspace", () => {
useStructureOptions.setState({ showFields: false, showNonPublic: false });
const input = open(filteredItems());
const fields = screen.getByRole("checkbox", { name: "Show fields" });
fireEvent.change(input, { target: { value: "hiddenField" } });
expect(fields).toBeChecked();
fireEvent.change(input, { target: { value: "hiddenFiel" } });
expect(fields).not.toBeChecked();
expect(screen.getByText("No symbols")).toBeInTheDocument();
expect(useStructureOptions.getState().showFields).toBe(false);
});
it("does not auto-enable filters when Narrow down on typing is off", () => {
useStructureOptions.setState({ showFields: false, showNonPublic: false });
const input = open(filteredItems());
act(() => useStructureOptions.setState({ narrowDown: false }));
const fields = screen.getByRole("checkbox", { name: "Show fields" });
const nonPublic = screen.getByRole("checkbox", { name: "Show non-public" });
fireEvent.change(input, { target: { value: "hiddenField" } });
expect(fields).not.toBeChecked();
expect(nonPublic).not.toBeChecked();
expect(screen.queryByRole("treeitem", { name: "hiddenField" })).toBeNull();
expect(useStructureOptions.getState()).toMatchObject({ showFields: false, showNonPublic: false });
});
it("restores an auto-enabled filter on backspace without reverting a manual checkbox change", () => {
useStructureOptions.setState({ showFields: false, showNonPublic: false });
const input = open(filteredItems());
const fields = screen.getByRole("checkbox", { name: "Show fields" });
const nonPublic = screen.getByRole("checkbox", { name: "Show non-public" });
fireEvent.change(input, { target: { value: "hiddenField" } });
expect(fields).toBeChecked();
fireEvent.click(nonPublic);
expect(useStructureOptions.getState().showNonPublic).toBe(true);
fireEvent.change(input, { target: { value: "hiddenFielX" } });
expect(fields).toBeChecked(); // Same-length edits do not trigger IDEA's backspace restore.
fireEvent.change(input, { target: { value: "visible" } });
expect(fields).not.toBeChecked();
expect(nonPublic).toBeChecked();
expect(screen.getByRole("treeitem", { name: "visible", selected: true })).toBeVisible();
expect(screen.queryByRole("treeitem", { name: "hiddenField" })).toBeNull();
expect(useStructureOptions.getState()).toMatchObject({ showFields: false, showNonPublic: true });
fireEvent.keyDown(input, { key: "Escape" });
fireEvent.keyDown(input, { key: "Escape" });
act(() => useFileStructurePopup.setState({ open: true }));
expect(screen.getByRole("checkbox", { name: "Show fields" })).not.toBeChecked();
expect(screen.getByRole("checkbox", { name: "Show non-public" })).toBeChecked();
});
it("temporarily enables Show inherited members and restores it when the query gets shorter", () => {
const input = open([item("Container", "class", 0, [item("own", "method", 2)])]);
const inherited = [{ item: item("inheritedNeedle", "method", 40), path: "/lib/Base.kt", owner: "Base" }];
act(() => useOutline.setState({ inheritedSupported: true, inherited: new Map([["0:4", inherited]]) }));
const checkbox = screen.getByRole("checkbox", { name: "Show inherited members" });
expect(checkbox).not.toBeChecked();
fireEvent.change(input, { target: { value: "inheritedNeedle" } });
expect(checkbox).toBeChecked();
expect(screen.getByRole("treeitem", { name: /^inheritedNeedle/, selected: true })).toBeVisible();
expect(useStructureOptions.getState().showInherited).toBe(false);
fireEvent.change(input, { target: { value: "own" } });
expect(checkbox).not.toBeChecked();
expect(screen.getByRole("treeitem", { name: "own", selected: true })).toBeVisible();
expect(screen.queryByRole("treeitem", { name: /^inheritedNeedle/ })).toBeNull();
expect(useStructureOptions.getState().showInherited).toBe(false);
});
});
it("offers Show inherited members only when the server knows type hierarchies", () => {
open();
expect(screen.queryByLabelText("Show inherited members")).toBeNull();
+30
Переглянути файл
@@ -0,0 +1,30 @@
import { afterEach, expect, it } from "vitest";
import { EditorSelection, EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { _setActiveEditor, type TextEditorHandle } from "@/editor/api";
import { editorSelectionText } from "../index";
const views: EditorView[] = [];
const view = (doc: string, from: number, to: number) => {
const v = new EditorView({
state: EditorState.create({ doc, selection: EditorSelection.single(from, to) }),
parent: document.body,
});
views.push(v);
return v;
};
afterEach(() => {
_setActiveEditor(null);
views.splice(0).forEach((v) => v.destroy());
});
it("takes the selection of the focused editor, such as the Find in Files preview, over the active one", () => {
const main = view("val first = 1", 4, 9);
_setActiveEditor({ view: main } as unknown as TextEditorHandle);
expect(editorSelectionText()).toBe("first");
const preview = view("fun second() {}", 4, 10);
preview.contentDOM.focus();
expect(editorSelectionText()).toBe("second");
preview.contentDOM.blur();
expect(editorSelectionText()).toBe("first");
});
+54 -20
Переглянути файл
@@ -34,13 +34,14 @@ import {
selectRow,
selectedRows,
rowSelectionMode,
showContextMenu,
type RowSelection,
type MenuItem,
T,
} from "@/ui";
import { useFileDecoration } from "@/workbench/contributions";
import { highlightTokens, languageForPath, type CodeToken } from "@/editor/lsp/markdown";
import { badgeKind, basename, openInListOrder, openLocation, relDir } from "../common/open";
import { badgeKind, basename, openInListOrder, openLocation, projectRoot, relDir } from "../common/open";
import { parseLocationQuery } from "../common/query";
import { setTextSearchOption, useFindPopup } from "../find/store";
import { CodePreview, type PreviewHighlight } from "../find/parts";
@@ -441,35 +442,67 @@ function SearchEverywhereDialog() {
/** IDEA's ⌥↵ on an action: record a shortcut for it (written to the active keymap). */
const assignShortcut = (id: string) => closeThen(() => void executeAction("settings.assignShortcut", id));
/** Actions of a file, symbol or text result: IDEA's ⌥↵ menu and the row's context menu. */
const resultMenu = (row: NavigationRow): MenuItem[] => {
const copy = (text: string) => void writeClipboardText(text).catch(() => {});
const folder = row.kind === "file" && row.folder;
const root = projectRoot();
const inProject = !!root && (row.path === root || row.path.startsWith(root.endsWith("/") ? root : `${root}/`));
const items: MenuItem[] = [
{ label: "Open", run: () => activate(row) },
{
label: "Open to the Side",
shortcut: formatBinding("Shift+Enter"),
disabled: !!folder,
run: () => activate(row, true),
},
// IDEA's Select in Project View (Select Opened File): shows a result opened in another
// application (.doc in WPS) in the Project view, where its place in the project is visible.
...(inProject
? [
{
label: "Select in Project View",
shortcut: shortcutLabel("navigate.selectInProjectView") ?? undefined,
run: () => closeThen(() => void executeActionFrom("search", "navigate.selectInProjectView", row.path)),
},
]
: []),
{ kind: "separator" },
];
items.push(
{ label: "Copy Path", run: () => copy(nativePath(row.path)) },
{ label: "Copy Path from Project Root", run: () => copy(row.rel) },
...(row.kind === "symbol" ? [{ label: "Copy Name", run: () => copy(row.name) }] : []),
...(row.kind === "file" || row.kind === "text"
? [
{
label: "Find in Directory…",
run: () => closeThen(() => void executeAction("find.inPath", { directory: dirOf(row.path) })),
},
]
: []),
);
return items;
};
const openIntentions = () => {
const row = activeRow;
if (!row || row.kind === "section" || row.kind === "more" || row.kind === "command") return;
if (row.kind === "action") return row.run ? undefined : assignShortcut(row.id);
const anchor = listRef.current?.querySelector('[data-lead="true"]') ?? inputRef.current;
if (!anchor) return;
const copy = (text: string) => void writeClipboardText(text).catch(() => {});
const items: MenuItem[] =
row.kind === "setting"
? [{ label: "Open Settings Page", run: () => activate(row) }]
: [
{ label: "Open", run: () => activate(row) },
{ label: "Open to the Side", shortcut: formatBinding("Shift+Enter"), run: () => activate(row, true) },
{ kind: "separator" },
{ label: "Copy Path", run: () => copy(nativePath(row.path)) },
{ label: "Copy Path from Project Root", run: () => copy(row.rel) },
...(row.kind === "symbol" ? [{ label: "Copy Name", run: () => copy(row.name) }] : []),
...(row.kind === "file" || row.kind === "text"
? [
{
label: "Find in Directory…",
run: () => closeThen(() => void executeAction("find.inPath", { directory: dirOf(row.path) })),
},
]
: []),
];
row.kind === "setting" ? [{ label: "Open Settings Page", run: () => activate(row) }] : resultMenu(row);
setMenu({ anchor, items, placement: "right-start" });
};
const onRowContextMenu = (row: SeRow, index: number, e: MouseEvent) => {
if (row.kind !== "file" && row.kind !== "symbol" && row.kind !== "text") return;
e.preventDefault();
select(index, e);
showContextMenu(e, resultMenu(row));
};
const onKeyDown = (e: KeyboardEvent<HTMLInputElement>) => {
if (isImeKey(e.nativeEvent)) return;
if (tab === "text" && e.altKey && !e.metaKey && !e.ctrlKey && !e.shiftKey) {
@@ -574,6 +607,7 @@ function SearchEverywhereDialog() {
if (preview && previewOf(r) && e.type === "click" && e.detail !== 2) return;
activate(r, e.shiftKey);
}}
onContextMenu={onRowContextMenu}
focusable={false}
rowHeight={rowHeight}
sectionHeight={rowHeight}
+8 -2
Переглянути файл
@@ -3,6 +3,7 @@
* Recent Files / Recent Locations, Find / Replace in Files + the Find tool
* window, the Structure tool window + File Structure popup, and bookmarks.
*/
import { EditorView } from "@codemirror/view";
import { lazyComponent, lazyWhen } from "@/ui";
import { activeEditor, focusedCellEditor, registerEditorContribution } from "@/editor/api";
import { executeAction, registerActions } from "@/platform/actions";
@@ -82,8 +83,13 @@ async function removeMissingBookmarks(removed: readonly string[]) {
}
/** Single-line editor selection, used to prefill search fields. */
function editorSelectionText(): string | null {
const view = activeEditor()?.view;
/**
* The single-line selection a search starts from: the focused editor's (a Find in Files preview,
* a diff pane), else the active editor's, as IDEA reads it from the editor in the action's context.
*/
export function editorSelectionText(): string | null {
const focused = document.activeElement?.closest(".cm-editor");
const view = (focused instanceof HTMLElement ? EditorView.findFromDOM(focused) : null) ?? activeEditor()?.view;
if (!view) return null;
const { from, to } = view.state.selection.main;
if (from === to || to - from > 200) return null;
+97 -14
Переглянути файл
@@ -33,7 +33,16 @@ import {
widgetLetter,
type OutlineNode,
} from "./outline";
import { useCollapsedStructure, useLiveOutline, useOutline, useOutlineNodes, useStructureOptions } from "./store";
import {
getOutlineNodes,
releaseInheritedMembers,
requestInheritedMembers,
useCollapsedStructure,
useLiveOutline,
useOutline,
useOutlineNodes,
useStructureOptions,
} from "./store";
import styles from "./StructureView.module.css";
import { tx } from "@/platform/i18n";
@@ -301,8 +310,30 @@ export function FileStructureOverlay() {
const POPUP_ROW = 22;
type TemporaryFilter = "showFields" | "showNonPublic" | "showInherited";
interface AutoFilter {
key: TemporaryFilter;
queryLength: number;
}
interface PopupFilters {
showFields: boolean;
showNonPublic: boolean;
showInherited: boolean;
}
const TEMPORARY_FILTERS: readonly TemporaryFilter[] = ["showFields", "showNonPublic", "showInherited"];
function effectivePopupFilters(options: PopupFilters, autoFilters: readonly AutoFilter[]): PopupFilters {
const enabled = (key: TemporaryFilter) => autoFilters.some((entry) => entry.key === key);
return {
showFields: options.showFields || enabled("showFields"),
showNonPublic: options.showNonPublic || enabled("showNonPublic"),
showInherited: options.showInherited || enabled("showInherited"),
};
}
function FileStructureDialog() {
useLiveOutline();
useEffect(() => () => releaseInheritedMembers(), []);
const rowHeight = useRowHeight(POPUP_ROW);
const path = useOutline((s) => s.path);
const items = useOutline((s) => s.items);
@@ -313,8 +344,13 @@ function FileStructureDialog() {
const showNonPublic = useStructureOptions((s) => s.showNonPublic);
const showInherited = useStructureOptions((s) => s.showInherited);
const inheritedSupported = useOutline((s) => s.inheritedSupported);
const nodes = useOutlineNodes();
const [query, setQuery] = useState("");
const [autoFilters, setAutoFilters] = useState<AutoFilter[]>([]);
const effectiveOptions = useMemo(
() => effectivePopupFilters({ showFields, showNonPublic, showInherited }, autoFilters),
[showFields, showNonPublic, showInherited, autoFilters],
);
const nodes = useOutlineNodes(false, effectiveOptions);
const [showOptions, setShowOptions] = useState(false);
// IDEA opens the popup fully expanded.
const [collapsed, setCollapsed] = useState<ReadonlySet<string>>(() => new Set());
@@ -351,7 +387,10 @@ function FileStructureDialog() {
else tree.current?.clearSelection();
}, [query, hasQuery, caretKey, filter.preferred, filter.nodes]);
const close = () => useFileStructurePopup.setState({ open: false });
const close = () => {
releaseInheritedMembers();
useFileStructurePopup.setState({ open: false });
};
const choose = (node: OutlineNode | undefined) => {
if (!node || !path) return;
close();
@@ -365,6 +404,53 @@ function FileStructureDialog() {
return next;
});
const availableFilters: Record<TemporaryFilter, boolean> = {
showFields: hasFields(items ?? []),
showNonPublic: hasVisibility(items ?? []),
showInherited: inheritedSupported,
};
const changeQuery = (nextQuery: string) => {
setQuery(nextQuery);
setCollapsed(new Set());
let nextAuto = autoFilters;
if (nextQuery.length < query.length) {
// IDEA restores every auto-click whose query was at least this long, newest first.
nextAuto = autoFilters.filter((entry) => entry.queryLength < nextQuery.length);
if (nextAuto.length !== autoFilters.length) {
if (
autoFilters.some((entry) => entry.key === "showInherited") &&
!nextAuto.some((entry) => entry.key === "showInherited")
)
releaseInheritedMembers();
setAutoFilters(nextAuto);
return;
}
}
if (!nextQuery.trim() || !narrowDown) {
setAutoFilters(nextAuto);
return;
}
const persisted = useStructureOptions.getState();
let options = effectivePopupFilters(persisted, nextAuto);
const hasMatch = () => filterOutline(getOutlineNodes(false, options), nextQuery, narrowDown).best !== null;
if (!hasMatch()) {
for (const key of TEMPORARY_FILTERS) {
if (options[key] || !availableFilters[key]) continue;
nextAuto = [{ key, queryLength: nextQuery.length }, ...nextAuto];
options = effectivePopupFilters(persisted, nextAuto);
if (key === "showInherited") requestInheritedMembers();
if (hasMatch()) break;
}
}
setAutoFilters(nextAuto);
};
const changeFilter = (key: TemporaryFilter, value: boolean) => {
// A manual edit takes ownership of the checkbox; later backspaces must not undo it.
setAutoFilters((entries) => entries.filter((entry) => entry.key !== key));
if (key === "showInherited") releaseInheritedMembers();
useStructureOptions.setState({ [key]: value });
};
const onKeyDown = (e: KeyboardEvent<HTMLInputElement>) => {
const lead = tree.current?.leadKey() ?? null;
const node = lead ? byKey.get(lead) : undefined;
@@ -377,7 +463,7 @@ function FileStructureDialog() {
// The first Esc clears the filter, the next one closes the popup.
if (!query) return;
e.stopPropagation();
setQuery("");
changeQuery("");
break;
case "ArrowDown":
case "ArrowUp": {
@@ -437,22 +523,22 @@ function FileStructureDialog() {
{(hasFields(items ?? []) || !showFields) && (
<Checkbox
label="Show fields"
checked={showFields}
onChange={(v) => useStructureOptions.setState({ showFields: v })}
checked={effectiveOptions.showFields}
onChange={(v) => changeFilter("showFields", v)}
/>
)}
{hasVisibility(items ?? []) && (
<Checkbox
label="Show non-public"
checked={showNonPublic}
onChange={(v) => useStructureOptions.setState({ showNonPublic: v })}
checked={effectiveOptions.showNonPublic}
onChange={(v) => changeFilter("showNonPublic", v)}
/>
)}
{inheritedSupported && (
<Checkbox
label="Show inherited members"
checked={showInherited}
onChange={(v) => useStructureOptions.setState({ showInherited: v })}
checked={effectiveOptions.showInherited}
onChange={(v) => changeFilter("showInherited", v)}
/>
)}
</div>
@@ -496,10 +582,7 @@ function FileStructureDialog() {
aria-label={tx("Filter symbols")}
spellCheck={false}
autoComplete="off"
onChange={(e) => {
setQuery(e.target.value);
setCollapsed(new Set());
}}
onChange={(e) => changeQuery(e.target.value)}
onKeyDown={onKeyDown}
/>
{hasQuery && !narrowDown && !filter.best && filter.nodes.length > 0 && (
+36 -5
Переглянути файл
@@ -47,6 +47,8 @@ let consumers = 0;
let stop: (() => void) | null = null;
let seq = 0;
let flutterSeq = 0;
let reloadOutline: (() => void) | null = null;
let inheritedRequest: { doc: number; path: string } | null = null;
/** A backend document id for `path` while `fn` runs (open editors are reused). */
async function withDoc<T>(path: string, fn: (doc: number) => Promise<T>): Promise<T> {
@@ -99,16 +101,31 @@ async function loadInherited(doc: number, path: string, items: readonly OutlineI
? true
: await probeHierarchy(doc, types);
if (my !== seq) return;
if (!supported || !useStructureOptions.getState().showInherited) {
const requested = inheritedRequest?.doc === doc && inheritedRequest.path === path;
if (!supported || !(useStructureOptions.getState().showInherited || requested)) {
if (requested) inheritedRequest = null;
useOutline.setState({ inheritedSupported: supported, inherited: null });
return;
}
useOutline.setState({ inheritedSupported: true });
const deps = inheritedDeps(path, doc, language === "python");
const entries = await Promise.all(
types.map(async (t) => [typeKey(t), await inheritedMembers(path, t, deps).catch(() => [])] as const),
);
if (my === seq)
useOutline.setState({ inheritedSupported: true, inherited: new Map(entries.filter(([, m]) => m.length)) });
if (my === seq) useOutline.setState({ inherited: new Map(entries.filter(([, m]) => m.length)) });
}
/** Loads inherited members for a temporary popup filter without changing persisted options. */
export function requestInheritedMembers() {
const { doc, path, inherited } = useOutline.getState();
if (doc === null || path === null) return;
inheritedRequest = { doc, path };
if (inherited === null) reloadOutline?.();
}
/** Ends a popup's temporary inherited-member request when its filter is restored or it closes. */
export function releaseInheritedMembers() {
inheritedRequest = null;
}
async function loadFlutter(doc: number, language: string) {
@@ -153,6 +170,7 @@ function start(): () => void {
if (!ctx) {
seq++;
flutterSeq++;
inheritedRequest = null;
useOutline.setState({
path: null,
doc: null,
@@ -167,6 +185,7 @@ function start(): () => void {
}
void load(ctx.doc, ctx.path, ctx.language);
};
reloadOutline = reloadNow;
reloadNow();
const unsubActive = useEditorRegistry.subscribe((s, prev) => {
if (s.active?.ctx.doc !== prev.active?.ctx.doc || s.active?.ctx.path !== prev.active?.ctx.path) reloadNow();
@@ -188,6 +207,8 @@ function start(): () => void {
return () => {
clearTimeout(timer);
flutterSeq++;
if (reloadOutline === reloadNow) reloadOutline = null;
inheritedRequest = null;
unsubFlutter();
unsubActive();
unsubInherited();
@@ -268,6 +289,8 @@ const outlinePreferences = (s: StructureOptions) => ({
showOnlyWidgets: s.showOnlyWidgets,
});
type OutlinePreferences = ReturnType<typeof outlinePreferences>;
function outlineNodes(
items: OutlineState["items"],
flutter: OutlineState["flutter"],
@@ -285,12 +308,20 @@ function outlineNodes(
return flutter && options.showOnlyWidgets ? onlyWidgets(nodes) : nodes;
}
export function useOutlineNodes(widgets = false) {
/** Snapshot builder for query-event transitions, which cannot call hooks. */
export function getOutlineNodes(widgets = false, overrides?: Partial<OutlinePreferences>) {
const { items, flutter, inheritedSupported, inherited } = useOutline.getState();
const options = { ...outlinePreferences(useStructureOptions.getState()), ...overrides };
return outlineNodes(items, widgets ? flutter : null, inheritedSupported ? inherited : null, options);
}
export function useOutlineNodes(widgets = false, overrides?: Partial<OutlinePreferences>) {
const items = useOutline((s) => s.items);
const flutter = useOutline((s) => (widgets ? s.flutter : null));
const inherited = useOutline((s) => (s.inheritedSupported ? s.inherited : null));
const options = useStructureOptions(useShallow(outlinePreferences));
return useMemo(() => outlineNodes(items, flutter, inherited, options), [items, flutter, inherited, options]);
const effective = useMemo(() => (overrides ? { ...options, ...overrides } : options), [options, overrides]);
return useMemo(() => outlineNodes(items, flutter, inherited, effective), [items, flutter, inherited, effective]);
}
function collapseStructure() {
+18 -1
Переглянути файл
@@ -15,7 +15,14 @@ import {
type ReactNode,
type Ref,
} from "react";
import { defaultRangeExtractor, elementScroll, useVirtualizer, type Range } from "@tanstack/react-virtual";
import {
defaultRangeExtractor,
elementScroll,
measureElement,
observeElementRect,
useVirtualizer,
type Range,
} from "@tanstack/react-virtual";
import clsx from "clsx";
import { tx } from "@/platform/i18n";
import { relativeDir, useProject } from "@/platform/project";
@@ -278,6 +285,16 @@ export function CombinedDiffView({
estimateSize: () => ESTIMATE,
overscan: 4,
rangeExtractor,
// A view with no height (hidden behind a maximized tool window) makes the library render nothing,
// skipping `rangeExtractor`: report at least 1 px so the focused and unsaved blocks stay mounted.
observeElementRect: (instance, cb) =>
observeElementRect(instance, (rect) => cb({ ...rect, height: Math.max(rect.height, 1) })),
// While the view is hidden its blocks are 0 px tall: recording that would collapse every block onto
// one offset and mount them all. Keep the last known size (or the estimate) instead.
measureElement: (node, entry, instance) =>
measureElement(node, entry, instance) ||
instance.itemSizeCache.get(keys[instance.indexFromElement(node)]!) ||
ESTIMATE,
// A correction for a block above moves the view by its delta from wherever it is now: a `scrollTo`
// (the library's offset plus the delta) can drop wheel scrolling still in flight in WebKit.
scrollToFn: (offset, options, instance) => {
+76
Переглянути файл
@@ -144,6 +144,82 @@ describe("the all-in-one diff, staged edits", () => {
expect(block(paths[0]!)).not.toBeNull();
});
it("with autosave off, keeps them while the view has no height, as when a maximized tool window hides it", async () => {
let height = 600;
const observers: Array<(entries: unknown[]) => void> = [];
vi.stubGlobal(
"ResizeObserver",
class {
constructor(cb: (entries: unknown[]) => void) {
observers.push(cb);
}
observe() {}
unobserve() {}
disconnect() {}
},
);
const heightOf = Object.getOwnPropertyDescriptor(HTMLElement.prototype, "clientHeight")!;
Object.defineProperty(HTMLElement.prototype, "clientHeight", { configurable: true, get: () => height });
try {
await editAndScrollAway(false);
height = 0;
act(() => observers.forEach((cb) => cb([])));
await act(() => new Promise((r) => setTimeout(r, 20)));
expect(savedStaged).toEqual([]);
expect(block(paths[0]!)).not.toBeNull();
} finally {
Object.defineProperty(HTMLElement.prototype, "clientHeight", heightOf);
vi.unstubAllGlobals();
}
});
it("with autosave off, keeps them and mounts only a few blocks while the blocks themselves have no height", async () => {
let height = 600;
const watched = new Set<Element>();
const observers: Array<(entries: unknown[]) => void> = [];
vi.stubGlobal(
"ResizeObserver",
class {
constructor(cb: (entries: unknown[]) => void) {
observers.push(cb);
}
observe(el: Element) {
watched.add(el);
}
unobserve(el: Element) {
watched.delete(el);
}
disconnect() {}
},
);
const descriptors = (["clientHeight", "offsetHeight"] as const).map(
(name) => [name, Object.getOwnPropertyDescriptor(HTMLElement.prototype, name)!] as const,
);
for (const [name] of descriptors)
Object.defineProperty(HTMLElement.prototype, name, { configurable: true, get: () => height });
try {
savedStaged.length = 0;
useProject.setState({ settings: { files: { autoSave: false } } as never });
render(<CombinedDiffTab input={combinedDiffInput({ items: staged })} />);
const view = await editableSide(paths[0]!, "b");
act(() => view.dispatch({ changes: { from: 0, insert: "EDIT " }, userEvent: "input" }));
// `display: none` on the island: the container and every block measure 0 px.
height = 0;
act(() =>
observers.forEach((cb) =>
cb([...watched].map((target) => ({ target, borderBoxSize: [{ blockSize: 0, inlineSize: 0 }] }))),
),
);
await act(() => new Promise((r) => setTimeout(r, 20)));
expect(savedStaged).toEqual([]);
expect(block(paths[0]!)).not.toBeNull();
expect(document.querySelectorAll("[data-combined-block]").length).toBeLessThanOrEqual(6);
} finally {
for (const [name, descriptor] of descriptors) Object.defineProperty(HTMLElement.prototype, name, descriptor);
vi.unstubAllGlobals();
}
});
it("with autosave on, saves them to the index once scrolled away", async () => {
await editAndScrollAway(true);
expect(block(paths[0]!)).toBeNull();
+36 -7
Переглянути файл
@@ -85,7 +85,7 @@ import { wheelZoomStep } from "@/platform/wheelZoom";
import { iconNode } from "@/ui/iconNode";
import { isMarkdownPath } from "../fileKinds";
import { attachPanZoom } from "../panZoom";
import { imageUrl } from "../previewImages";
import { createPreviewImageLoader } from "../previewImages";
/**
* Line of the heading `anchor` in the Markdown file `path`, from an open editor's text (unsaved
@@ -480,7 +480,18 @@ function MarkdownPreview({ path, tabId, sync }: { path: string; tabId: string; s
let live = true;
const size = (img: HTMLImageElement, intrinsic?: { w: number; h: number } | null) =>
applyImageZoomWidth(img, intrinsic, img.closest<HTMLElement>(`.${IMAGE_ZOOM}`) ?? img);
const resetImageSize = (img: HTMLImageElement) => {
const box = img.closest<HTMLElement>(`.${IMAGE_ZOOM}`) ?? img;
delete img.dataset.naturalWidth;
delete box.dataset.naturalWidth;
box.style.removeProperty("--image-width");
};
const bindImageUrl = (img: HTMLImageElement, url: string, asyncLoad: boolean) => {
const changed = img.getAttribute("src") !== url;
if (changed && img.hasAttribute("src")) {
resetImageSize(img);
size(img);
}
const svgSize = svgDataUrlSize(url);
if (svgSize && size(img, svgSize) && asyncLoad) {
setDiagramsDrawn((n) => n + 1);
@@ -495,11 +506,31 @@ function MarkdownPreview({ path, tabId, sync }: { path: string; tabId: string; s
setDiagramsDrawn((n) => n + 1);
}
};
if (img.getAttribute("src") !== url) img.src = url;
if (!img.hasAttribute("data-natural-width") && img.complete && img.naturalWidth > 0 && img.naturalHeight > 0) {
if (changed) img.src = url;
// Only trust synchronous naturalWidth when `src` did not change: right after assigning a new `src`,
// browsers still report the previous image's `complete` / `naturalWidth` until the new decode finishes.
if (
!changed &&
!img.hasAttribute("data-natural-width") &&
img.complete &&
img.naturalWidth > 0 &&
img.naturalHeight > 0
) {
size(img, { w: img.naturalWidth, h: img.naturalHeight });
}
};
const images = createPreviewImageLoader(
(img, url) => {
img.classList.remove(styles.blocked!);
bindImageUrl(img, url, true);
},
(img) => {
resetImageSize(img);
img.removeAttribute("src");
img.classList.add(styles.blocked!);
setDiagramsDrawn((n) => n + 1);
},
);
const imgs = [...root.querySelectorAll<HTMLImageElement>("img[data-src]")];
imgs.forEach((img) => {
attachImagePanZoom(img);
@@ -515,10 +546,7 @@ function MarkdownPreview({ path, tabId, sync }: { path: string; tabId: string; s
img.title = "Remote images are not loaded";
return;
}
imageUrl(target.path).then(
(url) => live && bindImageUrl(img, url, true),
() => live && img.classList.add(styles.blocked!),
);
images.load(img, target.path);
});
root.querySelectorAll<HTMLElement>("pre > code").forEach((code) => {
const pre = code.parentElement!;
@@ -531,6 +559,7 @@ function MarkdownPreview({ path, tabId, sync }: { path: string; tabId: string; s
});
return () => {
live = false;
images.dispose();
for (const img of imgs) img.onload = null;
};
}, [html, path]);
+306
Переглянути файл
@@ -0,0 +1,306 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { act, cleanup, render, screen, waitFor } from "@testing-library/react";
import { Text } from "@codemirror/state";
import * as ipc from "@/platform/ipc";
import { emitLocalIdeEvent } from "@/platform/ipc";
import { useLiveMarkdown } from "./markdown/live";
import { MarkdownEditor } from "./markdown/MarkdownEditor";
import { useMarkdownModes } from "./markdown/modes";
import { imageUrl } from "./previewImages";
import { useLiveRst } from "./rst/live";
import { RstEditor } from "./rst/RstEditor";
import { rstModes } from "./rst/RstLayoutActions";
const svgUrl = (width: number, height: number) =>
`data:image/svg+xml;base64,${btoa(`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${width} ${height}"></svg>`)}`;
const liveDoc = (lines: string[]) => ({
text: Text.of(lines),
topLine: 0,
sourceAtEnd: false,
scrollSeq: 0,
fontZoom: 0,
previewTop: 0,
caretLine: 0,
caretSeq: 0,
});
describe("preview image disk refresh", () => {
afterEach(() => {
cleanup();
vi.restoreAllMocks();
});
beforeEach(() => {
localStorage.clear();
useMarkdownModes.setState({ byTab: {}, fallback: "split" });
rstModes.useModes.setState({ byTab: {}, fallback: "split" });
useLiveMarkdown.setState({}, true);
useLiveRst.setState({}, true);
});
it("evicts cached image URLs on file and parent-directory fsChanged without dropping unrelated paths", async () => {
let version = 1;
const fsReadImage = vi.spyOn(ipc.commands, "fsReadImage").mockImplementation(async (path: string) => ({
status: "ok",
data: `data:image/png;base64,${path}:v${version}`,
}));
const a1 = await imageUrl("/p/cache/a.png");
const b1 = await imageUrl("/p/cache/b.png");
const dirImg1 = await imageUrl("/p/cache/assets/diagram.png");
expect(await imageUrl("/p/cache/a.png")).toBe(a1);
expect(fsReadImage).toHaveBeenCalledTimes(3);
version = 2;
emitLocalIdeEvent({
type: "fsChanged",
created: [],
modified: ["/p/cache/a.png"],
removed: [],
});
expect(await imageUrl("/p/cache/a.png")).toBe("data:image/png;base64,/p/cache/a.png:v2");
expect(await imageUrl("/p/cache/b.png")).toBe(b1);
expect(fsReadImage).toHaveBeenCalledTimes(4);
version = 3;
emitLocalIdeEvent({
type: "fsChanged",
created: ["/p/cache/assets"],
modified: [],
removed: [],
});
expect(await imageUrl("/p/cache/assets/diagram.png")).toBe("data:image/png;base64,/p/cache/assets/diagram.png:v3");
expect(dirImg1).toBe("data:image/png;base64,/p/cache/assets/diagram.png:v1");
expect(await imageUrl("/p/cache/b.png")).toBe(b1);
});
it("keeps a newer reload when an earlier in-flight read rejects or resolves late", async () => {
const imgPath = "/p/md-race/shot.png";
const mdPath = "/p/md-race/README.md";
const resolvers: Array<{ resolve: (v: { status: "ok"; data: string }) => void; reject: (e: Error) => void }> = [];
vi.spyOn(ipc.commands, "fsReadImage").mockImplementation(
() =>
new Promise((resolve, reject) => {
resolvers.push({ resolve, reject });
}),
);
useMarkdownModes.setState({ byTab: { t: "preview" }, fallback: "split" });
useLiveMarkdown.setState({ [mdPath]: liveDoc(["![Shot](./shot.png)"]) });
render(
<MarkdownEditor path={mdPath} tabId="t">
<div />
</MarkdownEditor>,
);
await waitFor(() => expect(resolvers).toHaveLength(1));
act(() => {
emitLocalIdeEvent({ type: "fsChanged", created: [], modified: [imgPath], removed: [] });
});
await waitFor(() => expect(resolvers).toHaveLength(2));
act(() => {
resolvers[1]!.resolve({ status: "ok", data: "data:image/png;base64,FRESH" });
});
const preview = screen.getByRole("document", { name: "Markdown preview" });
await waitFor(() => {
expect(preview.querySelector<HTMLImageElement>('img[alt="Shot"]')?.getAttribute("src")).toBe(
"data:image/png;base64,FRESH",
);
});
act(() => {
resolvers[0]!.reject(new Error("stale read failed"));
});
await act(async () => {});
expect(preview.querySelector<HTMLImageElement>('img[alt="Shot"]')?.getAttribute("src")).toBe(
"data:image/png;base64,FRESH",
);
expect(await imageUrl(imgPath)).toBe("data:image/png;base64,FRESH");
});
it("reloads Markdown preview images on fsChanged, updates dimensions, and recovers after removal", async () => {
const imgPath = "/p/md-reload/diagram.svg";
const mdPath = "/p/md-reload/README.md";
let current: string | null = svgUrl(320, 180);
vi.spyOn(ipc.commands, "fsReadImage").mockImplementation(async (path: string) => {
if (path === imgPath && current !== null) return { status: "ok", data: current };
return { status: "error", error: { kind: "notFound", message: path } } as never;
});
useMarkdownModes.setState({ byTab: { t: "preview" }, fallback: "split" });
useLiveMarkdown.setState({ [mdPath]: liveDoc(["![Diagram](./diagram.svg)"]) });
render(
<MarkdownEditor path={mdPath} tabId="t">
<div />
</MarkdownEditor>,
);
const preview = screen.getByRole("document", { name: "Markdown preview" });
await waitFor(() => {
const img = preview.querySelector<HTMLImageElement>('img[alt="Diagram"]');
expect(img?.getAttribute("src")).toBe(svgUrl(320, 180));
});
const img = preview.querySelector<HTMLImageElement>('img[alt="Diagram"]')!;
const box = img.closest<HTMLElement>(".image-zoom") ?? img;
expect(box.style.getPropertyValue("--image-width")).toBe("320px");
current = svgUrl(640, 240);
act(() => {
emitLocalIdeEvent({ type: "fsChanged", created: [], modified: [imgPath], removed: [] });
});
await waitFor(() => {
expect(img.getAttribute("src")).toBe(svgUrl(640, 240));
expect(box.style.getPropertyValue("--image-width")).toBe("640px");
});
current = null;
act(() => {
emitLocalIdeEvent({ type: "fsChanged", created: [], modified: [], removed: [imgPath] });
});
await waitFor(() => {
expect(img.getAttribute("src")).toBeNull();
expect(img.hasAttribute("data-natural-width")).toBe(false);
expect(box.style.getPropertyValue("--image-width")).toBe("");
});
current = svgUrl(480, 200);
act(() => {
emitLocalIdeEvent({ type: "fsChanged", created: [imgPath], modified: [], removed: [] });
});
await waitFor(() => {
expect(img.getAttribute("src")).toBe(svgUrl(480, 200));
expect(box.style.getPropertyValue("--image-width")).toBe("480px");
});
});
it("updates raster image width on reload even when old naturalWidth is still reported synchronously", async () => {
const imgPath = "/p/md-raster/shot.png";
const mdPath = "/p/md-raster/README.md";
let current = "data:image/png;base64,V1";
vi.spyOn(ipc.commands, "fsReadImage").mockImplementation(async (path: string) => {
if (path === imgPath) return { status: "ok", data: current };
return { status: "error", error: { kind: "notFound", message: path } } as never;
});
useMarkdownModes.setState({ byTab: { t: "preview" }, fallback: "split" });
useLiveMarkdown.setState({ [mdPath]: liveDoc(["![Shot](./shot.png)"]) });
render(
<MarkdownEditor path={mdPath} tabId="t">
<div />
</MarkdownEditor>,
);
const preview = screen.getByRole("document", { name: "Markdown preview" });
await waitFor(() => {
expect(preview.querySelector<HTMLImageElement>('img[alt="Shot"]')?.getAttribute("src")).toBe(
"data:image/png;base64,V1",
);
});
const img = preview.querySelector<HTMLImageElement>('img[alt="Shot"]')!;
const box = img.closest<HTMLElement>(".image-zoom") ?? img;
let naturalWidth = 960;
let naturalHeight = 600;
Object.defineProperty(img, "complete", { get: () => true, configurable: true });
Object.defineProperty(img, "naturalWidth", { get: () => naturalWidth, configurable: true });
Object.defineProperty(img, "naturalHeight", { get: () => naturalHeight, configurable: true });
act(() => {
img.dispatchEvent(new Event("load"));
});
expect(box.style.getPropertyValue("--image-width")).toBe("960px");
// Simulate HTML spec: right after `img.src = newUrl`, `complete` is still true and `naturalWidth` is still 960
// until the new image decodes and fires `load`.
current = "data:image/png;base64,V2";
act(() => {
emitLocalIdeEvent({ type: "fsChanged", created: [], modified: [imgPath], removed: [] });
});
await waitFor(() => {
expect(img.getAttribute("src")).toBe("data:image/png;base64,V2");
});
expect(img.hasAttribute("data-natural-width")).toBe(false);
naturalWidth = 420;
naturalHeight = 280;
act(() => {
img.dispatchEvent(new Event("load"));
});
expect(box.style.getPropertyValue("--image-width")).toBe("420px");
});
it("reloads reStructuredText preview images when modified on disk", async () => {
const rstPath = "/p/rst-reload/index.rst";
const imgPath = "/p/rst-reload/chart.png";
let current: string | null = "data:image/png;base64,OLD";
vi.spyOn(ipc.commands, "rstPreview").mockResolvedValue({
status: "ok",
data: '<main><img alt="Chart" src="chart.png" /></main>',
});
vi.spyOn(ipc.commands, "fsReadImage").mockImplementation(async (path: string) => {
if (path === imgPath && current !== null) return { status: "ok", data: current };
return { status: "error", error: { kind: "notFound", message: path } } as never;
});
useLiveRst.setState({ [rstPath]: "Title\n=====\n" });
render(
<RstEditor path={rstPath} tabId="t">
<div />
</RstEditor>,
);
const preview = document.querySelector<HTMLElement>('[aria-label="reStructuredText preview"]')!;
await waitFor(() => {
expect(preview.querySelector<HTMLImageElement>('img[alt="Chart"]')?.getAttribute("src")).toBe(
"data:image/png;base64,OLD",
);
});
current = "data:image/png;base64,NEW";
act(() => {
emitLocalIdeEvent({ type: "fsChanged", created: [], modified: [imgPath], removed: [] });
});
await waitFor(() => {
expect(preview.querySelector<HTMLImageElement>('img[alt="Chart"]')?.getAttribute("src")).toBe(
"data:image/png;base64,NEW",
);
});
current = null;
act(() => {
emitLocalIdeEvent({ type: "fsChanged", created: [], modified: [], removed: [imgPath] });
});
await waitFor(() => {
expect(preview.querySelector<HTMLImageElement>('img[alt="Chart"]')?.getAttribute("src")).toBeNull();
});
current = "data:image/png;base64,RESTORED";
act(() => {
emitLocalIdeEvent({ type: "fsChanged", created: [imgPath], modified: [], removed: [] });
});
await waitFor(() => {
expect(preview.querySelector<HTMLImageElement>('img[alt="Chart"]')?.getAttribute("src")).toBe(
"data:image/png;base64,RESTORED",
);
});
});
});
+88 -7
Переглянути файл
@@ -1,16 +1,97 @@
import { call, commands } from "@/platform/ipc";
import { call, commands, onIdeEvent } from "@/platform/ipc";
import { isSameOrInside } from "@/platform/paths";
/** Loaded local images by absolute path (data URLs), shared by all previews. */
const imageCache = new Map<string, Promise<string>>();
const IMAGE_CACHE_LIMIT = 64;
type ImageChangeListener = (changed: readonly string[]) => void;
const listeners = new Set<ImageChangeListener>();
let offFs: (() => void) | null = null;
function matchesChanged(path: string, changed: readonly string[]): boolean {
return changed.some((entry) => isSameOrInside(path, entry));
}
function ensureWatching(): void {
offFs ??= onIdeEvent("fsChanged", (e) => {
const changed = [...e.created, ...e.modified, ...e.removed];
if (!changed.length) return;
for (const cached of [...imageCache.keys()]) {
if (matchesChanged(cached, changed)) imageCache.delete(cached);
}
for (const listener of [...listeners]) listener(changed);
});
}
export function imageUrl(path: string): Promise<string> {
let p = imageCache.get(path);
if (!p) {
p = call(commands.fsReadImage(path));
p.catch(() => imageCache.delete(path));
ensureWatching();
let pending = imageCache.get(path);
if (!pending) {
const request = call(commands.fsReadImage(path));
request.catch(() => {
if (imageCache.get(path) === request) imageCache.delete(path);
});
if (imageCache.size >= IMAGE_CACHE_LIMIT) imageCache.delete(imageCache.keys().next().value!);
imageCache.set(path, p);
imageCache.set(path, request);
pending = request;
}
return p;
return pending;
}
/** Loads local preview images and reloads them whenever their disk paths change. */
export function createPreviewImageLoader(
onLoad: (img: HTMLImageElement, url: string) => void,
onError: (img: HTMLImageElement) => void,
) {
let active = true;
const groups = new Map<string, { imgs: HTMLImageElement[]; gen: number }>();
let off: (() => void) | null = null;
const apply = (
path: string,
group: { imgs: HTMLImageElement[]; gen: number },
targets: readonly HTMLImageElement[],
) => {
const gen = group.gen;
imageUrl(path).then(
(url) => {
if (!active || group.gen !== gen) return;
for (const img of targets) onLoad(img, url);
},
() => {
if (!active || group.gen !== gen) return;
for (const img of targets) onError(img);
},
);
};
return {
load(img: HTMLImageElement, path: string) {
let group = groups.get(path);
if (!group) {
group = { imgs: [], gen: 0 };
groups.set(path, group);
if (!off) {
ensureWatching();
const onChanged: ImageChangeListener = (changed) => {
for (const [watchedPath, watchedGroup] of groups) {
if (!matchesChanged(watchedPath, changed)) continue;
watchedGroup.gen++;
apply(watchedPath, watchedGroup, watchedGroup.imgs);
}
};
listeners.add(onChanged);
off = () => listeners.delete(onChanged);
}
}
group.imgs.push(img);
apply(path, group, [img]);
},
dispose() {
active = false;
off?.();
groups.clear();
},
};
}
+15 -15
Переглянути файл
@@ -13,7 +13,7 @@ import { maybeEditorService } from "@/workbench/contributions";
import { EmptyState, FloatingToolbar, Spinner, SplitGroup, SplitHandle, SplitPanel, selectableText } from "@/ui";
import { modeOf } from "../layoutModes";
import { ANCHOR_PREFIX, resolveLink, sanitizePreviewHtml } from "../markdown/render";
import { imageUrl } from "../previewImages";
import { createPreviewImageLoader } from "../previewImages";
import { useLiveRst } from "./live";
import { RstLayoutActions, rstModes } from "./RstLayoutActions";
import styles from "../markdown/Markdown.module.css";
@@ -25,10 +25,20 @@ const DEFAULT_SPLIT_LAYOUT = { editor: 50, preview: 50 };
type Rendered = { html: string } | { error: string };
/** Puts docutils' `html` into `root`: sanitized, local images loaded, code highlighted. */
function fill(root: HTMLElement, html: string, path: string, isLive: () => boolean) {
function fill(root: HTMLElement, html: string, path: string) {
const template = document.createElement("template");
template.innerHTML = sanitizePreviewHtml(html);
root.replaceChildren(template.content);
const images = createPreviewImageLoader(
(img, url) => {
img.classList.remove(styles.blocked!);
if (img.getAttribute("src") !== url) img.src = url;
},
(img) => {
img.removeAttribute("src");
img.classList.add(styles.blocked!);
},
);
root.querySelectorAll<HTMLImageElement>("img[data-src]").forEach((img) => {
const src = img.dataset.src ?? "";
if (/^data:image\//i.test(src)) {
@@ -41,19 +51,13 @@ function fill(root: HTMLElement, html: string, path: string, isLive: () => boole
img.title = tx("Remote images are not loaded");
return;
}
imageUrl(target.path).then(
(url) => {
if (isLive()) img.src = url;
},
() => {
if (isLive()) img.classList.add(styles.blocked!);
},
);
images.load(img, target.path);
});
root.querySelectorAll<HTMLElement>("pre.code > code").forEach((code) => {
const lang = [...code.parentElement!.classList].find((c) => c !== "code" && c !== "literal-block") ?? null;
void highlightInto(code, code.textContent ?? "", lang);
});
return () => images.dispose();
}
function RstPreview({ path }: { path: string }) {
@@ -84,11 +88,7 @@ function RstPreview({ path }: { path: string }) {
useLayoutEffect(() => {
const root = ref.current;
if (!root || html === null) return;
let live = true;
fill(root, html, path, () => live);
return () => {
live = false;
};
return fill(root, html, path);
}, [html, path]);
const scrollTo = (id: string) =>
+23
Переглянути файл
@@ -101,6 +101,29 @@ describe("resolveMonoFont", () => {
});
});
describe("a chosen family that isn't installed", () => {
afterEach(() => {
vi.resetModules();
});
it("puts the bundled face before the fallback, so Latin text doesn't take the fallback's proportional letters", async () => {
const fonts = await import("./fonts");
// Before the native catalog loads nothing is known to be missing.
expect(fonts.monoFontFamily("Fira Code", "PingFang SC", BASE)).toBe(`"Fira Code", "PingFang SC", ${BASE}`);
fonts.noteInstalledFonts(["PingFang SC", "Menlo"]);
expect(fonts.monoFontFamily("Fira Code", "PingFang SC", BASE)).toBe(
`"Fira Code", "JetBrains Mono", "JetBrains Mono Variable", "PingFang SC", ${BASE}`,
);
// Installed, bundled and generic families keep the fallback right after them; so does no fallback.
expect(fonts.monoFontFamily("menlo", "PingFang SC", BASE)).toBe(`"menlo", "PingFang SC", ${BASE}`);
expect(fonts.monoFontFamily("Inter", "PingFang SC", BASE)).toBe(
`"Inter", "Inter Variable", "PingFang SC", ${BASE}`,
);
expect(fonts.monoFontFamily("monospace", "PingFang SC", BASE)).toBe(`"monospace", "PingFang SC", ${BASE}`);
expect(fonts.monoFontFamily("Fira Code", "", BASE)).toBe(`"Fira Code", ${BASE}`);
});
});
describe("discovered Nerd Font fallbacks (#3723)", () => {
afterEach(() => {
vi.resetModules();
Loaded 100 of 125 files, more files were not shown because too many files have changed in this diff. Show more