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

..
Автор SHA1 Повідомлення Дата
l0ng-ai 566631b6b8 fix(debugger): debug Python with a Windows venv interpreter given by its path
A Python run configuration whose command is a Windows path
(C:\…\.venv\Scripts\python.exe) was not recognised as an interpreter:
the path was only split at '/', so debugpy got a bare `python` from PATH
and the whole path as the module to run. When PATH has no usable
python, the launcher debugpy asks the IDE to start never connects
("Timed out waiting for launcher to connect"). Command names now split
at both separators, and a venv tool given by a backslash path debugs
with the python.exe next to it.

Fixes #3907
2026-11-17 20:28:21 +08:00
l0ng-ai 77996f17e7 fix(terminal): open file:// links in the editor (#3996)
Compiler output such as Kotlin's "file:///develop/app/src/A.kt:15:56 Unresolved
reference" was linked as a URL and handed to the system opener: in a remote
window it failed with "Not allowed to open url", and locally it opened the file
in another app. A file:// URL is now a file location with its line and column,
opened in the editor on the machine the terminal runs on, as the Run console
already does.

Refs #3447
2026-11-17 20:12:33 +08:00
l0ng-ai bacdd3e5c3 fix(run): detect Spring Boot apps that inherit the plugin or use a meta-annotation (#3995)
Project detection only treated a module as Spring Boot when its own build file
applied the plugin, so microservice modules that inherit spring-boot-maven-plugin
from the parent POM's <build><plugins> (or Gradle's subprojects block) were missing
from Run configurations and Services until their main class was run once. And only
the literal @SpringBootApplication marked an application class, not
@SpringCloudApplication or a project annotation carrying @SpringBootApplication, so
the gutter's Run created a plain Application configuration.

A module now applies Spring Boot through its own build or a build above it
(pluginManagement alone doesn't apply it). Application classes are recognised by
@SpringBootApplication, @SpringCloudApplication, or a project annotation declared
with either (resolved through imports and the modules' main source roots). The
gutter reuses the Spring Boot kind of the detected configuration with the same id.

Fixes #3916
2026-11-17 20:10:43 +08:00
tomgorтаtomgor cb7bddec14 fix(java): show Maven-generated sources in Problems (#3944)
jdtls/m2e only import source folders declared in the POM. Generators such as protobuf/gRPC, jOOQ, Avro, OpenAPI and QueryDSL add theirs with addCompileSourceRoot while the build runs, so Problems stayed red after a successful Maven compile. After a Maven project update, and after Build, Rebuild and Compile File, the IDE now scans target/generated-sources and generated-test-sources and puts those folders on the jdtls classpath through openidea.java.generatedSources (java-usages bundle 1.16.0), marked so a later scan can drop them; annotation-processor output, which jdtls compiles itself, is left out. A Maven build never starts jdtls by itself.

Co-authored-by: tomgor <[email protected]>
2026-11-17 20:06:44 +08:00
Mr0Bread 407561e59a feat(agents): jump to the chat input with ⌘L from anywhere that doesn't claim it (#3961)
Focus Agent Input (⌘L / Ctrl+L) only worked while focus was already in a task view. It now also focuses the message input of the task shown in an editor tab or the Agents tool window (the one used last when several are shown) from anywhere that doesn't own the key: in a code editor ⌘L stays Go to Line, the terminal keeps Ctrl+L, and popups and dialogs keep focus. Inside a task view it still wins over the editor.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-17 20:02:09 +08:00
LU XIANGRUIтаwildcatDownstairs e34e925b8f feat(lsp): follow doc.rust-lang.org and docs.rs links inside the documentation popup (#3960)
rust-analyzer renders intra-doc links as rustdoc URLs (doc.rust-lang.org for the standard library, docs.rs for other crates, the project's own included). Such a link now resolves by crate, module path, name and member (#method.x, #variant.X) through workspace/symbol and opens as the next history step when exactly one declaration fits (re-exports don't count); otherwise it opens in the browser. Web link rules live per language in src/editor/lsp/docLinks/. typescript-language-server's #L20%2C3 source links keep their column.

Refs #3874

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-17 20:00:01 +08:00
LU XIANGRUIтаwildcatDownstairs 04ab9e8999 feat(lsp): follow pkg.go.dev links and Go signature types inside the documentation popup (#3959)
A pkg.go.dev link in gopls documentation (#Name, #Type.Method, @version paths) opens its declaration's documentation as the next history step when workspace/symbol finds exactly one; otherwise it opens in the browser as before (⌘-click always does). Type names in a Go signature are clickable: a qualified pkg.Name resolves through the imports (aliases included) of the hovered file and the declaring file, an unqualified name in the declaring package, and builtins in $GOROOT/src/builtin/builtin.go. Only a unique exact match navigates.

Refs #3874

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-17 19:57:34 +08:00
LU XIANGRUIтаwildcatDownstairs 4a9927c256 feat(lsp): resizable documentation popup; hover documentation shares the F1 view (#3958)
The Quick Documentation popup can be resized from its right and bottom edges and corner; the size is remembered. Hover documentation now uses the same DocView as the F1 popup and the Documentation tool window, so links open inside the popup with back/forward history, F4 / Edit Source goes to the source, and it can be moved to the tool window. The popup's 600px / 420px caps, which floating-ui's inline sizes overrode, now apply to the content.

Refs #3874

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-17 19:46:15 +08:00
Muuтаmuutot 084be4fb51 fix(vcs): Git Log column dividers, resize direction and Hide Column (#3879)
Dragging a Git Log column divider moved the wrong way and could shift unrelated columns, and the resize target was hard to find. The divider now sits on a column's left edge, follows the pointer, and resizes only its two neighbours; the flexible Commit column gets a header divider that resizes the column to its left. Visible dividers are an opt-in View Options › Columns › Column Dividers (off by default; the hit strip and resize cursor always work), and the column header menu can hide any column except Commit.

Co-authored-by: muutot <[email protected]>
2026-11-17 19:43:43 +08:00
l0ng-ai 5c0ff2a918 fix(search): show tool window names in the UI language in Recent Files (#3990)
The tool-window column of Recent Files / Switcher listed every window by its
English title in a localized UI; the window's own header translates it. Recent
Files, the Run configuration's Activate tool window task and its menu now use the
same translated title (plugin windows keep theirs), and the English name still
finds a translated window when typed.

Fixes #3931
2026-11-17 19:41:31 +08:00
l0ng-ai c65acc902e chore(release): drop nightly builds (#3988)
Stable releases ship often enough that a separate nightly channel isn't needed.
Removes the nightly workflow and its prepare script, the nightly branches in the
release build's updater manifest, the nightly-only update endpoint, and the
once-a-day prompt throttle for nightly versions.
2026-11-17 19:41:20 +08:00
l0ng-ai ec0a681b72 fix(terminal): clear terminalFocus when the focused terminal pane is closed (#3989)
Removing the focused pane (the shell exiting with Close session when it ends on,
or closing the focused tab) fires no blur, so terminalFocus stayed set and the
terminal's keyWhen bindings kept winning: with the IntelliJ macOS keymap ⌘T opened
a new terminal tab from the editor instead of Update Project. Disposing a session
whose pane holds the caret now clears it; a pane that takes the caret sets it again.

Fixes #3923
2026-11-17 19:40:44 +08:00
67 змінених файлів з 2668 додано та 697 видалено

No files matched your search

-119
Переглянути файл
@@ -1,119 +0,0 @@
name: Nightly
# Twice a day, builds the newest main commit that passed CI as a prerelease tagged with its own
# version, so remote development finds the server of that version. The `nightly` release holds
# the manifest the nightly app updates from; its tag marks the commit last built, and a run with
# nothing newer stops there. Only the latest builds are kept.
on:
schedule:
- cron: "17 2,14 * * *"
workflow_dispatch:
inputs:
force:
description: "Build even if nothing is newer than the last nightly"
type: boolean
default: false
permissions:
contents: read
concurrency:
group: nightly
env:
GH_TOKEN: ${{ github.token }}
GH_REPO: ${{ github.repository }}
jobs:
prepare:
permissions:
actions: read
contents: write
if: github.repository == 'l0ng-ai/openidea'
runs-on: ubuntu-latest
outputs:
sha: ${{ steps.commit.outputs.sha }}
tag: ${{ steps.release.outputs.tag }}
release_id: ${{ steps.release.outputs.id }}
steps:
- id: commit
env:
FORCE: ${{ inputs.force }}
run: |
sha="$(gh run list --workflow ci.yml --branch main --event push --status success --limit 1 \
--json headSha --jq '.[0].headSha // ""')"
if [ -z "$sha" ]; then
echo "::notice::no main commit has passed CI"
exit 0
fi
# No `nightly` tag yet (the first run): compare fails and the build goes on.
status="$(gh api "repos/$GH_REPO/compare/nightly...$sha" --jq .status 2>/dev/null)" || status=ahead
if [ "$status" != ahead ] && [ "$FORCE" != true ]; then
echo "::notice::$sha is not newer than the last nightly"
exit 0
fi
echo "sha=$sha" >> "$GITHUB_OUTPUT"
- uses: actions/checkout@v5
if: steps.commit.outputs.sha != ''
with: { ref: "${{ steps.commit.outputs.sha }}" }
- uses: actions/setup-node@v5
if: steps.commit.outputs.sha != ''
with: { node-version: 22 }
- uses: dtolnay/rust-toolchain@stable
if: steps.commit.outputs.sha != ''
- id: release
if: steps.commit.outputs.sha != ''
env:
SHA: ${{ steps.commit.outputs.sha }}
run: |
version="$(node scripts/nightly-prepare.ts "$(date -u +%Y%m%d%H%M)")"
tag="v$version"
git config user.name "github-actions[bot]"
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
git commit -am "chore: $tag"
git tag "$tag"
git push origin "$tag"
id="$(gh api -X POST "repos/$GH_REPO/releases" -f tag_name="$tag" -f name="OpenIDEA Nightly $version" \
-F draft=true -F prerelease=true -f body="Built from $SHA." --jq .id)"
echo "tag=$tag" >> "$GITHUB_OUTPUT"
echo "id=$id" >> "$GITHUB_OUTPUT"
binaries:
permissions:
contents: write
needs: prepare
if: needs.prepare.outputs.tag != ''
uses: ./.github/workflows/release-build.yml
with:
tag: ${{ needs.prepare.outputs.tag }}
release_id: ${{ needs.prepare.outputs.release_id }}
secrets: inherit
publish:
permissions:
contents: write
needs: [prepare, binaries]
runs-on: ubuntu-latest
env:
TAG: ${{ needs.prepare.outputs.tag }}
SHA: ${{ needs.prepare.outputs.sha }}
KEEP: 14
steps:
- name: Publish the build
run: gh release edit "$TAG" --tag "$TAG" --draft=false
- name: Point the updater at it
run: |
gh release download "$TAG" -p latest.json -D "$RUNNER_TEMP"
gh release view nightly >/dev/null 2>&1 ||
gh release create nightly --prerelease --latest=false --target "$SHA" --title "OpenIDEA Nightly" \
--notes "The update manifest of the nightly builds, and the commit last built."
gh release upload nightly "$RUNNER_TEMP/latest.json" --clobber
gh api -X PATCH "repos/$GH_REPO/git/refs/tags/nightly" -f sha="$SHA" -F force=true --silent
# Failed builds' drafts go too, once they are this old.
- name: Delete old builds
run: |
gh release list --limit 200 --json tagName,createdAt --jq \
'[.[] | select(.tagName | contains("-nightly."))] | sort_by(.createdAt) | reverse | .[env.KEEP | tonumber:][].tagName' |
while read -r tag; do
gh release delete "$tag" --cleanup-tag --yes
done
+8 -9
Переглянути файл
@@ -1,7 +1,7 @@
name: Release build
# Builds a tag's desktop apps, remote servers and updater manifest into its draft release.
# Stable releases (release.yml) and nightly builds (nightly.yml) both run it.
# Builds a tag's desktop apps, remote servers and updater manifest into its draft release
# (run by release.yml).
on:
workflow_call:
inputs:
@@ -224,18 +224,17 @@ jobs:
return;
}
// Bundle suffix → updater platform keys, as tauri-action names them.
// Nightly versions don't fit MSI or RPM, so those builds offer NSIS on Windows.
const nightly = tag.includes("-nightly.");
const windows = (arch, msi, nsis) => nightly
? [[nsis, [`windows-${arch}`, `windows-${arch}-nsis`]]]
: [[msi, [`windows-${arch}`, `windows-${arch}-msi`]], [nsis, [`windows-${arch}-nsis`]]];
const windows = (arch, msi, nsis) => [
[msi, [`windows-${arch}`, `windows-${arch}-msi`]],
[nsis, [`windows-${arch}-nsis`]],
];
const kinds = [
[/_aarch64\.AppImage$/, ["linux-aarch64", "linux-aarch64-appimage"]],
[/_arm64\.deb$/, ["linux-aarch64-deb"]],
...(nightly ? [] : [[/\.aarch64\.rpm$/, ["linux-aarch64-rpm"]]]),
[/\.aarch64\.rpm$/, ["linux-aarch64-rpm"]],
[/_amd64\.AppImage$/, ["linux-x86_64", "linux-x86_64-appimage"]],
[/_amd64\.deb$/, ["linux-x86_64-deb"]],
...(nightly ? [] : [[/\.x86_64\.rpm$/, ["linux-x86_64-rpm"]]]),
[/\.x86_64\.rpm$/, ["linux-x86_64-rpm"]],
[/_aarch64\.app\.tar\.gz$/, ["darwin-aarch64", "darwin-aarch64-app"]],
[/_x64\.app\.tar\.gz$/, ["darwin-x86_64", "darwin-x86_64-app"]],
...windows("aarch64", /_arm64_en-US\.msi$/, /_arm64-setup\.exe$/),
+2 -3
Переглянути файл
@@ -1,7 +1,7 @@
name: Release
on:
push:
tags: ["v*", "!v*-nightly.*"]
tags: ["v*"]
workflow_dispatch:
inputs:
tag:
@@ -23,7 +23,6 @@ env:
jobs:
# Creates (or reuses) one draft release that every platform build uploads into.
create-release:
if: ${{ !contains(github.event.inputs.tag || github.ref_name, '-nightly.') }}
permissions:
contents: write
runs-on: ubuntu-latest
@@ -62,7 +61,7 @@ jobs:
core.setOutput("id", existing.id);
return;
}
// Nightly builds are prereleases: the notes span stable release to stable release.
// Prereleases are skipped: the notes span stable release to stable release.
const previous = releases.find((r) => !r.draft && !r.prerelease);
const { data: notes } = await github.rest.repos.generateReleaseNotes({
owner, repo, tag_name: tag, previous_tag_name: previous?.tag_name,
+15 -4
Переглянути файл
@@ -886,12 +886,19 @@ pub async fn build_run(
for (path, items) in compile::diagnostics(&result.messages) {
sink.emit(IdeEvent::Diagnostics { path: path.into(), source: compile::DIAGNOSTICS_SOURCE.into(), items });
}
Ok(result)
Ok::<_, IdeError>(result)
})
.await
.map_err(join_err);
host.end_request(request);
result?
let outcome = result??;
// Maven generated sources (protobuf, gRPC) stay invisible to jdtls until the
// folders the build wrote are attached. An up-to-date build skips Maven and
// still needs this: the classes can already be on disk.
if outcome.system == ide_build::compile::BuildSystem::Maven {
project.lsp.sync_maven_generated_sources(&project.root).await;
}
Ok(outcome)
}
/// Build › Compile File: compiles one Java source of a linked Maven module with
@@ -928,12 +935,16 @@ pub async fn build_compile_file(
for (path, items) in compile::diagnostics(&result.messages) {
sink.emit(IdeEvent::Diagnostics { path: path.into(), source: compile::DIAGNOSTICS_SOURCE.into(), items });
}
Ok(result)
Ok::<_, IdeError>(result)
})
.await
.map_err(join_err);
host.end_request(request);
result?
let outcome = result??;
if outcome.system == ide_build::compile::BuildSystem::Maven {
project.lsp.sync_maven_generated_sources(&project.root).await;
}
Ok(outcome)
}
#[cfg(test)]
+48 -3
Переглянути файл
@@ -17,10 +17,12 @@ use std::sync::Arc;
use std::time::{Duration, Instant};
pub(crate) const SERVER: &str = "jdtls";
const GENERATED_SOURCES: &str = "openidea.java.generatedSources";
pub(crate) mod configuration;
mod extract_interface;
mod formatter;
mod generated;
mod hierarchy;
pub(crate) mod jvm_inspect;
mod move_refactoring;
@@ -638,6 +640,7 @@ impl LspManager {
/// jdtls reports `ProjectStatus` when an import or project update ends (a POM
/// change, a Maven sync, other Maven profiles), but does not check open documents
/// again against the new classpath: their errors would stay until the next edit.
/// Generated Maven sources are attached first, so that recheck sees them.
pub(crate) fn java_projects_updated(self: &Arc<Self>, server: Arc<Server>, generation: u64) {
let uris: Vec<String> = self
.docs
@@ -650,11 +653,10 @@ impl LspManager {
})
.map(|d| crate::uri::path_to_uri_string(&d.path))
.collect();
if uris.is_empty() {
return;
}
let mgr = self.clone();
self.runtime.spawn(async move {
let Some(run) = server.running_gen(generation) else { return };
mgr.sync_generated_sources(&server, &run).await;
for uri in uris {
let params =
json!({ "command": "java.project.refreshDiagnostics", "arguments": [uri, "thisFile", false] });
@@ -668,6 +670,49 @@ impl LspManager {
});
}
/// Puts Maven plugin output that already exists on disk (`target/generated-sources/...`)
/// onto the jdtls classpath. Best-effort: only a jdtls that is already running is
/// touched, so a Maven build does not start the language server by itself.
pub async fn sync_maven_generated_sources(&self, root: &Path) {
let servers: Vec<_> = self
.servers
.lock()
.iter()
.filter(|server| server.name == SERVER && server.running().is_some())
.filter(|server| server.root == root || root.starts_with(&server.root) || server.root.starts_with(root))
.cloned()
.collect();
for server in servers {
let Some(run) = server.running() else { continue };
self.sync_generated_sources(&server, &run).await;
}
}
async fn sync_generated_sources(&self, server: &Arc<Server>, run: &Running) {
if !run.caps.read().commands().iter().any(|command| command == GENERATED_SOURCES) {
return;
}
let root = server.root.clone();
let scan = tokio::task::spawn_blocking(move || generated::scan(&root))
.await
.unwrap_or(generated::GeneratedScan { maven: false, roots: Vec::new() });
if !scan.maven {
return;
}
let arguments: Vec<Value> = scan
.roots
.into_iter()
.map(|root| json!({ "path": root.path.to_string_lossy(), "test": root.test }))
.collect();
let params = json!({ "command": GENERATED_SOURCES, "arguments": arguments });
let request = run.peer.request::<_, Value>("workspace/executeCommand", params, None);
if let Ok(Err(e)) | Err(e) =
tokio::time::timeout(COMMAND_TIMEOUT, request).await.map_err(|_| ide_jsonrpc::RpcError::Timeout)
{
tracing::debug!("jdtls: {GENERATED_SOURCES}: {e}");
}
}
/// 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)> {
+421
Переглянути файл
@@ -0,0 +1,421 @@
//! Maven plugin output that jdtls never imports.
//!
//! `protobuf-maven-plugin` and the same kind of generator call
//! `MavenProject.addCompileSourceRoot` while the build runs. That list is not in the
//! POM, so m2e never adds the folders and the editor keeps reporting missing packages
//! after a successful Maven compile. Annotation-processor output (`annotations`,
//! `test-annotations`) is left out: jdtls compiles it itself, and adding it as a source
//! folder makes the processor emit the same file twice.
use std::collections::HashSet;
use std::path::{Path, PathBuf};
const MAX_DEPTH: usize = 16;
const MAX_JAVA_FILES: usize = 4_000;
const MAX_PARENTS: usize = 8;
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub(crate) struct GeneratedRoot {
pub path: PathBuf,
pub test: bool,
}
pub(crate) struct GeneratedScan {
pub maven: bool,
pub roots: Vec<GeneratedRoot>,
}
/// Generated Java source folders under `root` (a reactor or one module).
pub(crate) fn scan(root: &Path) -> GeneratedScan {
let mut modules = Vec::new();
collect_modules(root, 0, &mut modules);
let mut roots = Vec::new();
for module in &modules {
let build = build_dir(module);
collect_tree(&build.join("generated-sources"), false, &mut roots);
collect_tree(&build.join("generated-test-sources"), true, &mut roots);
}
roots.sort();
roots.dedup();
GeneratedScan { maven: !modules.is_empty(), roots }
}
fn collect_modules(dir: &Path, depth: usize, modules: &mut Vec<PathBuf>) {
if depth > MAX_DEPTH {
return;
}
let has_pom = dir.join("pom.xml").is_file();
if has_pom {
modules.push(dir.to_path_buf());
}
let build_name = has_pom.then(|| build_dir(dir)).and_then(|dir| dir.file_name().map(|name| name.to_os_string()));
let Ok(entries) = std::fs::read_dir(dir) else { return };
for entry in entries.flatten() {
let Ok(kind) = entry.file_type() else { continue };
if !kind.is_dir() || kind.is_symlink() {
continue;
}
let name = entry.file_name();
let shown = name.to_string_lossy();
if shown.starts_with('.') || shown == "node_modules" || shown == "target" {
continue;
}
if build_name.as_ref().is_some_and(|build| build == &name) {
continue;
}
collect_modules(&entry.path(), depth + 1, modules);
}
}
fn collect_tree(tree: &Path, test: bool, roots: &mut Vec<GeneratedRoot>) {
let mut files = Vec::new();
walk_java(tree, 0, &mut files);
let mut found = HashSet::new();
for file in files {
let Some(package) = package_name(&read_head(&file)) else { continue };
let Some(root) = source_root(&file, &package) else { continue };
if root.starts_with(tree) && found.insert(root.clone()) {
roots.push(GeneratedRoot { path: root, test });
}
}
}
fn walk_java(dir: &Path, depth: usize, files: &mut Vec<PathBuf>) {
if depth > MAX_DEPTH || files.len() >= MAX_JAVA_FILES {
return;
}
let Ok(entries) = std::fs::read_dir(dir) else { return };
for entry in entries.flatten() {
if files.len() >= MAX_JAVA_FILES {
return;
}
let Ok(kind) = entry.file_type() else { continue };
if kind.is_symlink() {
continue;
}
let path = entry.path();
if kind.is_dir() {
// The compiler's own output. jdtls already consumes it as annotation processing.
if depth == 0 && matches!(entry.file_name().to_str(), Some("annotations" | "test-annotations")) {
continue;
}
walk_java(&path, depth + 1, files);
} else if kind.is_file() && path.extension().is_some_and(|ext| ext == "java") {
files.push(path);
}
}
}
fn read_head(path: &Path) -> String {
let Ok(bytes) = std::fs::read(path) else { return String::new() };
let head = &bytes[..bytes.len().min(4096)];
String::from_utf8_lossy(head).into_owned()
}
/// The `package` declaration, ignoring comments that precede it.
fn package_name(text: &str) -> Option<String> {
let mut rest = text;
loop {
let trimmed = rest.trim_start();
if let Some(after) = trimmed.strip_prefix("//") {
rest = after.split_once('\n').map(|(_, next)| next).unwrap_or("");
continue;
}
if let Some(after) = trimmed.strip_prefix("/*") {
rest = after.split_once("*/").map(|(_, next)| next).unwrap_or("");
continue;
}
let after = trimmed.strip_prefix("package")?;
if !after.starts_with(|c: char| c.is_whitespace()) {
return None;
}
let after = after.trim_start();
let end = after.find([';', '{', '\n', '\r', ' ', '\t', '/']).unwrap_or(after.len());
let name = after[..end].trim();
if name.is_empty() || !name.split('.').all(java_identifier) {
return None;
}
return Some(name.to_owned());
}
}
fn java_identifier(segment: &str) -> bool {
let mut chars = segment.chars();
matches!(chars.next(), Some(c) if c.is_ascii_alphabetic() || c == '_' || c == '$')
&& chars.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '$')
}
/// Directory that is the source root for `file` declaring `package`.
fn source_root(file: &Path, package: &str) -> Option<PathBuf> {
let mut dir = file.parent()?.to_path_buf();
for segment in package.split('.').rev() {
if dir.file_name().and_then(|n| n.to_str()) != Some(segment) {
return None;
}
dir.pop();
}
Some(dir)
}
fn build_dir(module: &Path) -> PathBuf {
let mut pom = module.join("pom.xml");
let mut seen = HashSet::new();
for _ in 0..MAX_PARENTS {
if !seen.insert(pom.clone()) {
break;
}
let Ok(text) = std::fs::read_to_string(&pom) else { break };
let text = strip_comments(&text);
if let Some(raw) = own_build_directory(&text) {
let rel = relative_build_dir(&raw).unwrap_or_else(|| "target".to_owned());
return module.join(rel);
}
let Some(parent) = parent_pom(pom.parent().unwrap_or(module), &text) else { break };
pom = parent;
}
module.join("target")
}
fn own_build_directory(pom: &str) -> Option<String> {
let build = section(pom, "build")?;
let own = plugins_removed(build);
section(&own, "directory").map(str::to_owned)
}
fn parent_pom(dir: &Path, pom: &str) -> Option<PathBuf> {
let parent = section(pom, "parent")?;
let rel = match relative_path(parent) {
Some(value) if value.trim().is_empty() => return None,
Some(value) => value.trim(),
None => "../pom.xml",
};
if rel.contains("${") || rel.starts_with(['/', '\\']) || rel.contains(':') {
return None;
}
let path = dir.join(rel);
path.is_file().then_some(path)
}
/// `<relativePath>` text, or `Some("")` for a self-closing `<relativePath/>` (no local parent).
fn relative_path(parent: &str) -> Option<&str> {
if let Some(value) = section(parent, "relativePath") {
return Some(value);
}
["<relativePath/>", "<relativePath />"].iter().any(|tag| parent.contains(tag)).then_some("")
}
fn relative_build_dir(raw: &str) -> Option<String> {
let mut value = raw.trim();
for prefix in ["${project.basedir}", "${basedir}"] {
if let Some(rest) = value.strip_prefix(prefix) {
value = rest.trim_start_matches(['/', '\\']);
}
}
if value.is_empty()
|| value.contains("${")
|| value.contains("..")
|| value.starts_with(['/', '\\'])
|| value.contains(':')
{
return None;
}
Some(value.replace('\\', "/"))
}
fn strip_comments(text: &str) -> String {
let mut out = String::with_capacity(text.len());
let mut rest = text;
while let Some(start) = rest.find("<!--") {
out.push_str(&rest[..start]);
rest = rest[start..].find("-->").map_or("", |end| &rest[start + end + 3..]);
}
out.push_str(rest);
out
}
fn section<'a>(text: &'a str, tag: &str) -> Option<&'a str> {
let open = format!("<{tag}>");
let start = text.find(&open)? + open.len();
let end = text[start..].find(&format!("</{tag}>"))?;
Some(&text[start..start + end])
}
fn plugins_removed(build: &str) -> String {
let mut text = build.to_owned();
for tag in ["plugins", "pluginManagement"] {
let (open, close) = (format!("<{tag}>"), format!("</{tag}>"));
let mut kept = String::with_capacity(text.len());
let mut rest = text.as_str();
while let Some(start) = rest.find(&open) {
kept.push_str(&rest[..start]);
rest = rest[start..].find(&close).map_or("", |end| &rest[start + end + close.len()..]);
}
kept.push_str(rest);
text = kept;
}
text
}
#[cfg(test)]
mod tests {
use super::*;
fn write(root: &Path, rel: &str, text: &str) {
let path = root.join(rel);
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(path, text).unwrap();
}
fn grpc(root: &Path) {
write(root, "pom.xml", "<project><artifactId>app</artifactId></project>");
write(
root,
"target/generated-sources/protobuf/java/com/example/hello/Hello.java",
"package com.example.hello;\npublic class Hello {}",
);
write(
root,
"target/generated-sources/protobuf/grpc-java/com/example/hello/HelloGrpc.java",
"/* generated */\npackage com.example.hello;\npublic class HelloGrpc {}",
);
write(
root,
"target/generated-sources/annotations/com/example/hello/HelloMapperImpl.java",
"package com.example.hello;\nclass HelloMapperImpl {}",
);
}
#[test]
fn protobuf_and_grpc_roots_are_kept_and_annotation_output_is_not() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
grpc(root);
let scan = scan(root);
assert!(scan.maven);
assert_eq!(
scan.roots,
vec![
GeneratedRoot { path: root.join("target/generated-sources/protobuf/grpc-java"), test: false },
GeneratedRoot { path: root.join("target/generated-sources/protobuf/java"), test: false },
]
);
}
#[test]
fn comments_before_the_package_and_test_sources() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
write(root, "pom.xml", "<project/>");
write(
root,
"target/generated-test-sources/protobuf/java/com/example/hello/HelloTest.java",
"// package ignored.nope;\n/* package also.nope; */\npackage com.example.hello;\nclass HelloTest {}",
);
write(
root,
"target/generated-test-sources/test-annotations/com/example/hello/Skip.java",
"package com.example.hello;\nclass Skip {}",
);
write(
root,
"target/generated-sources/protobuf/java/com/example/Wrong.java",
"package com.other;\nclass Wrong {}",
);
let scan = scan(root);
assert_eq!(
scan.roots,
vec![GeneratedRoot { path: root.join("target/generated-test-sources/protobuf/java"), test: true }]
);
}
#[test]
fn custom_build_directory_ignores_plugin_configuration_and_inherits_from_the_parent() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
write(
root,
"pom.xml",
r#"<project><build><directory>out</directory></build><modules><module>app</module></modules></project>"#,
);
write(
root,
"app/pom.xml",
r#"<project>
<parent><groupId>g</groupId><artifactId>p</artifactId><version>1</version></parent>
<build>
<plugins><plugin><configuration><directory>nope</directory></configuration></plugin></plugins>
<directory>${project.basedir}/custom</directory>
</build>
</project>"#,
);
write(
root,
"lib/pom.xml",
"<project><parent><groupId>g</groupId><artifactId>p</artifactId><version>1</version></parent></project>",
);
write(
root,
"app/custom/generated-sources/protobuf/grpc-java/com/example/hello/HelloGrpc.java",
"package com.example.hello;\nclass HelloGrpc {}",
);
write(
root,
"lib/out/generated-sources/protobuf/java/com/example/hello/Hello.java",
"package com.example.hello;\nclass Hello {}",
);
write(
root,
"lib/target/generated-sources/protobuf/java/com/example/hello/Stale.java",
"package com.example.hello;\nclass Stale {}",
);
let scan = scan(root);
let paths: Vec<_> = scan.roots.iter().map(|r| r.path.clone()).collect();
assert_eq!(
paths,
vec![
root.join("app/custom/generated-sources/protobuf/grpc-java"),
root.join("lib/out/generated-sources/protobuf/java"),
]
);
}
#[test]
fn an_empty_relative_path_does_not_inherit_the_parent_build_directory() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
write(root, "pom.xml", "<project><build><directory>out</directory></build></project>");
write(
root,
"app/pom.xml",
"<project><parent><groupId>g</groupId><artifactId>p</artifactId><version>1</version><relativePath/></parent></project>",
);
write(
root,
"app/target/generated-sources/protobuf/java/com/example/hello/Hello.java",
"package com.example.hello;\nclass Hello {}",
);
write(
root,
"app/out/generated-sources/protobuf/java/com/example/hello/Other.java",
"package com.example.hello;\nclass Other {}",
);
let scan = scan(root);
assert_eq!(
scan.roots,
vec![GeneratedRoot { path: root.join("app/target/generated-sources/protobuf/java"), test: false }]
);
}
#[test]
fn a_project_without_maven_is_not_a_scan() {
let tmp = tempfile::tempdir().unwrap();
write(
tmp.path(),
"target/generated-sources/protobuf/java/com/example/hello/Hello.java",
"package com.example.hello;\nclass Hello {}",
);
let scan = scan(tmp.path());
assert!(!scan.maven);
assert!(scan.roots.is_empty());
}
}
+51
Переглянути файл
@@ -2943,6 +2943,57 @@ async fn open_java_files_are_checked_again_after_a_project_update() {
eventually(|| refreshed() == expected).await;
}
#[tokio::test(flavor = "multi_thread")]
async fn a_project_update_attaches_maven_generated_sources_before_rechecking() {
let mut caps = incremental_caps();
caps["executeCommandProvider"]["commands"].as_array_mut().unwrap().push(json!("openidea.java.generatedSources"));
let h = harness_for("java", "java", &[("jdtls", caps)], &[]);
let (_, _) = h.open("App.java", "package com.example;\nclass App {}");
h.wait_status("jdtls", ServerStatus::Ready).await;
let write = |rel: &str, text: &str| {
let path = h.root.join(rel);
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(path, text).unwrap();
};
write("pom.xml", "<project><artifactId>app</artifactId></project>");
write(
"target/generated-sources/protobuf/java/com/example/hello/Hello.java",
"package com.example.hello;\npublic class Hello {}",
);
write(
"target/generated-sources/protobuf/grpc-java/com/example/hello/HelloGrpc.java",
"package com.example.hello;\npublic class HelloGrpc {}",
);
write(
"target/generated-sources/annotations/com/example/hello/HelloMapperImpl.java",
"package com.example.hello;\nclass HelloMapperImpl {}",
);
let state = h.launcher.state("jdtls");
state.peer().notify("language/status", json!({ "type": "ProjectStatus", "message": "OK" })).unwrap();
eventually(|| {
let requests = state.requested("workspace/executeCommand");
let generated = requests.iter().position(|p| p["command"] == "openidea.java.generatedSources");
let refresh = requests.iter().position(|p| p["command"] == "java.project.refreshDiagnostics");
matches!((generated, refresh), (Some(generated), Some(refresh)) if generated < refresh)
})
.await;
let requests = state.requested("workspace/executeCommand");
let generated = requests.iter().find(|p| p["command"] == "openidea.java.generatedSources").unwrap();
let paths: Vec<_> = generated["arguments"]
.as_array()
.unwrap()
.iter()
.map(|arg| (arg["path"].as_str().unwrap().to_owned(), arg["test"].as_bool().unwrap()))
.collect();
assert_eq!(
paths,
vec![
(h.root.join("target/generated-sources/protobuf/grpc-java").to_string_lossy().into_owned(), false),
(h.root.join("target/generated-sources/protobuf/java").to_string_lossy().into_owned(), false),
]
);
}
#[tokio::test(flavor = "multi_thread")]
async fn library_classes_in_jars_open_as_their_source_or_decompiled() {
use std::io::Write;
+176 -46
Переглянути файл
@@ -10,7 +10,7 @@ mod zig;
use crate::RunConfig;
use ide_core::project_roots::expand_members;
use serde_json::Value as Json;
use std::collections::{BTreeMap, HashSet};
use std::collections::{BTreeMap, HashMap, HashSet};
use std::fs;
use std::path::{Path, PathBuf};
@@ -591,14 +591,15 @@ fn spring_boot_apps(root: &Path, build: &Path, out: &mut Vec<RunConfig>) {
level = level.iter().flat_map(|d| subdirs(d)).filter(|d| !d.ends_with("src")).collect();
modules.extend(level.iter().cloned());
}
for module in modules {
if !applies_spring_boot(&module) {
let mut annotations = BootAnnotations::new(&modules);
for module in &modules {
if !applies_spring_boot(build, module) {
continue;
}
// A budget per module: a large common library must not starve later app modules.
let mut budget = SPRING_SCAN_FILES;
let module_rel = (module != root).then(|| relative(root, &module).to_string_lossy().replace('\\', "/"));
for class in spring_boot_classes(&module, &mut budget) {
let module_rel = (module != root).then(|| relative(root, module).to_string_lossy().replace('\\', "/"));
for class in spring_boot_classes(module, &mut budget, &mut annotations) {
let simple = class.rsplit(['.', '$']).next().unwrap_or(&class).to_owned();
let id = match &module_rel {
Some(m) => format!("application:{m}:{class}"),
@@ -612,28 +613,163 @@ fn spring_boot_apps(root: &Path, build: &Path, out: &mut Vec<RunConfig>) {
}
}
/// The module's own build applies the Spring Boot plugin, and it has main sources.
fn applies_spring_boot(module: &Path) -> bool {
/// The module has main sources, and its build applies the Spring Boot plugin: its own build
/// file, or a build above it in `build` that applies it to its modules (a parent POM's
/// `<build><plugins>`, Gradle's `subprojects` / `allprojects`).
fn applies_spring_boot(build: &Path, module: &Path) -> bool {
if !["java", "kotlin"].iter().any(|l| module.join("src/main").join(l).is_dir()) {
return false;
}
if let Some(pom) = read(&module.join("pom.xml")) {
return pom.contains("spring-boot-maven-plugin") && !pom.contains("<packaging>pom</packaging>");
if pom.contains("<packaging>pom</packaging>") {
return false;
}
if pom.contains("spring-boot-maven-plugin") {
return true;
}
} else if GRADLE_BUILDS.iter().filter_map(|n| read(&module.join(n))).any(|text| applies_boot_gradle_plugin(&text)) {
return true;
}
GRADLE_BUILDS.iter().filter_map(|n| read(&module.join(n))).any(|text| {
text.lines().any(|l| {
let l = l.split("//").next().unwrap_or_default();
// The plugin id (`id("org.springframework.boot")`), not a dependency (`org.springframework.boot:…`).
["org.springframework.boot\"", "org.springframework.boot'"].iter().any(|p| l.contains(p))
&& !l.contains("apply false")
module.ancestors().skip(1).take_while(|dir| dir.starts_with(build)).any(|dir| {
if let Some(pom) = read(&dir.join("pom.xml")) {
return without_plugin_management(&pom).contains("spring-boot-maven-plugin");
}
GRADLE_BUILDS.iter().filter_map(|n| read(&dir.join(n))).any(|text| {
(text.contains("subprojects") || text.contains("allprojects")) && applies_boot_gradle_plugin(&text)
})
})
}
/// Binary names of the `@SpringBootApplication` classes with a `main` under
/// A Gradle build applying the plugin (`id("org.springframework.boot")`, `apply plugin: '…'`),
/// not only depending on Spring Boot (`org.springframework.boot:…`).
fn applies_boot_gradle_plugin(text: &str) -> bool {
text.lines().any(|l| {
let l = l.split("//").next().unwrap_or_default();
["org.springframework.boot\"", "org.springframework.boot'"].iter().any(|p| l.contains(p))
&& !l.contains("apply false")
})
}
/// A POM without its `<pluginManagement>` sections, which configure plugins without applying them.
fn without_plugin_management(pom: &str) -> String {
let mut out = String::with_capacity(pom.len());
let mut rest = pom;
while let Some(at) = rest.find("<pluginManagement>") {
out.push_str(&rest[..at]);
let Some(end) = rest[at..].find("</pluginManagement>") else { return out };
rest = &rest[at + end + "</pluginManagement>".len()..];
}
out.push_str(rest);
out
}
/// Annotations that mark a Spring Boot application class: `@SpringBootApplication`,
/// `@SpringCloudApplication`, and the project's own annotations meta-annotated with either.
struct BootAnnotations {
/// `src/main/{java,kotlin}` of every module, where a project annotation is looked up.
roots: Vec<PathBuf>,
known: HashMap<String, bool>,
}
const BOOT_ANNOTATIONS: [&str; 2] = ["SpringBootApplication", "SpringCloudApplication"];
impl BootAnnotations {
fn new(modules: &[PathBuf]) -> Self {
let roots = modules
.iter()
.flat_map(|m| ["java", "kotlin"].map(|l| m.join("src/main").join(l)))
.filter(|d| d.is_dir())
.collect();
Self { roots, known: HashMap::new() }
}
/// Whether `@name`, as written in a file of `package` with `imports`, marks an application.
fn marks_application(&mut self, name: &str, package: Option<&str>, imports: &[&str]) -> bool {
let simple = name.rsplit('.').next().unwrap_or(name);
if BOOT_ANNOTATIONS.contains(&simple) {
return true;
}
let qualified = if name.contains('.') {
name.to_owned()
} else if let Some(import) = imports.iter().find(|i| i.rsplit('.').next() == Some(name)) {
(*import).to_owned()
} else {
match package {
Some(p) => format!("{p}.{name}"),
None => name.to_owned(),
}
};
if qualified.starts_with("org.springframework.") {
return false;
}
if let Some(&known) = self.known.get(&qualified) {
return known;
}
// Not yet known: no cycle through an annotation that names itself.
self.known.insert(qualified.clone(), false);
let found = self.declares_boot_annotation(&qualified);
self.known.insert(qualified, found);
found
}
/// The project declares annotation `qualified` and annotates it as an application.
fn declares_boot_annotation(&mut self, qualified: &str) -> bool {
let path = qualified.replace('.', "/");
let simple = qualified.rsplit('.').next().unwrap_or(qualified);
let source = self
.roots
.iter()
.flat_map(|r| ["java", "kt"].map(|x| r.join(format!("{path}.{x}"))))
.find_map(|f| read(&f));
let Some(src) = source else { return false };
let code = strip_line_comments(&src);
let Some(decl) = [format!("@interface {simple}"), format!("annotation class {simple}")]
.iter()
.find_map(|d| code.find(d.as_str()))
else {
return false;
};
let (package, imports) = package_and_imports(&code);
annotations_in(&code[..decl]).iter().any(|a| self.marks_application(a, package.as_deref(), &imports))
}
}
fn strip_line_comments(src: &str) -> String {
src.lines().map(|l| l.split("//").next().unwrap_or_default()).collect::<Vec<_>>().join("\n")
}
fn package_and_imports(code: &str) -> (Option<String>, Vec<&str>) {
let package = code
.lines()
.map(str::trim)
.find_map(|l| l.strip_prefix("package "))
.map(|p| p.trim_end_matches(';').trim().to_owned())
.filter(|p| !p.is_empty());
let imports = code
.lines()
.filter_map(|l| l.trim().strip_prefix("import "))
.map(|i| i.trim_end_matches(';').trim())
.filter(|i| !i.starts_with("static ") && !i.ends_with('*'))
.collect();
(package, imports)
}
/// Names of the annotations in `code` (`@Foo`, `@a.b.Foo(…)`), in order; `@interface` excluded.
fn annotations_in(code: &str) -> Vec<&str> {
code.match_indices('@')
.filter_map(|(at, _)| {
let rest = &code[at + 1..];
let len = rest.find(|c: char| !(c.is_alphanumeric() || c == '_' || c == '.')).unwrap_or(rest.len());
let name = rest[..len].trim_end_matches('.');
(!name.is_empty() && name != "interface" && !name.starts_with("file:")).then_some(name)
})
.collect()
}
/// Binary names of the Spring Boot application classes with a `main` under
/// `src/main/{java,kotlin}`, from the shallowest packages that declare one (the
/// application class sits in the root package of the code it scans).
fn spring_boot_classes(module: &Path, budget: &mut usize) -> Vec<String> {
fn spring_boot_classes(module: &Path, budget: &mut usize, annotations: &mut BootAnnotations) -> Vec<String> {
let mut found = Vec::new();
let mut level: Vec<PathBuf> =
["java", "kotlin"].iter().map(|l| module.join("src/main").join(l)).filter(|d| d.is_dir()).collect();
@@ -661,7 +797,7 @@ fn spring_boot_classes(module: &Path, budget: &mut usize) -> Vec<String> {
if fs::metadata(&file).is_ok_and(|m| m.len() > 256 * 1024) {
continue;
}
if let Some(class) = read(&file).and_then(|src| spring_boot_class(&src, &file)) {
if let Some(class) = read(&file).and_then(|src| spring_boot_class(&src, &file, annotations)) {
found.push(class);
}
}
@@ -672,41 +808,35 @@ fn spring_boot_classes(module: &Path, budget: &mut usize) -> Vec<String> {
found
}
/// The class to launch for a source file declaring a `@SpringBootApplication` with a `main`.
pub(crate) fn spring_boot_class(src: &str, file: &Path) -> Option<String> {
let code: Vec<&str> = src.lines().map(|l| l.split("//").next().unwrap_or_default()).collect();
let code = code.join("\n");
let at = code.find("@SpringBootApplication")?;
let package = code
.lines()
.map(str::trim)
.find_map(|l| l.strip_prefix("package "))
.map(|p| p.trim_end_matches(';').trim().to_owned())
.filter(|p| !p.is_empty());
/// The class to launch for a source file declaring a Spring Boot application class with a `main`.
fn spring_boot_class(src: &str, file: &Path, annotations: &mut BootAnnotations) -> Option<String> {
let code = strip_line_comments(src);
let (package, imports) = package_and_imports(&code);
let qualify = |name: &str| match &package {
Some(p) => format!("{p}.{name}"),
None => name.to_owned(),
};
if file.extension().is_some_and(|x| x == "kt") {
// A top-level `fun main` compiles into the file facade (`AppKt`, or `@file:JvmName`).
if code.lines().any(|l| l.starts_with("fun main(")) {
let jvm_name = code
.lines()
.find_map(|l| l.trim().strip_prefix("@file:JvmName(")?.split('"').nth(1).map(str::to_owned));
let facade = jvm_name.unwrap_or_else(|| {
let stem = file.file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default();
let mut chars = stem.chars();
let upper: String = chars.next().map(|c| c.to_uppercase().chain(chars).collect()).unwrap_or_default();
format!("{upper}Kt")
});
return Some(qualify(&facade));
}
if !code.contains("fun main(") {
return None;
}
} else if !code.contains("void main(") {
let kotlin = file.extension().is_some_and(|x| x == "kt");
if !(if kotlin { code.contains("fun main(") } else { code.contains("void main(") }) {
return None;
}
// The annotation right before a class declaration: `@SpringBootApplication` or one carrying it.
let at = annotations_in(&code)
.into_iter()
.find(|a| !a.starts_with("file:") && annotations.marks_application(a, package.as_deref(), &imports))?;
let at = code.find(&format!("@{at}"))?;
if kotlin && code.lines().any(|l| l.starts_with("fun main(")) {
// A top-level `fun main` compiles into the file facade (`AppKt`, or `@file:JvmName`).
let jvm_name =
code.lines().find_map(|l| l.trim().strip_prefix("@file:JvmName(")?.split('"').nth(1).map(str::to_owned));
let facade = jvm_name.unwrap_or_else(|| {
let stem = file.file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default();
let mut chars = stem.chars();
let upper: String = chars.next().map(|c| c.to_uppercase().chain(chars).collect()).unwrap_or_default();
format!("{upper}Kt")
});
return Some(qualify(&facade));
}
let name: String = code[at..]
.split_whitespace()
.skip_while(|t| *t != "class")
+51
Переглянути файл
@@ -399,6 +399,57 @@ fn spring_boot_applications_need_the_plugin_and_a_main() {
assert!(!c.iter().any(|c| c.kind == "spring-boot"), "{:?}", ids(&c));
}
#[test]
fn spring_boot_modules_inherit_the_plugin_from_their_parent_build() {
let main = |pkg: &str, ann: &str, cls: &str| {
format!("package {pkg};\n{ann}\npublic class {cls} {{\n public static void main(String[] a) {{}}\n}}\n")
};
let parent = "<project><packaging>pom</packaging><modules><module>order</module><module>user</module>\
<module>gateway</module></modules><build><plugins><plugin>\
<artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>";
let order = main("shop.order", "@SpringBootApplication", "OrderApp");
let user = main("shop.user", "@SpringCloudApplication", "UserApp");
// A project annotation carrying @SpringBootApplication, declared in another module.
let gateway = main("shop.gateway", "@ShopApplication", "GatewayApp")
.replace("package shop.gateway;\n", "package shop.gateway;\nimport shop.common.ShopApplication;\n");
let annotation = "package shop.common;\n\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\n\
@Target(ElementType.TYPE)\n@SpringBootApplication\npublic @interface ShopApplication {}\n";
let files = [
("pom.xml", parent.to_owned()),
("order/pom.xml", "<project><artifactId>order</artifactId></project>".to_owned()),
("order/src/main/java/shop/order/OrderApp.java", order),
("user/pom.xml", "<project><artifactId>user</artifactId></project>".to_owned()),
("user/src/main/java/shop/user/UserApp.java", user),
("gateway/pom.xml", "<project><artifactId>gateway</artifactId></project>".to_owned()),
("gateway/src/main/java/shop/gateway/GatewayApp.java", gateway),
("common/src/main/java/shop/common/ShopApplication.java", annotation.to_owned()),
];
let files: Vec<(&str, &str)> = files.iter().map(|(p, t)| (*p, t.as_str())).collect();
let c = detect(project(&files).path());
for id in [
"application:order:shop.order.OrderApp",
"application:user:shop.user.UserApp",
"application:gateway:shop.gateway.GatewayApp",
] {
assert_eq!(find(&c, id).kind, "spring-boot", "{id}");
}
// A parent that only manages the plugin doesn't apply it; Gradle applies it from `subprojects`.
let dir = project(&[
("pom.xml", PARENT_POM),
("app/pom.xml", "<project/>"),
("app/src/main/java/demo/App.java", &main("demo", "@SpringBootApplication", "App")),
]);
assert!(!detect(dir.path()).iter().any(|c| c.kind == "spring-boot"));
let dir = project(&[
("settings.gradle", "include 'app'\n"),
("build.gradle", "subprojects {\n apply plugin: 'org.springframework.boot'\n}\n"),
("app/build.gradle", "dependencies {}\n"),
("app/src/main/java/demo/App.java", &main("demo", "@SpringBootApplication", "App")),
]);
assert_eq!(find(&detect(dir.path()), "application:app:demo.App").kind, "spring-boot");
}
#[test]
fn go_projects() {
let dir = project(&[
+1 -1
Переглянути файл
@@ -1614,7 +1614,7 @@ pub fn usages_bundle(data_dir: &Path) -> Option<PathBuf> {
install_bundle(
data_dir,
"java-usages",
"1.15.0",
"1.16.0",
include_bytes!("../../../java/java-usages/openidea-java-usages.jar"),
)
}
+1 -1
Переглянути файл
@@ -80,7 +80,7 @@ On your own messages you can **Edit** (the messages after it are replaced; files
**Focus Agent Input** defaults to `⌘L` on macOS and `Ctrl+L` on Windows / Linux in every built-in keymap. When focus is inside your writable task conversation, in either an editor tab or the tool window, it returns focus to the message input without changing your draft, caret position or selection—even when pressed repeatedly. It does not send a message or jump through message history.
The shortcut does not apply to archived tasks, subagent conversations or the New Task page, and does not take focus from open popups or dialogs. Outside the task conversation, the keys keep their usual editor or terminal behavior. To change or remove the binding, open **Settings › Keymap › Agents › Focus Agent Input**.
With focus anywhere else, the same shortcut jumps to the message input of the task shown in an editor tab or the tool window (the one you used last, if several are shown), unless a panel claims the shortcut there: in a code editor `⌘L` / `Ctrl+L` keeps its editor meaning (for example Go to Line), and in a terminal on Windows / Linux `Ctrl+L` still reaches the shell. It does not apply to archived tasks, subagent conversations or the New Task page, and does not take focus from open popups or dialogs. To change or remove the binding, open **Settings › Keymap › Agents › Focus Agent Input**.
**Cycle Agent Effort** defaults to `Option+T` on macOS and `Alt+T` on Windows / Linux in every built-in keymap. With focus inside New Task or your own writable task conversation, in an editor tab or the tool window, it cycles the current model's provider-advertised effort levels in order, wrapping from the last to the first. It preserves your message, selection, caret and focus, and sends nothing. Like the effort control, it changes the provider configuration; it does not promise to change a turn already running.
+1 -1
Переглянути файл
@@ -80,7 +80,7 @@ Codex 有自己的项目信任设置。如果它禁用了当前项目的 `.codex
所有内置按键映射中,**聚焦 Agent 输入框** 的默认快捷键都是 macOS 上的 `⌘L`、Windows / Linux 上的 `Ctrl+L`。焦点位于你自己的可输入任务对话中时,无论对话显示在编辑器标签页还是工具窗口中,它都会将焦点移回消息输入框,保留草稿、光标位置和选区;重复按下也不会改变这些内容。它不会发送消息,也不会跳转消息历史。
此快捷键不适用于已归档任务、子 agent 对话或“新建任务”页面,也不会从打开的弹出窗口或对话框中抢走焦点。在任务对话之外,按键保留原有的编辑器或终端行为。要修改或移除绑定,请打开 **设置 › 按键映射 › 智能体 › 聚焦 Agent 输入框**。
焦点位于其他位置时,同一快捷键会跳转到编辑器标签页或工具窗口中显示的任务的消息输入框(显示多个时,选择你最近使用的那个),除非该位置有面板占用此快捷键:在代码编辑器中,`⌘L` / `Ctrl+L` 保留编辑器含义(例如“转到行”);在 Windows / Linux 的终端中,`Ctrl+L` 仍会发送给 shell。此快捷键不适用于已归档任务、子 agent 对话或“新建任务”页面,也不会从打开的弹出窗口或对话框中抢走焦点。要修改或移除绑定,请打开 **设置 › 按键映射 › 智能体 › 聚焦 Agent 输入框**。
所有内置按键映射中,**循环切换 Agent 思考强度** 的默认快捷键都是 macOS 上的 `Option+T`、Windows / Linux 上的 `Alt+T`。焦点位于“新建任务”或你自己的可输入任务对话中时,无论显示在编辑器标签页还是工具窗口中,它都会按提供商声明的顺序切换当前模型支持的思考强度,从最后一级循环回第一级。它会保留消息、选区、光标和焦点,不发送任何内容。与思考强度控件一样,它修改的是提供商配置,不保证改变已经运行中的轮次。
+17
Переглянути файл
@@ -327,6 +327,23 @@ test("editor Go to Line stays available while a docked agent conversation is vis
await expect(messageBox(page)).toHaveText(draft);
});
for (const placement of ["editor", "toolWindow"] as const) {
test(`${placement}: the shortcut jumps to the shown task's input from the project tree`, async ({
workbench: page,
}) => {
await openFromTree(page, "README.md");
await seedTasks(page, placement);
const box = messageBox(page);
await box.fill(draft);
await page.getByRole("treeitem", { name: "README.md", exact: true }).click();
await expect(box).not.toBeFocused();
await page.keyboard.press("Meta+L");
await expect(box).toBeFocused();
await expect(box).toHaveText(draft);
await expect(page.getByRole("dialog", { name: "Go to Line:Column", exact: true })).toHaveCount(0);
});
}
for (const preset of ["intellij-windows", "vscode-windows", "eclipse-windows"]) {
test(`${preset} uses Ctrl+L to focus the task message`, async ({ workbench: page }) => {
await seedTasks(page, "editor");
+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.15.0
Bundle-Version: 1.16.0
Bundle-RequiredExecutionEnvironment: JavaSE-21
Require-Bundle: org.eclipse.jdt.ls.core,org.eclipse.jdt.core,
org.eclipse.jdt.core.manipulation,org.eclipse.core.runtime,
+4 -1
Переглянути файл
@@ -88,7 +88,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.15.0.jar`, and added alongside existing initialization bundles.
`java-usages-1.16.0.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.
@@ -136,6 +136,9 @@ Version 1.12.0 caches usages answers until the Java model or an unsaved edit cha
Version 1.15.0 adds `openidea.java.implementationLocations`, which resolves the method an
implementation in a dependency declares (the standard request starts at its class file); its
reproducible SHA-256 is `c29e5455c02c245523b2e7a5861e00ae670cefc66cda33ec19fdce280f94c40c`.
Version 1.16.0 adds `openidea.java.generatedSources`, which puts Maven plugin output such as
protobuf and gRPC stubs on the project classpath; its reproducible SHA-256 is
`a5feda1cae11bdea1044fb311404840b048601af037f65685973721f1eefff8b`.
```sh
export PATH=/path/to/jdk25/bin:$PATH
Бінарний файл не відображається.
+3
Переглянути файл
@@ -20,6 +20,9 @@
<delegateCommandHandler class="ai.openidea.archives.RefreshArchivesCommand">
<command id="openidea.java.refreshArchives"/>
</delegateCommandHandler>
<delegateCommandHandler class="ai.openidea.sources.GeneratedSourcesCommand">
<command id="openidea.java.generatedSources"/>
</delegateCommandHandler>
<delegateCommandHandler class="ai.openidea.implementations.ImplementationTargetsCommand">
<command id="openidea.java.implementationLocations"/>
</delegateCommandHandler>
+162
Переглянути файл
@@ -0,0 +1,162 @@
package ai.openidea.sources;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.core.runtime.Path;
import org.eclipse.jdt.core.IClasspathAttribute;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.ls.core.internal.IDelegateCommandHandler;
import org.eclipse.jdt.ls.core.internal.JavaLanguageServerPlugin;
/**
* Adds Maven plugin output (protobuf, gRPC, jOOQ, …) as source folders.
*
* <p>The argument is {@code [{path, test}, …]}: absolute directories the build already
* generated. Folders this command added are marked {@code openidea.generatedSource} and
* dropped again when they are no longer in that list, so a later reload does not keep a
* source folder Maven has cleaned. Entries m2e or build-helper already created are left
* as they are.
*/
public final class GeneratedSourcesCommand implements IDelegateCommandHandler {
static final String MARKER = "openidea.generatedSource";
private static final String MAVEN = "org.eclipse.m2e.core.maven2Nature";
private record Spec(IPath path, boolean test) {}
@Override
public Object executeCommand(String command, List<Object> arguments, IProgressMonitor monitor) throws Exception {
List<Spec> specs = specs(arguments);
IJavaProject[] projects = JavaCore.create(ResourcesPlugin.getWorkspace().getRoot()).getJavaProjects();
int changed = 0;
for (IJavaProject project : projects) {
if (monitor.isCanceled()) throw new OperationCanceledException();
if (!isMaven(project)) continue;
if (sync(project, owned(projects, project, specs), monitor)) changed++;
}
return changed;
}
private static List<Spec> specs(List<Object> arguments) {
List<Spec> specs = new ArrayList<>();
if (arguments == null) return specs;
for (Object argument : arguments) {
if (!(argument instanceof Map<?, ?> map)) continue;
if (!(map.get("path") instanceof String path) || path.isBlank()) continue;
specs.add(new Spec(Path.fromOSString(path), Boolean.TRUE.equals(map.get("test"))));
}
return specs;
}
/** Specs whose longest Maven project prefix is `project`. A reactor parent also prefixes its modules. */
private static List<Spec> owned(IJavaProject[] projects, IJavaProject project, List<Spec> specs) {
IPath location = project.getProject().getLocation();
List<Spec> owned = new ArrayList<>();
if (location == null) return owned;
for (Spec spec : specs) {
if (!location.isPrefixOf(spec.path)) continue;
IJavaProject best = project;
int segments = location.segmentCount();
for (IJavaProject other : projects) {
if (other == project || !isMaven(other)) continue;
IPath otherLocation = other.getProject().getLocation();
if (otherLocation != null && otherLocation.isPrefixOf(spec.path)
&& otherLocation.segmentCount() > segments) {
best = other;
segments = otherLocation.segmentCount();
}
}
if (best == project) owned.add(spec);
}
return owned;
}
private static boolean sync(IJavaProject project, List<Spec> specs, IProgressMonitor monitor) {
try {
IPath location = project.getProject().getLocation();
if (location == null) return false;
Map<IPath, Boolean> wanted = new LinkedHashMap<>();
for (Spec spec : specs) {
if (monitor.isCanceled()) throw new OperationCanceledException();
IPath relative = spec.path.makeRelativeTo(location);
if (relative.isAbsolute() || relative.segmentCount() == 0) continue;
IFolder folder = project.getProject().getFolder(relative);
refresh(folder, monitor);
if (folder.exists()) wanted.put(project.getPath().append(relative), spec.test);
}
IClasspathEntry[] raw = project.getRawClasspath();
List<IClasspathEntry> next = new ArrayList<>();
boolean changed = false;
for (IClasspathEntry entry : raw) {
if (!marked(entry)) {
next.add(entry);
continue;
}
if (wanted.containsKey(entry.getPath())) next.add(entry);
else changed = true;
}
for (Map.Entry<IPath, Boolean> entry : wanted.entrySet()) {
if (hasSource(next, entry.getKey())) continue;
IClasspathAttribute[] attributes = entry.getValue()
? new IClasspathAttribute[] {
JavaCore.newClasspathAttribute(IClasspathAttribute.TEST, "true"),
JavaCore.newClasspathAttribute(MARKER, "true")
}
: new IClasspathAttribute[] { JavaCore.newClasspathAttribute(MARKER, "true") };
next.add(JavaCore.newSourceEntry(entry.getKey(), new IPath[0], new IPath[0], null, attributes));
changed = true;
}
if (!changed) return false;
project.setRawClasspath(next.toArray(IClasspathEntry[]::new), monitor);
return true;
} catch (CoreException | OperationCanceledException e) {
JavaLanguageServerPlugin.logException("Adding generated Maven sources to " + project.getElementName(), e);
return false;
}
}
private static void refresh(IFolder folder, IProgressMonitor monitor) throws CoreException {
IResource resource = folder;
while (resource.getType() != IResource.ROOT && !resource.exists()) {
IResource parent = resource.getParent();
if (parent == null) return;
resource = parent;
}
resource.refreshLocal(IResource.DEPTH_INFINITE, monitor);
}
private static boolean marked(IClasspathEntry entry) {
if (entry.getEntryKind() != IClasspathEntry.CPE_SOURCE) return false;
for (IClasspathAttribute attribute : entry.getExtraAttributes()) {
if (MARKER.equals(attribute.getName()) && "true".equals(attribute.getValue())) return true;
}
return false;
}
private static boolean hasSource(List<IClasspathEntry> entries, IPath path) {
for (IClasspathEntry entry : entries) {
if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE && entry.getPath().equals(path)) return true;
}
return false;
}
private static boolean isMaven(IJavaProject project) {
IProject resource = project.getProject();
try {
return resource.isAccessible() && resource.hasNature(MAVEN);
} catch (CoreException e) {
return false;
}
}
}
+1 -2
Переглянути файл
@@ -32,8 +32,7 @@
"perf": "node perf/run.ts",
"perf:rust": "node perf/rust.ts",
"eval": "node evals/run.ts",
"release:prepare": "node scripts/release-prepare.ts",
"nightly:prepare": "node scripts/nightly-prepare.ts"
"release:prepare": "node scripts/release-prepare.ts"
},
"simple-git-hooks": {
"pre-commit": "pnpm lint-staged"
-34
Переглянути файл
@@ -1,34 +0,0 @@
// @vitest-environment node
import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
import { NIGHTLY_ENDPOINT, nightlyVersion, setNightlyIdentity } from "./nightly-prepare.ts";
describe("nightlyVersion", () => {
it("is one patch above the current version, numbered by its stamp", () => {
expect(nightlyVersion("0.1.39", "202611081417")).toBe("0.1.40-nightly.202611081417");
});
it.each([undefined, "", "2026", "012611081417", "20261108141a"])("rejects the stamp %s", (stamp) => {
expect(() => nightlyVersion("0.1.39", stamp)).toThrow("stamp");
});
it("rejects a current version that is not a release version", () => {
expect(() => nightlyVersion("0.1.40-nightly.202611081417", "202611081417")).toThrow("expected a version");
});
});
describe("setNightlyIdentity", () => {
const conf = JSON.parse(setNightlyIdentity(readFileSync("src-tauri/tauri.conf.json", "utf8")));
it("is an app of its own that updates from the nightly manifest", () => {
expect(conf.productName).toBe("OpenIDEA Nightly");
expect(conf.identifier).toBe("ai.l0ng.openidea.nightly");
expect(conf.plugins.updater.endpoints).toEqual([NIGHTLY_ENDPOINT]);
});
it("leaves out the bundles that reject prerelease versions", () => {
expect(conf.bundle.targets).not.toContain("msi");
expect(conf.bundle.targets).not.toContain("rpm");
expect(conf.bundle.createUpdaterArtifacts).toBe(true);
});
});
-54
Переглянути файл
@@ -1,54 +0,0 @@
/**
* Prepares a nightly build's commit: `node scripts/nightly-prepare.ts 202611081417` sets the
* version one patch above the current one, with that stamp as its prerelease number, in the
* files `release:prepare` covers, and gives tauri.conf.json the nightly app's identity, so it
* installs next to the stable app and updates from its own manifest. Prints the version.
*/
import { spawnSync } from "node:child_process";
import { readFileSync } from "node:fs";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { cargoVersion, edit, parseVersion, setCargoVersion, setJsonVersion } from "./release-prepare.ts";
export const NIGHTLY_ENDPOINT = "https://github.com/l0ng-ai/openidea/releases/download/nightly/latest.json";
/** `0.1.40-nightly.202611081417` from `0.1.39`: always above the last stable version and the last nightly. */
export function nightlyVersion(current: string, stamp: string | undefined): string {
if (!stamp || !/^[1-9]\d{11}$/.test(stamp)) throw new Error(`expected a YYYYMMDDHHMM stamp, got ${stamp}`);
const [major, minor, patch] = parseVersion(current).split(".").map(Number);
return `${major}.${minor}.${patch! + 1}-nightly.${stamp}`;
}
/** MSI and RPM reject prerelease versions, so a nightly build leaves them out of its bundles. */
export function setNightlyIdentity(json: string): string {
const conf = JSON.parse(json);
conf.productName = "OpenIDEA Nightly";
conf.identifier = "ai.l0ng.openidea.nightly";
conf.bundle.targets = ["app", "dmg", "appimage", "deb", "nsis"];
conf.plugins.updater.endpoints = [NIGHTLY_ENDPOINT];
return `${JSON.stringify(conf, null, 2)}\n`;
}
function main() {
const root = fileURLToPath(new URL("..", import.meta.url));
const version = nightlyVersion(cargoVersion(readFileSync(join(root, "Cargo.toml"), "utf8")), process.argv[2]);
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) => setNightlyIdentity(setJsonVersion(text, version)));
const cargo = spawnSync("cargo", ["update", "--workspace"], {
cwd: root,
stdio: ["ignore", 2, 2],
});
if (cargo.status !== 0) throw new Error("cargo update --workspace failed");
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);
}
}
+58 -61
Переглянути файл
@@ -12,66 +12,63 @@ const run = new Function("github", "context", "core", `return (async () => {${sc
afterEach(() => vi.unstubAllEnvs());
it.each(["v0.1.42", "v0.1.43-nightly.20261112"])(
"publishes signed portable updates for both Windows architectures alongside the installers (%s)",
async (tag) => {
vi.stubEnv("TAG", tag);
vi.stubEnv("RELEASE_ID", "42");
const version = tag.slice(1);
const nightly = tag.includes("-nightly.");
const bundles = [
"OpenIDEA_aarch64.AppImage",
"OpenIDEA_arm64.deb",
"OpenIDEA.aarch64.rpm",
"OpenIDEA_amd64.AppImage",
"OpenIDEA_amd64.deb",
"OpenIDEA.x86_64.rpm",
"OpenIDEA_aarch64.app.tar.gz",
"OpenIDEA_x64.app.tar.gz",
"OpenIDEA_arm64_en-US.msi",
"OpenIDEA_arm64-setup.exe",
"OpenIDEA_x64_en-US.msi",
"OpenIDEA_x64-setup.exe",
`OpenIDEA_${version}_windows_x64_portable.zip`,
`OpenIDEA_${version}_windows_arm64_portable.zip`,
].filter((name) => !nightly || (!name.endsWith(".msi") && !name.endsWith(".rpm")));
const assets = bundles.flatMap((name, id) => [
{ name, id: id * 2 },
{ name: `${name}.sig`, id: id * 2 + 1 },
]);
const upload = vi.fn();
const failed = vi.fn();
await run(
{
paginate: async () => assets,
rest: {
repos: {
listReleaseAssets: vi.fn(),
getRelease: async () => ({ data: { body: "Release notes" } }),
getReleaseAsset: async ({ asset_id }: { asset_id: number }) => ({
data: Buffer.from(`signature-${asset_id}\n`),
}),
uploadReleaseAsset: upload,
},
it("publishes signed portable updates for both Windows architectures alongside the installers", async () => {
const tag = "v0.1.42";
vi.stubEnv("TAG", tag);
vi.stubEnv("RELEASE_ID", "42");
const version = tag.slice(1);
const bundles = [
"OpenIDEA_aarch64.AppImage",
"OpenIDEA_arm64.deb",
"OpenIDEA.aarch64.rpm",
"OpenIDEA_amd64.AppImage",
"OpenIDEA_amd64.deb",
"OpenIDEA.x86_64.rpm",
"OpenIDEA_aarch64.app.tar.gz",
"OpenIDEA_x64.app.tar.gz",
"OpenIDEA_arm64_en-US.msi",
"OpenIDEA_arm64-setup.exe",
"OpenIDEA_x64_en-US.msi",
"OpenIDEA_x64-setup.exe",
`OpenIDEA_${version}_windows_x64_portable.zip`,
`OpenIDEA_${version}_windows_arm64_portable.zip`,
];
const assets = bundles.flatMap((name, id) => [
{ name, id: id * 2 },
{ name: `${name}.sig`, id: id * 2 + 1 },
]);
const upload = vi.fn();
const failed = vi.fn();
await run(
{
paginate: async () => assets,
rest: {
repos: {
listReleaseAssets: vi.fn(),
getRelease: async () => ({ data: { body: "Release notes" } }),
getReleaseAsset: async ({ asset_id }: { asset_id: number }) => ({
data: Buffer.from(`signature-${asset_id}\n`),
}),
uploadReleaseAsset: upload,
},
},
{ repo: { owner: "l0ng-ai", repo: "openidea" } },
{ notice: vi.fn(), info: vi.fn(), setFailed: failed },
);
expect(failed).not.toHaveBeenCalled();
const manifest = JSON.parse(upload.mock.calls[0]![0].data);
for (const [arch, filename] of [
["x86_64", "x64"],
["aarch64", "arm64"],
]) {
const name = `OpenIDEA_${version}_windows_${filename}_portable.zip`;
const sig = assets.find((a) => a.name === `${name}.sig`)!;
expect(manifest.platforms[`windows-${arch}-portable`]).toEqual({
signature: `signature-${sig.id}`,
url: `https://github.com/l0ng-ai/openidea/releases/download/${tag}/${name}`,
});
expect(manifest.platforms[`windows-${arch}`].url).toContain(nightly ? "-setup.exe" : "_en-US.msi");
expect(manifest.platforms[`windows-${arch}-nsis`].url).toContain("-setup.exe");
}
},
);
},
{ repo: { owner: "l0ng-ai", repo: "openidea" } },
{ notice: vi.fn(), info: vi.fn(), setFailed: failed },
);
expect(failed).not.toHaveBeenCalled();
const manifest = JSON.parse(upload.mock.calls[0]![0].data);
for (const [arch, filename] of [
["x86_64", "x64"],
["aarch64", "arm64"],
]) {
const name = `OpenIDEA_${version}_windows_${filename}_portable.zip`;
const sig = assets.find((a) => a.name === `${name}.sig`)!;
expect(manifest.platforms[`windows-${arch}-portable`]).toEqual({
signature: `signature-${sig.id}`,
url: `https://github.com/l0ng-ai/openidea/releases/download/${tag}/${name}`,
});
expect(manifest.platforms[`windows-${arch}`].url).toContain("_en-US.msi");
expect(manifest.platforms[`windows-${arch}-nsis`].url).toContain("-setup.exe");
}
});
+8 -25
Переглянути файл
@@ -480,10 +480,9 @@ fn config_endpoints<R: tauri::Runtime>(app: &AppHandle<R>) -> Vec<String> {
/// 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. Nightly builds
/// aren't mirrored: the mirror's manifest would move them to the stable version.
fn source_endpoints(official: Vec<String>, source: UpdateSource, nightly: bool) -> Vec<String> {
if official.is_empty() || nightly {
/// 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() {
return official;
}
let mirror = vec![CNB_ENDPOINT.to_string()];
@@ -493,10 +492,6 @@ fn source_endpoints(official: Vec<String>, source: UpdateSource, nightly: bool)
}
}
fn is_nightly(version: &str) -> bool {
version.contains("-nightly.")
}
fn updater(app: &AppHandle, source: UpdateSource) -> IdeResult<Option<tauri_plugin_updater::Updater>> {
use tauri_plugin_updater::UpdaterExt;
if !updates_configured(app) {
@@ -504,7 +499,7 @@ fn updater(app: &AppHandle, source: UpdateSource) -> IdeResult<Option<tauri_plug
}
let endpoints = match update_endpoint_env() {
Some(url) => vec![url],
None => source_endpoints(config_endpoints(app), source, is_nightly(&app.package_info().version.to_string())),
None => source_endpoints(config_endpoints(app), source),
};
let endpoints = endpoints
.iter()
@@ -703,7 +698,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, is_nightly(&app.package_info().version.to_string())),
None => source_endpoints(config_endpoints(&app), source),
};
let client = ide_http::client::shared()?;
for endpoint in endpoints {
@@ -830,22 +825,10 @@ 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, false),
[github.clone(), CNB_ENDPOINT.into()]
);
assert_eq!(source_endpoints(vec![github.clone()], UpdateSource::Cnb, false), [CNB_ENDPOINT.into(), github]);
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]);
// A build without an update endpoint stays without one.
assert!(source_endpoints(Vec::new(), UpdateSource::Cnb, false).is_empty());
}
#[test]
fn nightly_builds_update_from_their_own_manifest_whatever_the_source() {
let nightly = "https://github.com/l0ng-ai/openidea/releases/download/nightly/latest.json".to_string();
assert_eq!(source_endpoints(vec![nightly.clone()], UpdateSource::Cnb, true), vec![nightly.clone()]);
assert_eq!(source_endpoints(vec![nightly.clone()], UpdateSource::Github, true), [nightly]);
assert!(is_nightly("0.1.40-nightly.202611081417"));
assert!(!is_nightly("0.1.40"));
assert!(source_endpoints(Vec::new(), UpdateSource::Cnb).is_empty());
}
#[test]
+118
Переглянути файл
@@ -0,0 +1,118 @@
/**
* The documentation view with its history toolbar, as IDEA's one documentation
* component: the F1 popup, the hover and the Documentation tool window show it.
*/
import { useEffect, useRef, type KeyboardEvent } from "react";
import { createRoot } from "react-dom/client";
import clsx from "clsx";
import { useStore } from "zustand";
import { IconButton, selectableText } from "@/ui";
import { shortcutLabel } from "@/platform/keymap";
import {
docLinkHandler,
docStep,
editDocSource,
linkSignatureTypes,
moveDocPopupToWindow,
type DocHistory,
type DocHost,
type HoverDoc,
} from "./docs";
import { renderMarkup } from "./markdown";
import styles from "./Popups.module.css";
export function DomContent({ build, className }: { build: () => HTMLElement; className?: string }) {
const ref = useRef<HTMLDivElement>(null);
useEffect(() => {
const el = ref.current;
if (!el) return;
const node = build();
el.replaceChildren(node);
return () => el.replaceChildren();
// Built once per popup.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return <div ref={ref} className={className} />;
}
export function DocView({ host, history, themeClasses }: { host: DocHost; history: DocHistory; themeClasses: string }) {
const entry = history.entries[history.index];
const onKeyDown = (e: KeyboardEvent) => {
if (e.metaKey || e.ctrlKey || e.altKey || e.shiftKey) return;
if (e.key === "ArrowLeft" || e.key === "ArrowRight") {
e.preventDefault();
docStep(host, e.key === "ArrowLeft" ? -1 : 1);
} else if (e.key === "F4" && entry?.source) {
e.preventDefault();
void editDocSource(host);
}
};
return (
<div
tabIndex={-1}
data-lsp-doc={typeof host === "object" ? "hover" : host}
className={clsx(themeClasses, host === "window" ? styles.docWindowFrame : styles.docFrame)}
onKeyDown={onKeyDown}
>
{entry && (
<DomContent
key={`${history.index}:${history.entries.length}`}
className={clsx(styles.docBody, selectableText)}
build={() => {
const dom = renderMarkup(entry.markup, entry.language, docLinkHandler(host));
linkSignatureTypes(dom, host, entry);
return dom;
}}
/>
)}
<div className={styles.docToolbar}>
<IconButton
icon="arrow-left"
size="small"
title="Back"
shortcut="←"
disabled={history.index === 0}
onClick={() => docStep(host, -1)}
/>
<IconButton
icon="arrow-right"
size="small"
title="Forward"
shortcut="→"
disabled={history.index >= history.entries.length - 1}
onClick={() => docStep(host, 1)}
/>
<span className={styles.spacer} />
{entry?.source && (
<IconButton
icon="edit"
size="small"
title="Edit Source"
shortcut="F4"
onClick={() => void editDocSource(host)}
/>
)}
{host !== "window" && (
<IconButton
icon="open-in-tool-window"
size="small"
title="Show in Documentation Tool Window"
shortcut={(host === "popup" && shortcutLabel("code.quickDocumentation")) || undefined}
onClick={() => moveDocPopupToWindow(host)}
/>
)}
</div>
</div>
);
}
function HoverDocView({ doc }: { doc: HoverDoc }) {
return <DocView host={doc} history={useStore(doc)} themeClasses="" />;
}
/** Mounts a hover's documentation into its CodeMirror tooltip; returns its unmount. */
export function mountHoverDoc(el: HTMLElement, doc: HoverDoc): () => void {
const root = createRoot(el);
root.render(<HoverDocView doc={doc} />);
return () => queueMicrotask(() => root.unmount());
}
+29 -3
Переглянути файл
@@ -232,10 +232,11 @@
color: var(--fg-faint);
}
/* Fits its content up to a cap; resized (`data-resized`), it keeps that size and the body scrolls. */
.docPopup {
max-width: min(600px, 90vw);
max-height: 420px;
overflow: auto;
display: flex;
flex-direction: column;
overflow: hidden;
}
.docScope {
display: contents;
@@ -243,6 +244,24 @@
.docFrame {
outline: none;
}
.docPopup .docFrame {
flex: 1 1 auto;
min-height: 0;
display: flex;
flex-direction: column;
}
.docPopup:not([data-resized]) .docFrame {
max-width: min(600px, 90vw);
max-height: 420px;
}
.docPopup .docBody {
flex: 1 1 auto;
min-height: 0;
overflow: auto;
}
.docPopup .docToolbar {
flex: none;
}
.docWindowFrame {
height: 100%;
display: flex;
@@ -271,6 +290,13 @@
.docBody {
padding: 10px 14px;
}
/* Go signatures: a type name opens its documentation (`linkSignatureTypes` in docs.ts). */
.docBody :global(.cm-lsp-markdown > pre:first-of-type > code.language-go .tok-typeName) {
cursor: pointer;
}
.docBody :global(.cm-lsp-markdown > pre:first-of-type > code.language-go .tok-typeName:hover) {
text-decoration: underline;
}
.defPopup {
width: min(640px, 90vw);
max-height: 460px;
+77 -1
Переглянути файл
@@ -16,9 +16,14 @@ vi.mock("@/workbench/contributions", async (orig) => {
const { LspPopups, DocumentationWindow } = await import("./Popups");
const { closePopup, openPopup, useLspPopup } = await import("./popupStore");
const { useDocWindow, pushHistory, stepHistory, hoverCandidates } = await import("./docs");
const { useDocWindow, hoverDoc, pushHistory, stepHistory, hoverCandidates } = await import("./docs");
const { mountHoverDoc } = await import("./DocView");
const { hoverSource } = await import("./hover");
import popupStyles from "./Popups.module.css";
import { registerImportsOnPasteActions } from "./importsOnPaste";
import { EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { CONTRIBUTED_HOVER, type ContributedHover } from "@/editor/api";
const loc = (path: string, line: number): Location => ({
path,
@@ -252,6 +257,77 @@ describe("documentation", () => {
});
});
describe("hover documentation", () => {
const text = (value: string) => ({ markup: { kind: "plaintext" as const, value }, language: null });
const frame = (el: Element) => el.querySelector<HTMLElement>('[data-lsp-doc="hover"]')!;
afterEach(() => document.body.replaceChildren());
it("shows the hovered documentation in the same view as F1's", async () => {
const docHover: ContributedHover = (state, pos) => {
const w = state.wordAt(pos);
return w ? { from: w.from, to: w.to, markdown: "hovered docs" } : null;
};
const view = new EditorView({
state: EditorState.create({
doc: "query.FlightPlan",
extensions: [EditorState.languageData.of(() => [{ [CONTRIBUTED_HOVER]: docHover }])],
}),
parent: document.body.appendChild(document.createElement("div")),
});
const tooltip = await hoverSource(view, 2);
let created!: { dom: HTMLElement; destroy: () => void };
await act(async () => {
created = tooltip!.create() as typeof created;
document.body.appendChild(created.dom);
});
expect(frame(created.dom).textContent).toContain("hovered docs");
expect(screen.getByRole("button", { name: "Back" })).toBeTruthy();
created.destroy();
view.destroy();
});
it("walks its history with ← / →; Edit Source closes the hover", async () => {
const close = vi.fn();
const source = vi.fn(async () => loc("/p/b.ts", 3));
const doc = hoverDoc(text("first"), close);
doc.setState({ entries: [text("first"), { ...text("second"), source }], index: 1 });
const el = document.body.appendChild(document.createElement("div"));
await act(async () => void mountHoverDoc(el, doc));
expect(frame(el).textContent).toContain("second");
fireEvent.keyDown(frame(el), { key: "ArrowLeft" });
expect(frame(el).textContent).toContain("first");
fireEvent.click(screen.getByRole("button", { name: "Forward" }));
expect(frame(el).textContent).toContain("second");
fireEvent.keyDown(frame(el), { key: "F4" });
await vi.waitFor(() =>
expect(openFile).toHaveBeenCalledWith("/p/b.ts", { selection: { line: 3, col: 4 }, focus: true }),
);
expect(close).toHaveBeenCalled();
});
it("keeps each hover's history apart (an editor shown again brings its hover back)", async () => {
const [a, b] = [hoverDoc(text("in a.go"), vi.fn()), hoverDoc(text("in b.rs"), vi.fn())];
const [elA, elB] = [0, 1].map(() => document.body.appendChild(document.createElement("div")));
await act(async () => {
mountHoverDoc(elA!, a);
mountHoverDoc(elB!, b);
});
await act(async () => b.setState({ entries: [text("in b.rs"), text("followed in b.rs")], index: 1 }));
expect(frame(elA!).textContent).toContain("in a.go");
expect(frame(elB!).textContent).toContain("followed in b.rs");
});
it("moves its history to the Documentation tool window", async () => {
const close = vi.fn();
const el = document.body.appendChild(document.createElement("div"));
await act(async () => void mountHoverDoc(el, hoverDoc(text("hovered"), close)));
fireEvent.click(screen.getByRole("button", { name: "Show in Documentation Tool Window" }));
expect(close).toHaveBeenCalled();
expect(show).toHaveBeenCalledWith("documentation", true);
expect(useDocWindow.getState().entries[0]?.markup.value).toBe("hovered");
});
});
describe("quick definition popup", () => {
it("switches between several definitions with ← / → and edits the source with F4", () => {
openPopup({
+9 -95
Переглянути файл
@@ -28,17 +28,9 @@ import {
type ListPreview,
type LspPopup,
} from "./popupStore";
import { shortcutLabel } from "@/platform/keymap";
import {
docLinkHandler,
docStep,
editDocSource,
moveDocPopupToWindow,
useDocWindow,
type DocHistory,
type DocHost,
} from "./docs";
import { renderCode, renderMarkup } from "./markdown";
import { DOC_MIN_HEIGHT, DOC_MIN_WIDTH, loadDocSize, saveDocSize, useDocWindow } from "./docs";
import { DocView, DomContent } from "./DocView";
import { renderCode } from "./markdown";
import { describeSummary } from "./workspaceEdit";
import { useUsagesStatus } from "./navigation";
import styles from "./Popups.module.css";
@@ -352,90 +344,6 @@ function RenamePopup({ popup }: { popup: Extract<LspPopup, { kind: "rename" }> }
);
}
function DomContent({ build, className }: { build: () => HTMLElement; className?: string }) {
const ref = useRef<HTMLDivElement>(null);
useEffect(() => {
const el = ref.current;
if (!el) return;
const node = build();
el.replaceChildren(node);
return () => el.replaceChildren();
// Built once per popup.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return <div ref={ref} className={className} />;
}
/** Documentation with its history toolbar; shared by the popup and the Documentation tool window. */
function DocView({ host, history, themeClasses }: { host: DocHost; history: DocHistory; themeClasses: string }) {
const entry = history.entries[history.index];
const onKeyDown = (e: KeyboardEvent) => {
if (e.metaKey || e.ctrlKey || e.altKey || e.shiftKey) return;
if (e.key === "ArrowLeft" || e.key === "ArrowRight") {
e.preventDefault();
docStep(host, e.key === "ArrowLeft" ? -1 : 1);
} else if (e.key === "F4" && entry?.source) {
e.preventDefault();
void editDocSource(host);
}
};
const ref = useRef<HTMLDivElement>(null);
return (
<div
ref={ref}
tabIndex={-1}
data-lsp-doc={host}
className={clsx(themeClasses, host === "popup" ? styles.docFrame : styles.docWindowFrame)}
onKeyDown={onKeyDown}
>
{entry && (
<DomContent
key={`${history.index}:${history.entries.length}`}
className={clsx(styles.docBody, selectableText)}
build={() => renderMarkup(entry.markup, entry.language, docLinkHandler(host))}
/>
)}
<div className={styles.docToolbar}>
<IconButton
icon="arrow-left"
size="small"
title="Back"
shortcut="←"
disabled={history.index === 0}
onClick={() => docStep(host, -1)}
/>
<IconButton
icon="arrow-right"
size="small"
title="Forward"
shortcut="→"
disabled={history.index >= history.entries.length - 1}
onClick={() => docStep(host, 1)}
/>
<span className={styles.spacer} />
{entry?.source && (
<IconButton
icon="edit"
size="small"
title="Edit Source"
shortcut="F4"
onClick={() => void editDocSource(host)}
/>
)}
{host === "popup" && (
<IconButton
icon="open-in-tool-window"
size="small"
title="Show in Documentation Tool Window"
shortcut={shortcutLabel("code.quickDocumentation") || undefined}
onClick={() => moveDocPopupToWindow()}
/>
)}
</div>
</div>
);
}
function DocPopup({ popup }: { popup: Extract<LspPopup, { kind: "doc" }> }) {
const focusSeq = useLspPopup((s) => s.focusSeq);
const scope = useRef<HTMLDivElement>(null);
@@ -444,6 +352,7 @@ function DocPopup({ popup }: { popup: Extract<LspPopup, { kind: "doc" }> }) {
if (focusSeq !== opened.current)
scope.current?.querySelector<HTMLElement>("[data-lsp-doc]")?.focus({ preventScroll: true });
}, [focusSeq]);
const [initialSize] = useState(loadDocSize);
return (
<Popup
open
@@ -453,6 +362,11 @@ function DocPopup({ popup }: { popup: Extract<LspPopup, { kind: "doc" }> }) {
className={styles.docPopup}
// As in IDEA the popup leaves the keyboard to the editor until F1 focuses it.
autoFocus={false}
resizable="both"
minWidth={DOC_MIN_WIDTH}
minHeight={DOC_MIN_HEIGHT}
initialSize={initialSize}
onResized={saveDocSize}
>
<div ref={scope} data-testid="doc-popup" className={styles.docScope}>
<DocView host="popup" history={popup} themeClasses={popup.themeClasses} />
+171
Переглянути файл
@@ -0,0 +1,171 @@
import { describe, expect, it, vi } from "vitest";
import type { WorkspaceSymbol } from "@/bindings";
const GOROOT = "/go/src";
const files: Record<string, string> = {
"/p/cmd/main.go": 'package main\n\nimport (\n\t"fmt"\n\tst "example.com/p/store"\n\t_ "embed"\n)\n',
"/p/store/store.go": 'package store\n\nimport "time"\n\ntype Note struct{ At time.Time }\n',
"/p/conv/conv.go": 'package conv\n\nimport (\n\tam "example.com/p/a/model"\n\tbm "example.com/p/b/model"\n)\n',
[`${GOROOT}/builtin/builtin.go`]:
"package builtin\n\n// bool is…\ntype bool bool\n\nconst (\n\ttrue = 0 == 0\n)\n\ntype error interface {\n\tError() string\n}\n\nfunc len(v Type) int\n",
};
const sym = (name: string, container: string, path: string, line = 3): WorkspaceSymbol => ({
name,
kind: "struct",
container,
location: { path, range: { start: { line, col: 5 }, end: { line, col: 9 } } },
});
// What gopls answers per query (names come back qualified as the query is).
const index: Record<string, WorkspaceSymbol[]> = {
"fmt.Println": [
sym("fmt.Println", "fmt", "/go/src/fmt/print.go", 305),
sym("fmt.Fprintln", "fmt", "/go/src/fmt/print.go"),
],
"log.Logger.Printf": [sym("log.Logger.Printf", "log", "/go/src/log/log.go", 265)],
"store.Note": [sym("store.Note", "example.com/p/store", "/p/store/store.go", 4)],
"time.Time": [sym("time.Time", "time", "/go/src/time/time.go", 135)],
Note: [
sym("Note", "example.com/p/store", "/p/store/store.go", 4),
sym("Note", "example.com/p/other", "/p/other/x.go"),
],
"model.Item": [
sym("model.Item", "example.com/p/a/model", "/p/a/model/model.go"),
sym("model.Item", "example.com/p/b/model", "/p/b/model/model.go"),
],
"yaml.Node": [sym("yaml.Node", "gopkg.in/yaml.v3", "/mod/yaml/yaml.go")],
};
const queries: string[] = [];
vi.mock("@tauri-apps/api/core", () => ({ Channel: class {} }));
vi.mock("@/platform/ipc", async (orig) => ({
...(await orig<typeof import("@/platform/ipc")>()),
commands: {
lspWorkspaceSymbols: async (_id: number, q: string) => {
queries.push(q);
return { status: "ok", data: index[q] ?? [] };
},
sdkProjectLibraries: async () => ({
status: "ok",
data: [{ name: "Go SDK", kind: "go", roots: [{ name: "src", path: GOROOT }] }],
}),
},
}));
vi.mock("../files", () => ({ readFileLines: async (p: string) => files[p]?.split("\n") ?? null }));
const { goImports, goPackageName, pkgGoDevLink, resolveGoRef, findInPackage, signatureRef } = await import("./go");
describe("pkg.go.dev links", () => {
it.each([
["https://pkg.go.dev/fmt#Println", { importPath: "fmt", name: "Println" }],
["https://pkg.go.dev/log#Logger.Printf", { importPath: "log", name: "Logger.Printf" }],
[
"https://pkg.go.dev/golang.org/x/[email protected]/language#Tag",
{ importPath: "golang.org/x/text/language", name: "Tag" },
],
["https://pkg.go.dev/fmt", null],
["https://pkg.go.dev/fmt#hdr-Printing", null],
["https://go.dev/doc#Println", null],
["file:///go/src/fmt/print.go#L1", null],
])("%s", (href, want) => expect(pkgGoDevLink(href)).toEqual(want));
it.each([
["fmt", "Println", { path: "/go/src/fmt/print.go", line: 305, col: 5 }],
["log", "Logger.Printf", { path: "/go/src/log/log.go", line: 265, col: 5 }],
["example.com/nowhere", "Missing", null],
])("finds %s#%s only by its exact name in that package", async (path, name, want) => {
expect(await findInPackage(path, name)).toEqual(want);
});
});
describe("Go names", () => {
it("reads import names, aliases and package names", () => {
expect([...goImports(files["/p/cmd/main.go"]!)]).toEqual([
["fmt", "fmt"],
["st", "example.com/p/store"],
]);
expect([...goImports('package x\nimport y "a/b"\nimport "c/d.v2"')]).toEqual([
["y", "a/b"],
["d", "c/d.v2"],
]);
expect(["gopkg.in/yaml.v3", "github.com/google/go-cmp/cmp", "x/go-redis/v9", "a/b-go"].map(goPackageName)).toEqual([
"yaml",
"cmp",
"redis",
"b",
]);
});
it("splits a qualified name in a signature", () => {
const text = "func (s *st.Store) Get(id int) (st.Note, error)";
expect(signatureRef(text, 12, 17)).toEqual({ qualifier: "st", name: "Store" });
expect(signatureRef(text, 26, 29)).toEqual({ qualifier: null, name: "int" });
});
const current = "/p/cmd/main.go";
it.each<
[string, { qualifier: string | null; name: string }, { declaring: string | null; current: string | null }, unknown]
>([
[
"alias of the file asked in",
{ qualifier: "st", name: "Note" },
{ declaring: null, current },
"/p/store/store.go",
],
[
"import of the declaring file",
{ qualifier: "time", name: "Time" },
{ declaring: "/p/store/store.go", current },
"/go/src/time/time.go",
],
[
"package no file imports, unique",
{ qualifier: "yaml", name: "Node" },
{ declaring: null, current },
"/mod/yaml/yaml.go",
],
["same package name twice: ambiguous", { qualifier: "model", name: "Item" }, { declaring: null, current }, null],
[
"unqualified, in the declaring package",
{ qualifier: null, name: "Note" },
{ declaring: "/p/store/store.go", current },
"/p/store/store.go",
],
[
"unqualified, not in that package",
{ qualifier: null, name: "Note" },
{ declaring: "/p/cmd/main.go", current },
null,
],
["not found", { qualifier: "st", name: "Missing" }, { declaring: null, current }, null],
[
"builtin type",
{ qualifier: null, name: "error" },
{ declaring: null, current },
`${GOROOT}/builtin/builtin.go:9:5`,
],
[
"builtin constant",
{ qualifier: null, name: "true" },
{ declaring: null, current },
`${GOROOT}/builtin/builtin.go:6:1`,
],
[
"builtin function",
{ qualifier: null, name: "len" },
{ declaring: null, current },
`${GOROOT}/builtin/builtin.go:13:5`,
],
])("%s", async (_, ref, ctx, want) => {
const t = await resolveGoRef(ref, ctx);
const got = t && (t.path.includes("builtin") ? `${t.path}:${t.line}:${t.col}` : t.path);
expect(got).toEqual(want);
});
it("an alias meaning different packages in the two files is ambiguous", async () => {
files["/p/other.go"] = 'package other\n\nimport st "example.com/p/stuff"\n';
expect(await resolveGoRef({ qualifier: "st", name: "Note" }, { declaring: "/p/other.go", current })).toBeNull();
expect(queries).not.toContain("stuff.Note");
});
});
+148
Переглянути файл
@@ -0,0 +1,148 @@
/**
* Go documentation links (gopls), resolved to declarations through `workspace/symbol`
* so their documentation opens in place, as in GoLand:
* - `https://pkg.go.dev/<import path>#<Name>` (or `#<Type>.<Method>`) links;
* - type names in a signature: `pkg.Name` by the import the qualifier names, `Name` in the
* documented symbol's package, predeclared names (`string`, `error`…) in `builtin`.
* Only a unique exact match counts: nothing is guessed from the name alone.
*/
import { Channel } from "@tauri-apps/api/core";
import { call, commands, nextRequestId, type LibraryGroup, type WorkspaceSymbol } from "@/platform/ipc";
import { symbols, unique, type DocTarget } from "./symbols";
import { dirname } from "@/platform/project";
import { readFileLines } from "../files";
/** A name in a Go signature: `pkg.Name` (`qualifier` = `pkg`) or `Name`. */
export interface GoRef {
qualifier: string | null;
name: string;
}
/** Where a signature comes from: its declaration's file and the file the documentation was asked in. */
export interface GoRefContext {
declaring: string | null;
current: string | null;
}
const IDENT = "[A-Za-z_][A-Za-z0-9_]*";
/** `https://pkg.go.dev/<import path>[@version]#<Name>` or `#<Type>.<Method>`; null for other links. */
export function pkgGoDevLink(href: string): { importPath: string; name: string } | null {
// Malformed URLs and escapes are no links.
try {
const url = new URL(href);
if (url.hostname !== "pkg.go.dev") return null;
const name = decodeURIComponent(url.hash.slice(1));
const importPath = decodeURIComponent(url.pathname.slice(1)).replace(/@[^/]*/, "");
if (!importPath || !new RegExp(`^${IDENT}(\\.${IDENT})?$`).test(name)) return null;
return { importPath, name };
} catch {
return null;
}
}
/**
* The package name an import path usually declares (`…/yaml.v3` → `yaml`, `…/go-cmp/v2` → `cmp`).
* ponytail: a heuristic, used only to query and for packages no file at hand imports.
*/
export function goPackageName(importPath: string): string {
const parts = importPath.split("/");
let last = parts[parts.length - 1] ?? "";
if (/^v\d+$/.test(last) && parts.length > 1) last = parts[parts.length - 2]!;
return last
.replace(/\.v\d+$/, "")
.replace(/^go-|-go$/, "")
.replace(/\W/g, "_");
}
/** Import name → import path of a Go file's imports (aliases, groups; `_` and `.` imports skipped). */
export function goImports(text: string): Map<string, string> {
const imports = new Map<string, string>();
const spec = new RegExp(`^\\s*(?:(${IDENT}|\\.)\\s+)?"([^"]+)"`);
for (const m of text.matchAll(/^import\s*(?:\(([\s\S]*?)\)|(.*))$/gm)) {
for (const line of (m[1] ?? m[2] ?? "").split("\n")) {
const s = spec.exec(line);
if (!s || s[1] === "_" || s[1] === ".") continue;
imports.set(s[1] ?? goPackageName(s[2]!), s[2]!);
}
}
return imports;
}
/** The name at [from, to) of a signature's text, with the `pkg.` written before it. */
export function signatureRef(text: string, from: number, to: number): GoRef {
const q = new RegExp(`(?:^|[^\\w.])(${IDENT})\\.$`).exec(text.slice(0, from));
return { qualifier: q?.[1] ?? null, name: text.slice(from, to) };
}
const PREDECLARED = new Set(
(
"any bool byte comparable complex64 complex128 error float32 float64 int int8 int16 int32 int64 rune " +
"string uint uint8 uint16 uint32 uint64 uintptr true false iota nil append cap clear close complex " +
"copy delete imag len make max min new panic print println real recover"
).split(" "),
);
/** Whether `s` is `name` itself, as found by a query qualified with `qualifier` or not. */
function named(s: WorkspaceSymbol, qualifier: string, name: string): boolean {
return s.name === name || s.name === `${qualifier}.${name}`;
}
/** `name` (`Name` or `Type.Method`) declared in the package at `importPath`. */
export async function findInPackage(importPath: string, name: string): Promise<DocTarget | null> {
const pkg = goPackageName(importPath);
const inPackage = (list: WorkspaceSymbol[]) => list.filter((s) => s.container === importPath && named(s, pkg, name));
const hits = inPackage(await symbols(`${pkg}.${name}`));
return unique(hits.length ? hits : inPackage(await symbols(name)));
}
async function importsOf(path: string | null): Promise<Map<string, string>> {
const lines = path ? await readFileLines(path).catch(() => null) : null;
return goImports(lines?.join("\n") ?? "");
}
async function goSourceRoot(): Promise<string | null> {
const groups = await call(commands.sdkProjectLibraries(nextRequestId(), new Channel<LibraryGroup[]>())).catch(
() => [],
);
return groups.find((g) => g.kind === "go")?.roots[0]?.path ?? null;
}
/** A predeclared name's declaration in `$GOROOT/src/builtin/builtin.go`. */
async function builtin(name: string): Promise<DocTarget | null> {
const src = await goSourceRoot();
if (!src) return null;
const path = `${src}/builtin/builtin.go`;
const lines = (await readFileLines(path).catch(() => null)) ?? [];
const decl = new RegExp(`^(?:(?:type|func|var|const)\\s+|\\t)(${name})\\b`);
for (let line = 0; line < lines.length; line++) {
const m = decl.exec(lines[line]!);
if (m) return { path, line, col: m[0].length - name.length };
}
return null;
}
/** Where a name in a Go signature is declared; null when it isn't found exactly once. */
export async function resolveGoRef(ref: GoRef, ctx: GoRefContext): Promise<DocTarget | null> {
const { qualifier, name } = ref;
if (!qualifier) {
if (PREDECLARED.has(name)) return builtin(name);
const file = ctx.declaring ?? ctx.current;
if (!file) return null;
const dir = dirname(file);
return unique((await symbols(name)).filter((s) => s.name === name && dirname(s.location.path) === dir));
}
// A function's signature is qualified by the imports of the file asked about; a type's
// declaration is its source text, qualified by the declaring file's imports.
const files = [...new Set([ctx.declaring, ctx.current])];
const paths = new Set((await Promise.all(files.map(importsOf))).map((m) => m.get(qualifier)).filter((p) => !!p));
if (paths.size > 1) return null;
const [path] = paths;
if (path) return findInPackage(path, name);
// A package neither file imports: gopls names it by its package name.
return unique(
(await symbols(`${qualifier}.${name}`)).filter(
(s) => !!s.container && goPackageName(s.container) === qualifier && named(s, qualifier, name),
),
);
}
+13
Переглянути файл
@@ -0,0 +1,13 @@
/** Web documentation links a language server's convention lets us resolve to a declaration. */
import { findInPackage, pkgGoDevLink } from "./go";
import { findRustItem, rustDocLink } from "./rust";
import type { DocTarget } from "./symbols";
/** Looks up the declaration `href` documents; null when no language's rule reads the link. */
export function docUrlResolver(href: string): (() => Promise<DocTarget | null>) | null {
const go = pkgGoDevLink(href);
if (go) return () => findInPackage(go.importPath, go.name);
const rust = rustDocLink(href);
if (rust) return () => findRustItem(rust);
return null;
}
+145
Переглянути файл
@@ -0,0 +1,145 @@
import { describe, expect, it, vi } from "vitest";
import type { WorkspaceSymbol } from "@/bindings";
const LIB = "/rust/lib/rustlib/src/rust/library";
const REG = "/home/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f";
const files: Record<string, string> = {
[`${LIB}/std/src/ffi/mod.rs`]: "\n\npub use self::os_str::{OsStr, OsString};\n",
};
const sym = (name: string, path: string, container: string | null = null, line = 3): WorkspaceSymbol => ({
name,
kind: "struct",
container,
location: { path, range: { start: { line, col: 11 }, end: { line, col: 14 } } },
});
// What rust-analyzer answers per query (`*` = the dependencies instead of the workspace, `#` = every kind).
const index: Record<string, WorkspaceSymbol[]> = {
"ExitCode*": [
sym("ExitCode", `${LIB}/std/src/process.rs`),
sym("ExitCode", `${LIB}/std/src/sys/process/mod.rs`),
sym("ExitCode", `${LIB}/std/src/sys/process/unix/common.rs`),
],
"HashMap*": [
sym("HashMap", `${LIB}/vendor/hashbrown-0.17.1/src/map.rs`),
sym("HashMap", `${LIB}/std/src/collections/mod.rs`),
sym("HashMap", `${LIB}/std/src/collections/hash/map.rs`),
],
"OsString*": [sym("OsString", `${LIB}/std/src/ffi/os_str.rs`), sym("OsString", `${LIB}/std/src/ffi/mod.rs`, null, 2)],
"From*": [sym("From", `${LIB}/core/src/convert/mod.rs`)],
"push*#": [
sym("push", `${LIB}/alloc/src/vec/mod.rs`, "Vec<T, A>"),
sym("push", `${LIB}/alloc/src/string.rs`, "String"),
],
"None*#": [sym("None", `${LIB}/core/src/option.rs`, "Option")],
"exit*#": [sym("exit", `${LIB}/std/src/process.rs`), sym("exit", `${REG}/libc-0.2.170/src/unix/mod.rs`)],
Sku: [sym("Sku", "/work/rust-app/src/lib.rs")],
"Sku*": [sym("Sku", `${REG}/other-1.0.0/src/lib.rs`)],
"parse#": [sym("parse", "/work/rust-app/src/parser.rs"), sym("parse", "/work/rust-app/src/lib.rs", "Sku")],
"Value*": [sym("Value", `${REG}/serde_json-1.0.140/src/value/mod.rs`)],
Twice: [sym("Twice", "/work/a/src/lib.rs"), sym("Twice", "/work/b/src/lib.rs")],
};
vi.mock("@/platform/ipc", async (orig) => ({
...(await orig<typeof import("@/platform/ipc")>()),
commands: { lspWorkspaceSymbols: async (_id: number, q: string) => ({ status: "ok", data: index[q] ?? [] }) },
}));
vi.mock("../files", () => ({ readFileLines: async (p: string) => files[p]?.split("\n") ?? [] }));
const { rustDocLink, findRustItem } = await import("./rust");
const { docUrlResolver } = await import("./index");
describe("rustdoc links", () => {
it.each([
[
"https://doc.rust-lang.org/stable/std/process/struct.ExitCode.html",
{ crate: "std", modules: ["process"], kind: "struct", name: "ExitCode", member: null },
],
[
"https://doc.rust-lang.org/nightly/alloc/vec/struct.Vec.html#method.push",
{ crate: "alloc", modules: ["vec"], kind: "struct", name: "Vec", member: "push" },
],
[
"https://doc.rust-lang.org/stable/alloc/vec/struct.Vec.html#capacity-and-reallocation",
{ crate: "alloc", modules: ["vec"], kind: "struct", name: "Vec", member: null },
],
[
"https://docs.rs/inventory/0.1.0/inventory/struct.Sku.html",
{ crate: "inventory", modules: [], kind: "struct", name: "Sku", member: null },
],
[
"https://docs.rs/serde-json/latest/serde_json/value/enum.Value.html",
{ crate: "serde_json", modules: ["value"], kind: "enum", name: "Value", member: null },
],
["https://doc.rust-lang.org/stable/alloc/fmt/index.html", null],
["https://doc.rust-lang.org/nightly/core/primitive.char.html", null],
["https://doc.rust-lang.org/stable/core/iter/book/ch03-05-control-flow.html", null],
["https://docs.rs/serde", null],
["https://crates.io/keywords/hasher", null],
["https://docs.rs/x/1/x/struct.%E0%A4%A.html", null],
])("%s", (href, want) => expect(rustDocLink(href)).toEqual(want));
const at = (path: string, line = 3) => ({ path, line, col: 11 });
it.each([
[
"std struct, among private copies",
"https://doc.rust-lang.org/stable/std/process/struct.ExitCode.html",
at(`${LIB}/std/src/process.rs`),
],
[
"module path into a private submodule's file",
"https://doc.rust-lang.org/stable/std/collections/hash/map/struct.HashMap.html",
at(`${LIB}/std/src/collections/hash/map.rs`),
],
[
"re-export left out",
"https://doc.rust-lang.org/stable/std/ffi/struct.OsString.html",
at(`${LIB}/std/src/ffi/os_str.rs`),
],
["trait", "https://doc.rust-lang.org/stable/core/convert/trait.From.html", at(`${LIB}/core/src/convert/mod.rs`)],
[
"method of its type only",
"https://doc.rust-lang.org/stable/alloc/vec/struct.Vec.html#method.push",
at(`${LIB}/alloc/src/vec/mod.rs`),
],
[
"enum variant",
"https://doc.rust-lang.org/stable/core/option/enum.Option.html#variant.None",
at(`${LIB}/core/src/option.rs`),
],
[
"function, other crate's same name left out",
"https://doc.rust-lang.org/stable/std/process/fn.exit.html",
at(`${LIB}/std/src/process.rs`),
],
[
"the project's own crate (docs.rs)",
"https://docs.rs/inventory/0.1.0/inventory/struct.Sku.html",
at("/work/rust-app/src/lib.rs"),
],
[
"own module function, not a method",
"https://docs.rs/inventory/0.1.0/inventory/parser/fn.parse.html",
at("/work/rust-app/src/parser.rs"),
],
[
"registry crate",
"https://docs.rs/serde_json/1.0.140/serde_json/value/enum.Value.html",
at(`${REG}/serde_json-1.0.140/src/value/mod.rs`),
],
["registry crate of another version name", "https://docs.rs/serde_json/1.0.140/other/value/enum.Value.html", null],
["two local crates: ambiguous", "https://docs.rs/a/0.1.0/a/struct.Twice.html", null],
["not found", "https://doc.rust-lang.org/stable/std/process/struct.Missing.html", null],
["member not found", "https://doc.rust-lang.org/stable/alloc/string/struct.String.html#method.push_front", null],
])("%s", async (_, href, want) => {
expect(await findRustItem(rustDocLink(href)!)).toEqual(want);
});
it("is one of the languages documentation links resolve for", async () => {
expect(docUrlResolver("https://example.com/x")).toBeNull();
expect(await docUrlResolver("https://doc.rust-lang.org/stable/core/convert/trait.From.html")!()).toEqual(
at(`${LIB}/core/src/convert/mod.rs`),
);
});
});
+90
Переглянути файл
@@ -0,0 +1,90 @@
/**
* Rust documentation links (rust-analyzer): intra-doc links come as rustdoc URLs —
* `https://doc.rust-lang.org/<channel>/<crate>/<module…>/<kind>.<Name>.html[#method.<m>]`
* for the standard library, `https://docs.rs/<package>/<version>/<crate>/…` for other crates,
* the project's own included. They resolve through `workspace/symbol` by name, the crate and
* module the URL names and, for a member, its type; only a unique match counts.
*/
import type { WorkspaceSymbol } from "@/platform/ipc";
import { readFileLines } from "../files";
import { symbols, unique, type DocTarget } from "./symbols";
export interface RustDocLink {
crate: string;
/** Module path inside the crate (`["collections", "hash", "map"]`). */
modules: string[];
/** Item kind as rustdoc names its page (`struct`, `fn`, `trait`…). */
kind: string;
name: string;
/** `#method.push`, `#variant.None`…: that member of the item. */
member: string | null;
}
const IDENT = /^[A-Za-z_][A-Za-z0-9_]*$/;
const MEMBER = /^(?:method|tymethod|variant|structfield|associatedconstant|associatedtype)\.([A-Za-z_][A-Za-z0-9_]*)$/;
/** Pages of items `workspace/symbol` lists (not modules, primitives or keywords). */
const ITEM_KINDS = new Set(["struct", "enum", "trait", "union", "type", "fn", "macro", "constant", "static"]);
const TYPE_KINDS = new Set(["struct", "enum", "trait", "union", "type"]);
/** A rustdoc item URL on doc.rust-lang.org or docs.rs; null for other links. */
export function rustDocLink(href: string): RustDocLink | null {
// Malformed URLs and escapes are no links.
try {
const url = new URL(href);
const parts = url.pathname.split("/").filter(Boolean).map(decodeURIComponent);
// doc.rust-lang.org/<channel>/<crate>/…; docs.rs/<package>/<version>/<crate>/…
const skip = url.hostname === "doc.rust-lang.org" ? 1 : url.hostname === "docs.rs" ? 2 : -1;
if (skip < 0 || parts.length < skip + 2) return null;
const [crate, ...rest] = parts.slice(skip);
const page = /^(\w+)\.(\w+)\.html$/.exec(rest.pop()!);
if (!page || !ITEM_KINDS.has(page[1]!) || ![crate, ...rest].every((p) => IDENT.test(p!))) return null;
const member = MEMBER.exec(decodeURIComponent(url.hash.slice(1)))?.[1] ?? null;
return { crate: crate!, modules: rest, kind: page[1]!, name: page[2]!, member };
} catch {
return null;
}
}
/**
* Whether `path` can be `link`'s module of its crate: the module's file or a file under its
* directory. Files of the standard library and of downloaded crates also have to be that crate;
* the project's own crates can't be told apart by path.
*/
export function inModule(path: string, link: Pick<RustDocLink, "crate" | "modules">): boolean {
const m = /^(.*\/)?([^/]+)\/src\/(.*)$/.exec(path);
if (!m) return false;
const [, parent = "", dir, file] = m;
const crateDir = link.crate.replace(/_/g, "[-_]");
const packaged = /\/(?:registry\/src\/[^/]+|library\/vendor)\/$/.test(parent);
if (/\/library\/$/.test(parent) ? dir !== link.crate : packaged && !new RegExp(`^${crateDir}-\\d`).test(dir!))
return false;
if (!link.modules.length) return true;
const mod = link.modules.join("/");
return file === `${mod}.rs` || file!.startsWith(`${mod}/`);
}
/** The type a member's symbol belongs to, as rust-analyzer names its container (`Vec<T, A>` → `Vec`). */
function ownerName(s: WorkspaceSymbol): string {
return (s.container ?? "").replace(/<.*$/, "").trim();
}
/** A `use` line: rust-analyzer lists re-exports too, but the declaration is what's meant. */
async function isReexport(s: WorkspaceSymbol): Promise<boolean> {
const line = (await readFileLines(s.location.path).catch(() => null))?.[s.location.range.start.line] ?? "";
return /^\s*(?:pub(?:\([^)]*\))?\s+)?use\b/.test(line);
}
/** Where `link` is declared, when exactly one symbol fits it. */
export async function findRustItem(link: RustDocLink): Promise<DocTarget | null> {
const name = link.member ?? link.name;
// rust-analyzer's query markers: `*` searches the dependencies (instead of the workspace),
// `#` every kind of symbol (not only types).
// A common name (`Vec::new`) can be past rust-analyzer's 128 results; such links open in the browser.
const all = link.member || !TYPE_KINDS.has(link.kind) ? "#" : "";
const found = await Promise.all([symbols(`${name}${all}`), symbols(`${name}*${all}`)]);
const hits = found
.flat()
.filter((s) => s.name === name && (!link.member || ownerName(s) === link.name) && inModule(s.location.path, link));
const declared = await Promise.all(hits.map(async (s) => !(await isReexport(s))));
return unique(hits.filter((_, i) => declared[i]));
}
+23
Переглянути файл
@@ -0,0 +1,23 @@
/** `workspace/symbol` lookups shared by the per-language documentation link rules. */
import { call, commands, nextRequestId, type WorkspaceSymbol } from "@/platform/ipc";
export interface DocTarget {
path: string;
line: number;
col: number;
}
export async function symbols(query: string): Promise<WorkspaceSymbol[]> {
return call(commands.lspWorkspaceSymbols(nextRequestId(), query)).catch(() => []);
}
/** The one place `hits` name (the same place listed twice counts once); null when none or several. */
export function unique(hits: WorkspaceSymbol[]): DocTarget | null {
const places = new Map(
hits.map((s) => {
const { path, range } = s.location;
return [`${path}:${range.start.line}:${range.start.col}`, { path, ...range.start }] as const;
}),
);
return places.size === 1 ? [...places.values()][0]! : null;
}
+115 -26
Переглянути файл
@@ -3,14 +3,18 @@
* their documentation in place (⌘-click opens the source instead), ← / →
* walk the history, Edit Source (F4) jumps to the declaration, and F1 on a
* focused popup moves it to the Documentation tool window, which then shows
* F1's documentation instead of a popup while it is open.
* F1's documentation instead of a popup while it is open. The hover's
* documentation is the same view with its own history.
*/
import { create } from "zustand";
import { create, createStore, type StoreApi } from "zustand";
import { commands, nextRequestId, type Location } from "@/platform/ipc";
import { hasPrimaryModifier } from "@/platform/keymap";
import { editorService, maybeEditorService, toolWindowService } from "@/workbench/contributions";
import { closePopup, updatePopup, useLspPopup, type DocEntry } from "./popupStore";
import { isEmptyMarkup, languageForPath, sourceLink, type DocLinkHandler } from "./markdown";
import { isEmptyMarkup, languageForPath, openDocLink, sourceLink, type DocLinkHandler } from "./markdown";
import { resolveGoRef, signatureRef } from "./docLinks/go";
import { docUrlResolver } from "./docLinks";
import type { DocTarget } from "./docLinks/symbols";
import { lspRequest } from "./lsp";
import { readFileLines, withDocument } from "./files";
@@ -54,33 +58,79 @@ export function showInDocWindow(entry: DocEntry, themeClasses: string) {
toolWindowService().show(DOCUMENTATION_WINDOW, false);
}
/** F1 on a focused documentation popup: the popup's history moves to the tool window. */
export function moveDocPopupToWindow(): boolean {
/** F1 on a focused documentation popup: the popup's (or the hover's) history moves to the tool window. */
export function moveDocPopupToWindow(host: "popup" | HoverDoc = "popup"): boolean {
const h = history(host);
if (!h) return false;
const popup = useLspPopup.getState().popup;
if (popup?.kind !== "doc") return false;
useDocWindow.setState({ entries: popup.entries, index: popup.index, themeClasses: popup.themeClasses });
closePopup();
const themeClasses = host === "popup" && popup?.kind === "doc" ? popup.themeClasses : "";
useDocWindow.setState((s) => ({ entries: h.entries, index: h.index, themeClasses: themeClasses || s.themeClasses }));
closeHost(host);
toolWindowService().show(DOCUMENTATION_WINDOW, true);
return true;
}
// ---------------------------------------------------------------------------
// Hover documentation: each hover tooltip keeps its own history (an editor that comes back
// into view brings its open hover back too).
interface HoverDocState extends DocHistory {
close: () => void;
}
export type HoverDoc = StoreApi<HoverDocState>;
export function hoverDoc(entry: DocEntry, close: () => void): HoverDoc {
return createStore<HoverDocState>(() => ({ entries: [entry], index: 0, close }));
}
/** The size the documentation popup was last resized to, kept across sessions as IDEA does. */
const DOC_SIZE_KEY = "openidea.lsp.docPopupSize";
export const DOC_MIN_WIDTH = 240;
export const DOC_MIN_HEIGHT = 120;
export function loadDocSize(): { w: number; h: number } | null {
try {
const v = JSON.parse(localStorage.getItem(DOC_SIZE_KEY) ?? "null") as { w?: unknown; h?: unknown } | null;
return typeof v?.w === "number" && typeof v.h === "number" ? { w: v.w, h: v.h } : null;
} catch {
return null;
}
}
export function saveDocSize(size: { w: number; h: number }) {
try {
localStorage.setItem(DOC_SIZE_KEY, JSON.stringify(size));
} catch {
// Storage unavailable: the next popup opens at its default size.
}
}
// ---------------------------------------------------------------------------
// Shared by the popup and the tool window
/** Where a doc view keeps its history: the popup or the tool window. */
export type DocHost = "popup" | "window";
/** Where a doc view keeps its history: the F1 popup, the hover or the tool window. */
export type DocHost = "popup" | "window" | HoverDoc;
function history(host: DocHost): DocHistory | null {
if (host === "window") return useDocWindow.getState();
if (typeof host === "object") return host.getState();
const p = useLspPopup.getState().popup;
return p?.kind === "doc" ? p : null;
}
function setHistory(host: DocHost, h: DocHistory) {
if (host === "window") useDocWindow.setState(h);
else if (typeof host === "object") host.setState(h);
else updatePopup("doc", h);
}
/** Closes the popup or the hover a link or Edit Source leaves; the tool window stays. */
function closeHost(host: DocHost) {
if (host === "popup") closePopup();
else if (typeof host === "object") host.getState().close();
}
export function docStep(host: DocHost, delta: -1 | 1) {
const h = history(host);
if (h) setHistory(host, { entries: h.entries, index: stepHistory(h, delta) });
@@ -92,7 +142,7 @@ export async function editDocSource(host: DocHost): Promise<boolean> {
const entry = h?.entries[h.index];
const loc = (await entry?.source?.().catch(() => null)) ?? null;
if (!loc) return false;
if (host === "popup") closePopup();
closeHost(host);
await editorService().openFile(loc.path, {
selection: { line: loc.range.start.line, col: loc.range.start.col },
focus: true,
@@ -130,37 +180,76 @@ async function docAt(target: { path: string; line: number; col: number }): Promi
path: target.path,
range: { start: { line: target.line, col }, end: { line: target.line, col } },
};
return { markup: hover.contents, language: languageForPath(target.path), source: async () => location };
return {
markup: hover.contents,
language: languageForPath(target.path),
file: target.path,
source: async () => location,
};
}
}
return null;
});
}
/** Shows `target`'s documentation as the next history step; without any, opens its source. */
async function followTo(host: DocHost, target: DocTarget) {
const entry = await docAt(target).catch(() => null);
const h = history(host);
if (!entry || !h) {
closeHost(host);
void maybeEditorService()?.openFile(target.path, {
selection: { line: target.line, col: target.col },
focus: true,
});
return;
}
setHistory(host, pushHistory(h, entry));
}
/**
* Link clicks in a documentation view: a source link shows that symbol's
* documentation in the same view (⌘-click opens the source instead).
* documentation in the same view (⌘-click opens the source instead); so does
* a web link a language's rule (`docLinks/`) finds the symbol of, others open in the browser.
*/
export function docLinkHandler(host: DocHost): DocLinkHandler {
return (href, e) => {
const target = sourceLink(href);
if (!target || hasPrimaryModifier(e)) {
if (host === "popup" && target) closePopup();
const web = target ? null : docUrlResolver(href);
if ((!target && !web) || hasPrimaryModifier(e)) {
if (target) closeHost(host);
return false;
}
void (async () => {
const entry = await docAt(target).catch(() => null);
const h = history(host);
if (!entry || !h) {
if (host === "popup") closePopup();
void maybeEditorService()?.openFile(target.path, {
selection: { line: target.line, col: target.col },
focus: true,
});
return;
}
setHistory(host, pushHistory(h, entry));
const found = target ?? (web && (await web().catch(() => null)));
if (found) await followTo(host, found);
else openDocLink(href);
})();
return true;
};
}
/** The signature block of gopls documentation, whose type names `linkSignatureTypes` follows. */
const GO_SIGNATURE = ":scope > pre:first-of-type > code.language-go";
/**
* Go: a click on a type name in the signature shows that type's documentation
* in the same view, when the name resolves to exactly one declaration.
*/
export function linkSignatureTypes(dom: HTMLElement, host: DocHost, entry: DocEntry) {
dom.addEventListener("click", (e) => {
const name = (e.target as Element | null)?.closest?.(".tok-typeName");
const code = dom.querySelector(GO_SIGNATURE);
if (!name || !code?.contains(name) || !document.getSelection()?.isCollapsed) return;
const before = document.createRange();
before.setStart(code, 0);
before.setEndBefore(name);
const from = before.toString().length;
const ref = signatureRef(code.textContent ?? "", from, from + (name.textContent ?? "").length);
void (async () => {
const declaring = (await entry.source?.().catch(() => null))?.path ?? null;
const target = await resolveGoRef(ref, { declaring, current: entry.file ?? null }).catch(() => null);
if (target) await followTo(host, target);
})();
});
}
+24 -18
Переглянути файл
@@ -19,7 +19,7 @@ import {
import { executeAction } from "@/platform/actions";
import { shortcutLabel } from "@/platform/keymap";
import { diagnosticsAt, type PlacedDiagnostic, type EditorDiagnostic } from "./diagnostics";
import { isEmptyMarkup, languageForPath, renderMarkup } from "./markdown";
import { isEmptyMarkup, languageForPath } from "./markdown";
import { selectableText } from "@/ui/selectableText";
import { docOf, lspRequest, reportLspError } from "./lsp";
import { requestNavigation } from "./configurationNavigation";
@@ -28,7 +28,8 @@ import { showHint } from "./hint";
import { caretAnchor, focusPopup, openPopup, useLspPopup, type DefinitionTarget, type DocEntry } from "./popupStore";
import { selectedLookupDoc, showLookupDocs } from "./completion";
import { readFileLines, targetLabel, withDocument } from "./files";
import { docWindowVisible, moveDocPopupToWindow, showInDocWindow } from "./docs";
import { docWindowVisible, hoverDoc, moveDocPopupToWindow, showInDocWindow } from "./docs";
import { mountHoverDoc } from "./DocView";
import { structure } from "@/editor/structure";
import { basename } from "@/platform/project";
import { iconNode } from "@/ui/iconNode";
@@ -178,7 +179,7 @@ export async function hoverSource(view: EditorView, pos: number) {
const word = view.state.wordAt(pos);
if (word) ({ from, to } = word);
}
const lang = docOf(view)?.uiMode ?? null;
const entry = hover && docEntry(view, pos, hover);
return {
pos: from,
end: to,
@@ -187,8 +188,11 @@ export async function hoverSource(view: EditorView, pos: number) {
const dom = document.createElement("div");
dom.className = `cm-lsp-hover ${selectableText}`;
if (diags.length) dom.appendChild(renderDiagnostics(view, diags));
if (hover) dom.appendChild(renderMarkup(hover.contents, lang));
return { dom };
if (!entry) return { dom };
// The same documentation view as F1's popup: links open in place, ← / →, Edit Source.
dom.classList.add("cm-lsp-hover-doc");
const doc = hoverDoc(entry, () => view.dispatch({ effects: closeHoverTooltips }));
return { dom, destroy: mountHoverDoc(dom.appendChild(document.createElement("div")), doc) };
},
};
}
@@ -239,6 +243,20 @@ function definitionOf(doc: number, pos: Pos): () => Promise<Location | null> {
));
}
/** The documentation `hover` shows for `pos`, with its declaration for Edit Source. */
function docEntry(view: EditorView, pos: number, hover: Hover): DocEntry {
const ctx = docOf(view);
return {
markup: hover.contents,
language: ctx?.uiMode ?? null,
file: ctx?.path,
source:
ctx && !constructAt(view.state, pos, ctx.language)
? definitionOf(ctx.doc, offsetToPos(view.state.doc, pos))
: undefined,
};
}
function showDoc(view: EditorView, entry: DocEntry, at: number) {
if (docWindowVisible()) {
showInDocWindow(entry, view.themeClasses);
@@ -287,19 +305,7 @@ export async function quickDocumentation(view: EditorView) {
showHint(view, "No documentation found");
return;
}
const ctx = docOf(view);
showDoc(
view,
{
markup: hover.contents,
language: ctx?.uiMode ?? null,
source:
ctx && !constructAt(view.state, pos, ctx.language)
? definitionOf(ctx.doc, offsetToPos(view.state.doc, pos))
: undefined,
},
hover.range ? rangeToOffsets(view.state.doc, hover.range).from : pos,
);
showDoc(view, docEntry(view, pos, hover), hover.range ? rangeToOffsets(view.state.doc, hover.range).from : pos);
} catch (e) {
reportLspError(view, e, true);
}
+1
Переглянути файл
@@ -68,6 +68,7 @@ describe("sourceLink", () => {
it("reads the file and position a documentation link names", () => {
project("C:/repo");
expect(sourceLink("file:///C:/repo/src/a.py#L12,5")).toEqual({ path: "/C:/repo/src/a.py", line: 11, col: 4 });
expect(sourceLink("file:///p/src/cart.ts#L20%2C3")).toEqual({ path: "/p/src/cart.ts", line: 19, col: 2 });
expect(sourceLink("https://example.com/a.py")).toBeNull();
});
+2 -1
Переглянути файл
@@ -208,7 +208,8 @@ export function sourceLink(href: string): { path: string; line: number; col: num
const path = decodeURIComponent(url.pathname);
// Documentation is text someone else wrote.
if (onOtherShare(path, useProject.getState().project?.root ?? "")) return null;
const m = /^#?L?(\d+)(?:[,:](\d+))?/.exec(url.hash.slice(1));
// typescript-language-server encodes the comma (`#L20%2C3`).
const m = /^#?L?(\d+)(?:[,:](\d+))?/.exec(url.hash.slice(1).replace(/%2C/gi, ","));
return {
path,
line: m ? Math.max(0, Number(m[1]) - 1) : 0,
+2
Переглянути файл
@@ -48,6 +48,8 @@ export interface DiffLine {
export interface DocEntry {
markup: Markup;
language: string | null;
/** The file the documentation was asked about in (its imports qualify Go signatures). */
file?: string;
/** Declaration of the documented element (Edit Source), resolved on demand. */
source?: () => Promise<Location | null>;
}
+5 -4
Переглянути файл
@@ -225,10 +225,11 @@ export const lspTheme = EditorView.theme({
".cm-tooltip.cm-tooltip-hover": { ...tooltipSurface, display: "flex", flexDirection: "column" },
".cm-tooltip-hover > .cm-tooltip-section": { minHeight: 0, flexShrink: 1 },
".cm-lsp-hover": { maxWidth: "580px", maxHeight: "380px", overflow: "auto", padding: "10px 14px" },
".cm-lsp-hover-diagnostics + .cm-lsp-markdown": {
borderTop: "1px solid var(--border-popup)",
margin: "10px -14px 0",
padding: "10px 14px 0",
// With documentation the doc view pads its own body and keeps its toolbar at the bottom.
".cm-lsp-hover.cm-lsp-hover-doc": { padding: "0" },
".cm-lsp-hover-doc > .cm-lsp-hover-diagnostics": {
padding: "10px 14px",
borderBottom: "1px solid var(--border-popup)",
},
".cm-lsp-diag": {
display: "flex",
+9 -3
Переглянути файл
@@ -33,7 +33,7 @@ import { executeAction } from "@/platform/actions";
import { call, commands, onIdeEvent } from "@/platform/ipc";
import { isSameOrInside } from "@/platform/paths";
import { basename, relativeDir, useProject } from "@/platform/project";
import { notifications, useEditorShown, type EditorInput } from "@/workbench/contributions";
import { notifications, useEditorShown, useToolWindowShown, type EditorInput } from "@/workbench/contributions";
import { confirm } from "@/workbench/messages";
import {
Button,
@@ -150,7 +150,7 @@ import {
useAgentCommands,
useAgents,
} from "./store";
import { setFocusedSession, focusedSession, type FocusedSession } from "./sessionFocus";
import { setFocusedSession, focusedSession, registerReachableSession, type FocusedSession } from "./sessionFocus";
import { taskMenu } from "./taskActions";
import styles from "./Session.module.css";
@@ -225,7 +225,10 @@ function TaskSession({ id, docked }: { id: string; docked: boolean }) {
const { fitWindowWidth } = useAgentSettings();
const sessionRoot = useRef<HTMLDivElement>(null);
const { fontZoom, zoomStyle } = useAgentFontZoomSurface(sessionRoot, sessionKey(id), docked, !!task);
const canFocusInput = shown && !!task && task.status !== "archived" && !view;
// A docked task is on screen while its tool window is; a tab's own `shown` is its editor slot's.
const toolWindowShown = useToolWindowShown();
const onScreen = docked ? toolWindowShown : shown;
const canFocusInput = onScreen && !!task && task.status !== "archived" && !view;
const session = useMemo<FocusedSession>(
() => ({
openFind: () => {
@@ -247,6 +250,9 @@ function TaskSession({ id, docked }: { id: string; docked: boolean }) {
if (focusedSession() === session) setFocusedSession(null);
};
}, [session, shown]);
useLayoutEffect(() => {
if (session.focusInput) return registerReachableSession(session);
}, [session]);
if (!task) return <EmptyState title="This agent task no longer exists" />;
return (
<div
+7 -5
Переглянути файл
@@ -36,7 +36,7 @@ import {
providerIcon,
} from "./model";
import { sendPaths, sendSelection, trackEditorCopies } from "./references";
import { focusedSession } from "./sessionFocus";
import { focusedSession, inputSession } from "./sessionFocus";
import { cycleFocusedEffort } from "./effortFocus";
import { clearAgentTabFontZoom } from "./fontZoom";
import {
@@ -227,11 +227,13 @@ export function activate(): () => void {
{
id: "agents.focusInput",
title: "Focus Agent Input",
description: "Focuses the message input of the current agent task without moving the caret.",
description:
"Focuses the message input of the current agent task, or of the one on screen when focus is elsewhere and no panel claims the shortcut, without moving the caret.",
category: "Agents",
when: "agentSessionFocus && agentInputAvailable",
keyWhen: "agentSessionFocus && !popupOpen",
run: () => focusedSession()?.focusInput?.(),
when: "agentInputAvailable",
// In a task view it wins over the editor's Go to Line; elsewhere it yields wherever that applies.
keyWhen: "!popupOpen && (agentSessionFocus || !(textEditorActive && (editorFocus || !toolWindowFocus)))",
run: () => inputSession()?.focusInput?.(),
},
{
id: "agents.cycleEffort",
+26 -3
Переглянути файл
@@ -1,4 +1,4 @@
/** The agent session holding focus, for actions scoped to that task view. */
/** The agent session holding focus, and those shown elsewhere, for actions scoped to a task view. */
import { setContext } from "@/platform/context";
export interface FocusedSession {
@@ -7,11 +7,34 @@ export interface FocusedSession {
}
let focused: FocusedSession | null = null;
/** Sessions on screen that accept input, least recently focused first. */
let reachable: FocusedSession[] = [];
/** The session `Focus Agent Input` targets: the focused one, else the most recently used shown one. */
export function inputSession(): FocusedSession | null {
if (focused) return focused.focusInput ? focused : null;
return reachable.at(-1) ?? null;
}
function publish() {
setContext("agentSessionFocus", !!focused);
setContext("agentInputAvailable", !!inputSession());
}
export function setFocusedSession(session: FocusedSession | null) {
focused = session;
setContext("agentSessionFocus", !!session);
setContext("agentInputAvailable", !!session?.focusInput);
if (session && reachable.includes(session)) reachable = [...reachable.filter((s) => s !== session), session];
publish();
}
/** Lists a shown session that accepts input as a target for the shortcut; returns a disposer. */
export function registerReachableSession(session: FocusedSession): () => void {
reachable = [...reachable.filter((s) => s !== session), session];
publish();
return () => {
reachable = reachable.filter((s) => s !== session);
publish();
};
}
export const focusedSession = () => focused;
-62
Переглянути файл
@@ -445,68 +445,6 @@ describe("Check for Updates", () => {
});
});
describe("automatic nightly update prompts", () => {
const DAY = 24 * 60 * 60 * 1000;
const update = (currentVersion: string): UpdateInfo => ({
version: "0.1.41",
currentVersion,
notes: null,
date: null,
});
const startupCheck = async (currentVersion: string) => {
notes = [];
await notifyUpdate(update(currentVersion));
return notes.length;
};
beforeEach(() => {
localStorage.clear();
vi.useFakeTimers({ toFake: ["Date"], now: 10 * DAY });
});
afterEach(() => vi.useRealTimers());
it("leaves stable prompts to the backend announcement policy", async () => {
expect(await startupCheck("0.1.40")).toBe(1);
expect(await startupCheck("0.1.40")).toBe(1);
});
it("asks a nightly build at most once a day", async () => {
const nightly = "0.1.41-nightly.202611081417";
expect(await startupCheck(nightly)).toBe(1);
vi.setSystemTime(11 * DAY - 1);
expect(await startupCheck(nightly)).toBe(0);
vi.setSystemTime(11 * DAY);
expect(await startupCheck(nightly)).toBe(1);
});
it("does not prompt twice a day for periodic nightly checks, but always answers a manual check", async () => {
const nightly = "0.1.41-nightly.202611081417";
const dispose = installUpdateChecks();
await tick();
try {
const available = updateListeners.get("updateAvailable")!;
available({ update: update(nightly) });
await tick();
expect(notes).toHaveLength(1);
vi.setSystemTime(10 * DAY + 4 * 60 * 60 * 1000);
available({ update: { ...update(nightly), version: "0.1.42-nightly.202611090200" } });
await tick();
expect(notes).toHaveLength(1);
const done = checkForUpdates();
check.resolve(ok({ enabled: true, update: update(nightly) }));
await done;
expect(notes.at(-1)).toMatchObject({ title: "OpenIDEA 0.1.41 is available", userInitiated: true });
notes = [];
vi.setSystemTime(11 * DAY);
available({ update: { ...update(nightly), version: "0.1.42-nightly.202611091400" } });
await tick();
expect(notes).toHaveLength(1);
} finally {
dispose();
}
});
});
describe("updateSource", () => {
const withSettings = (updateSource: string | undefined, locale: string | undefined) =>
useProject.setState({ settings: { general: { updateSource }, appearance: { locale } } as unknown as Settings });
-12
Переглянути файл
@@ -121,17 +121,6 @@ async function runCheck() {
}
}
const NIGHTLY_PROMPT_KEY = "openidea.update.nightlyPromptedAt";
const NIGHTLY_PROMPT_INTERVAL_MS = 24 * 60 * 60 * 1000;
/** Nightly builds come out more often than anyone wants to be asked: at most one prompt a day. */
function nightlyPromptDue(now = Date.now()): boolean {
const last = Number(localStorage.getItem(NIGHTLY_PROMPT_KEY));
if (now - last < NIGHTLY_PROMPT_INTERVAL_MS) return false;
localStorage.setItem(NIGHTLY_PROMPT_KEY, String(now));
return true;
}
/** Start one backend schedule after this window can receive its notifications. */
export function installUpdateChecks(): () => void {
let disposed = false;
@@ -167,7 +156,6 @@ export async function notifyUpdate(update: UpdateInfo, userInitiated = false): P
);
if (!claimed) return;
}
if (!userInitiated && update.currentVersion.includes("-nightly.") && !nightlyPromptDue()) return;
notifications().notify({
level: "info",
title: t("app.update.available", { version: update.version }),
+18
Переглянути файл
@@ -176,6 +176,24 @@ describe("run config → launch config", () => {
expect(extra(uv)).toMatchObject({ python: ["uv", "run", "python"], debugLauncherPython: "python" });
});
it("debugpy: a Windows venv interpreter or tool path debugs with that interpreter", () => {
usePlatform.setState({ os: "windows" });
const venv = "C:\\work\\app\\.venv\\Scripts\\";
const script = launchConfigFor(
rc({ kind: "python", command: `${venv}python.exe`, args: ["main.py"], debugAdapter: "debugpy" }),
"C:/work/app",
)!;
expect(extra(script).python).toBe(`${venv}python.exe`);
expect(extra(script).module).toBeUndefined();
expect(script.program).toBe("C:/work/app/main.py");
const pytest = launchConfigFor(
rc({ kind: "pytest", command: `${venv}pytest.exe`, args: ["-x"], debugAdapter: "debugpy" }),
"C:/work/app",
)!;
expect(extra(pytest)).toMatchObject({ module: "pytest", python: `${venv}python.exe` });
});
it("js-debug: npm scripts run through the package manager, node scripts directly", () => {
const npm = launchConfigFor(
rc({ kind: "npm", command: "pnpm", args: ["run", "dev"], cwd: "web", debugAdapter: "js-debug" }),
+6 -6
Переглянути файл
@@ -76,7 +76,7 @@ function cargoLaunch(rc: RunConfig, cwd: string, adapter: string): LaunchConfig
};
}
const PYTHON_NAME = /^python[\d.]*(\.exe)?$/;
const PYTHON_NAME = /^python[\d.]*(\.exe)?$/i;
/** `python` on Windows (`python3` is at most a Store alias there, and venvs have no `python3.exe`), `python3` elsewhere. */
function systemPython(): string {
@@ -85,10 +85,10 @@ function systemPython(): string {
function pythonFor(rc: RunConfig, cwd: string): string {
const cmd = rc.command;
const name = cmd.split("/").pop() ?? cmd;
if (PYTHON_NAME.test(name)) return resolveCommand(cmd, cwd);
// A venv tool such as `.venv/bin/pytest`: use the interpreter next to it.
if (cmd.includes("/")) return resolveCommand(cmd.slice(0, cmd.lastIndexOf("/") + 1) + "python", cwd);
if (PYTHON_NAME.test(commandName(cmd))) return resolveCommand(cmd, cwd);
// A venv tool such as `.venv/bin/pytest` or `.venv\Scripts\pytest.exe`: use the interpreter next to it.
const dir = cmd.slice(0, Math.max(cmd.lastIndexOf("/"), cmd.lastIndexOf("\\")) + 1);
if (dir) return resolveCommand(dir + (hostOs() === "windows" ? "python.exe" : "python"), cwd);
return systemPython();
}
@@ -107,7 +107,7 @@ function debugpyLaunch(rc: RunConfig, cwd: string): LaunchConfig {
subProcess: dbg.python.attachSubprocess,
};
if (dbg.python.gevent) extra.gevent = true;
const name = (rc.command.split("/").pop() ?? rc.command).replace(/\.exe$/, "");
const name = commandName(rc.command);
let args = rc.args;
let tool: string | null = PYTHON_NAME.test(name) ? null : name;
if (PYTHON_RUNNERS.has(name) && args[0] === "run" && args[1]) {
+2 -2
Переглянути файл
@@ -1,8 +1,8 @@
/**
* The one-time notice for installs whose settings file still names the removed
* `one-dark` built-in (#2981): One Dark now ships as the One Dark Pro marketplace
* plugin, and the notice offers to install it. Shown once (a `localStorage` flag,
* like the nightly update prompt); the backend only reports the raw id, the notice
* plugin, and the notice offers to install it. Shown once (a `localStorage` flag);
* the backend only reports the raw id, the notice
* decides what it means.
*/
import { tx } from "@/platform/i18n";
+5 -2
Переглянути файл
@@ -28,10 +28,13 @@ export function applicationConfig(
configs: readonly RunConfig[] = [],
): RunConfig {
const module = jvmModuleDir(relPath, configs);
const id = `application:${module ? `${module}:` : ""}${target.className}`;
// Project detection also recognises annotations carrying @SpringBootApplication.
const spring = target.spring || configs.some((c) => c.id === id && c.kind === "spring-boot");
return {
id: `application:${module ? `${module}:` : ""}${target.className}`,
id,
name: simpleClassName(target.className),
kind: target.spring ? "spring-boot" : "application",
kind: spring ? "spring-boot" : "application",
command: "java",
args: ["-cp", isTestSource(relPath) ? TEST_CLASSPATH : CLASSPATH, target.className],
cwd: null,
+25
Переглянути файл
@@ -235,6 +235,31 @@ describe("application configurations", () => {
});
});
it("runs a main class as Spring Boot when the annotation carries @SpringBootApplication", () => {
const rel = "src/main/java/shop/GatewayApp.java";
const cloud =
"package shop;\n@SpringCloudApplication\nclass GatewayApp {\n public static void main(String[] a) {}\n}";
expect(
targetConfig(
detectRunTargets(cloud, rel).find((t) => t.kind === "main")!,
rel,
maven,
cloud,
),
).toMatchObject({
kind: "spring-boot",
});
// A project annotation: project detection found the application.
const own = "package shop;\n@ShopApplication\nclass GatewayApp {\n public static void main(String[] a) {}\n}";
const main = detectRunTargets(own, rel).find((t) => t.kind === "main")!;
expect(targetConfig(main, rel, maven, own)).toMatchObject({ kind: "application" });
const detected = { ...applicationConfig({ className: "shop.GatewayApp" }, rel), kind: "spring-boot" as const };
expect(targetConfig(main, rel, [...maven, detected], own)).toMatchObject({
id: "application:shop.GatewayApp",
kind: "spring-boot",
});
});
it("scopes Maven and Gradle test configs to a class or method", () => {
const file = cfg({ id: "f", kind: "maven", args: ["test", "-Dtest=OrderTest"], isTest: true });
expect(jvmTestConfig(file, "a.OrderTest$Nested", "fails")).toMatchObject({
+6 -3
Переглянути файл
@@ -21,6 +21,9 @@ export interface JvmTarget {
instance?: boolean;
}
const BOOT_ANNOTATIONS = ["SpringBootApplication", "SpringCloudApplication"];
const isBootApplication = (annotations: readonly string[]) => annotations.some((a) => BOOT_ANNOTATIONS.includes(a));
/** A class with `extends X` and no `main` of its own: it may inherit one. */
export interface JvmMainCandidate {
/** Position of the class name (0-based line, UTF-16 column). */
@@ -196,7 +199,7 @@ function scan(src: string, relPath: string, kotlin: boolean) {
col: frame.inheritsFrom.col,
className: qualify(binaryName([...classes, frame])),
base: frame.inheritsFrom.base,
spring: frame.annotations.includes("SpringBootApplication") || undefined,
spring: isBootApplication(frame.annotations) || undefined,
});
classes.push(frame);
pendingClass = null;
@@ -290,7 +293,7 @@ function scan(src: string, relPath: string, kotlin: boolean) {
line: tokens[i]!.line,
kind: "main",
className: qualify(binaryName(launch)),
spring: cls.annotations.includes("SpringBootApplication") || undefined,
spring: isBootApplication(cls.annotations) || undefined,
});
}
}
@@ -298,7 +301,7 @@ function scan(src: string, relPath: string, kotlin: boolean) {
const isStatic = modifiers.includes("static");
// Java 25 instance main methods (JEP 512) need no `static` / arguments.
if (isStatic || owner.kind === "class" || owner.kind === "record") {
const spring = classes.some((c) => c.annotations.includes("SpringBootApplication"));
const spring = classes.some((c) => isBootApplication(c.annotations));
out.push({
line: tokens[i]!.line,
kind: "main",
+35 -1
Переглянути файл
@@ -1,6 +1,7 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { provideToolWindowService, type ToolWindowService } from "@/workbench/contributions";
import { closeAll, getSession, newTab, useTerminals } from "./store";
import { getContext, setContext } from "@/platform/context";
import { closeAll, closeTab, getSession, newTab, useTerminals } from "./store";
const { focused } = vi.hoisted(() => ({ focused: [] as string[] }));
@@ -95,3 +96,36 @@ describe("shell exit with sessions left", () => {
expect(document.activeElement).toBe(editor);
});
});
describe("terminalFocus after the focused pane goes away", () => {
function typeInto(key: string) {
const host = (getSession(key) as unknown as { host: HTMLDivElement }).host;
const input = document.createElement("textarea");
host.appendChild(input);
document.body.appendChild(host);
input.focus();
setContext("terminalFocus", true);
}
it("is cleared when the shell exits and the last tab closes", () => {
const tab = newTab("/repo");
typeInto(tab.session);
shellExit(tab.session);
expect(getContext().terminalFocus).toBe(false);
});
it("is cleared when the focused tab is closed", () => {
const tab = newTab("/repo");
typeInto(tab.session);
closeTab(tab.id);
expect(getContext().terminalFocus).toBe(false);
});
it("is left alone when a background session ends", () => {
const a = newTab("/repo");
const b = newTab("/repo");
typeInto(b.session);
closeTab(a.id);
expect(getContext().terminalFocus).toBe(true);
});
});
+25 -1
Переглянути файл
@@ -34,11 +34,35 @@ export function trimUrl(url: string): string {
}
}
/**
* A `file://` URL (compiler output such as Kotlin's `file:///src/A.kt:15:56`) as a file location:
* it opens in the editor, on the machine the terminal runs on, like a plain path.
*/
function fileUrlTarget(url: string): { path: string; line?: number; col?: number } | null {
const m = /^file:\/\/[^/]*(\/.*?)(?::(\d+)(?::(\d+))?)?$/i.exec(url);
if (!m) return null;
let path: string;
try {
path = decodeURIComponent(m[1]!);
} catch {
return null;
}
// `file:///C:/x` is the Windows path `C:/x`.
if (/^\/[A-Za-z]:\//.test(path)) path = path.slice(1);
return { path, line: m[2] ? Number(m[2]) : undefined, col: m[3] ? Number(m[3]) : undefined };
}
export function findTerminalLinks(text: string): TerminalLink[] {
const links: TerminalLink[] = [];
for (const m of text.matchAll(URL_RE)) {
const url = trimUrl(m[0]);
links.push({ kind: "url", start: m.index, end: m.index + url.length, text: url, url });
const end = m.index + url.length;
const file = fileUrlTarget(url);
links.push(
file
? { kind: "file", start: m.index, end, text: url, ...file }
: { kind: "url", start: m.index, end, text: url, url },
);
}
const overlaps = (s: number, e: number) => links.some((l) => s < l.end && e > l.start);
for (const m of text.matchAll(FILE_RE)) {
+6 -1
Переглянути файл
@@ -144,7 +144,12 @@ function createSession(cwd: string, command?: SessionOptions["command"], fallbac
}
function disposeSession(key: string) {
sessions.get(key)?.dispose();
const session = sessions.get(key);
const focus = document.activeElement;
// Removing the focused pane fires no blur, so `terminalFocus` would stay set (⌘T would keep
// opening terminal tabs). Another pane taking the caret sets it again.
if (focus && session?.host?.contains(focus)) publishFocus(false);
session?.dispose();
sessions.delete(key);
useTerminals.setState((s) => {
const next = { ...s.sessions };
+13
Переглянути файл
@@ -99,6 +99,19 @@ describe("terminal links", () => {
expect(findTerminalLinks("12:30 http://localhost:3000").map((l) => l.kind)).toEqual(["url"]);
});
it("opens file:// URLs as file locations", () => {
const line = "[ERROR] file:///develop/mc/src/main/kotlin/top/A%20B.kt:15:56 Unresolved reference 'x'.";
expect(findTerminalLinks(line)).toEqual([
expect.objectContaining({ kind: "file", path: "/develop/mc/src/main/kotlin/top/A B.kt", line: 15, col: 56 }),
]);
expect(findTerminalLinks("see file:///C:/work/a.kt:3")).toEqual([
expect.objectContaining({ kind: "file", path: "C:/work/a.kt", line: 3, col: undefined }),
]);
expect(findTerminalLinks("file://host/srv/x.txt")).toEqual([
expect.objectContaining({ kind: "file", path: "/srv/x.txt", line: undefined }),
]);
});
it("trims trailing punctuation from URLs", () => {
expect(trimUrl("https://a.dev/x.")).toBe("https://a.dev/x");
expect(trimUrl("https://a.dev/(x)")).toBe("https://a.dev/(x)");
+69 -3
Переглянути файл
@@ -202,6 +202,11 @@
flex: none;
overflow: hidden;
text-overflow: ellipsis;
/* Keep the first glyph clear of the divider on this column's left edge.
box-sizing: border-box keeps the width and boundary position unchanged. */
padding-inline-start: var(--space-2);
/* Anchor for the full-height column resize strip (IDEA's invisible divider). */
position: relative;
}
.columnHeading {
position: relative;
@@ -219,17 +224,75 @@
.columnHeading.dropAfter {
box-shadow: inset -2px 0 0 var(--accent);
}
/* Column divider: an 8px hit strip centred on the column's LEFT edge, with a
visible rule and grip so the resize target is easy to see and grab. Each row
carries one, so the rule runs the full table height. */
.columnResize {
position: absolute;
inset-block: 0;
inset-inline-end: 0;
width: 6px;
/* Keep the strip centre (and rule) at the cell's left edge: the cell has
overflow:hidden, so any rule drawn into the 8px gap would be clipped away. */
inset-inline-start: -4px;
width: 8px;
cursor: ew-resize;
touch-action: none;
z-index: 1;
display: flex;
align-items: center;
justify-content: center;
}
/* Divider line is opt-in (View Options › Columns › Column Dividers, off by
default like IDEA). The transparent hit strip and resize cursor always work;
only the paint is gated. */
.columnResize::before,
.columnResize::after {
content: "";
display: none;
}
.showDividers .columnResize::before {
display: block;
position: absolute;
inset-block: 0;
inset-inline-start: 4px;
width: 1px;
background: var(--border-strong);
}
.showDividers .columnResize::after {
display: block;
width: 2px;
height: 16px;
border-radius: 1px;
background: var(--control-off);
}
.showDividers .columnResize:hover::before,
.showDividers .columnResize:active::before {
background: var(--accent);
width: 2px;
}
.showDividers .columnResize:hover::after,
.showDividers .columnResize:active::after {
background: var(--accent);
}
/* First column's border: visible only when dividers are on, never draggable. */
.columnResizeDisabled {
cursor: default;
}
.showDividers .columnResizeDisabled::after {
display: none;
}
.showDividers .columnResizeDisabled:hover::before,
.showDividers .columnResizeDisabled:active::before {
background: var(--border-strong);
width: 1px;
}
/* Data-row strips keep the full-height rule but not the repeating grip. */
.columnResizeRow::after {
display: none;
}
.columnResize:focus-visible {
outline: 2px solid var(--focus-ring);
outline-offset: -2px;
outline-offset: -1px;
border-radius: 1px;
}
/* View Options › Highlight › Current Branch: commits reachable from HEAD are tinted. */
.currentBranch {
@@ -256,6 +319,9 @@
display: flex;
align-items: center;
gap: var(--space-1-5);
/* Anchor for the left divider. The graph SVG uses lane-relative coordinates,
so a positioned parent does not move it. */
position: relative;
/* Let graph endpoints overlap adjacent rows, but never paint over the next column. */
overflow-x: clip;
overflow-y: visible;
+129 -3
Переглянути файл
@@ -157,7 +157,7 @@ describe("log controls", () => {
useLogOptions.setState({ showColumnHeaders: true });
render(<LogView />);
const author = await screen.findByRole("separator", { name: "Resize Author column" });
fireEvent.keyDown(author, { key: "ArrowRight" });
fireEvent.keyDown(author, { key: "ArrowLeft" });
expect(useLogOptions.getState().columnWidths.author).toBe(140);
fireEvent.keyDown(author, { key: "ArrowRight", altKey: true });
expect(useLogOptions.getState().columnOrder).toEqual(["subject", "date", "author", "hash"]);
@@ -179,6 +179,132 @@ describe("log controls", () => {
},
);
it("Commit's left divider is header-only, resizes its left neighbour, and is inert when first", async () => {
// Commit leads by default: its left divider exists but cannot be dragged.
useLogOptions.setState({ showColumnHeaders: true, columnOrder: ["author", "date"] });
render(<LogView />);
const commitBorder = await screen.findByRole("separator", { name: "Commit column border" });
expect(commitBorder.tabIndex).toBe(-1);
expect(useLogOptions.getState().columnWidths.author).toBeUndefined();
// Data rows have no Commit divider.
expect(document.querySelector('[role="option"] [class*="colSubject"] [class*="columnResize"]')).toBeNull();
});
it("dragging Commit's divider grows the column to its left and shrinks Commit", async () => {
// Put Hash before Commit so the divider has a left neighbour to resize.
// subject must be listed explicitly after hash, else columnSequence puts it first.
useLogOptions.setState({
showColumnHeaders: true,
showHash: true,
columnOrder: ["hash", "subject", "author", "date"],
});
render(<LogView />);
const handle = await screen.findByRole("separator", { name: "Resize Commit column" });
handle.setPointerCapture = vi.fn();
handle.hasPointerCapture = () => true;
handle.releasePointerCapture = vi.fn();
// Drag left: the divider follows the pointer, so the left neighbour (Hash)
// shrinks and Commit (flex) grows. Default Hash width is 72 -> 42.
fireEvent.pointerDown(handle, { button: 0, pointerId: 7, clientX: 100 });
fireEvent.pointerMove(handle, { pointerId: 7, clientX: 70 });
fireEvent.pointerUp(handle, { pointerId: 7, clientX: 70 });
expect(useLogOptions.getState().columnWidths.hash).toBe(42); // 72 - 30
});
it("hides column dividers by default and shows them via the option", async () => {
useLogOptions.setState({ showColumnHeaders: true, showColumnDividers: false });
const { rerender } = render(<LogView />);
await screen.findByRole("separator", { name: "Resize Author column" });
const sep = screen.getByRole("separator", { name: "Resize Author column" });
// Hit strip and cursor stay active, but no rule is painted by default.
expect(sep.className).toMatch(/columnResize/);
expect(sep.closest('[class*="showDividers"]')).toBeNull();
act(() => useLogOptions.setState({ showColumnDividers: true }));
rerender(<LogView />);
expect(
screen.getByRole("separator", { name: "Resize Author column" }).closest('[class*="showDividers"]'),
).not.toBeNull();
});
it("hides a column from the header context menu", async () => {
useLogOptions.setState({ showColumnHeaders: true });
render(
<>
<LogView />
<ContextMenuHost />
</>,
);
const author = document.querySelector<HTMLElement>('[data-log-column="author"]')!;
fireEvent.contextMenu(author, { bubbles: true, clientX: 10, clientY: 10 });
fireEvent.click(await screen.findByRole("menuitem", { name: "Hide Column" }));
expect(useLogOptions.getState().showAuthor).toBe(false);
});
it("exposes a full-height column divider on data rows", async () => {
useLogOptions.setState({ showColumnHeaders: true });
render(<LogView />);
await screen.findByRole("separator", { name: "Resize Author column" });
const header = screen.getByRole("separator", { name: "Resize Author column" });
expect(header.className).toMatch(/columnResize/);
// Data rows carry the same strips so the divider — and its visible rule —
// spans the whole table height, not just the header.
const rowStrips = [...document.querySelectorAll<HTMLElement>('[role="option"] [class*="columnResize"]')];
expect(rowStrips.length).toBeGreaterThan(0);
for (const strip of rowStrips) {
expect(strip.getAttribute("aria-hidden")).toBe("true");
expect(strip.className).toMatch(/columnResize/);
}
});
it("resizes from a data-row strip and auto-fits on double-click", async () => {
useLogOptions.setState({ showColumnHeaders: true });
render(<LogView />);
await screen.findByRole("separator", { name: "Resize Author column" });
const rows = within(screen.getByRole("listbox", { name: "Commits" })).getAllByRole("option");
const rowStrip = rows[0]!.querySelector<HTMLElement>('[class*="columnResize"]')!;
const release = vi.fn();
rowStrip.setPointerCapture = vi.fn();
rowStrip.hasPointerCapture = () => true;
rowStrip.releasePointerCapture = release;
// The strip is on the column's left edge: drag left -> wider.
fireEvent.pointerDown(rowStrip, { button: 0, pointerId: 5, clientX: 40 });
fireEvent.pointerMove(rowStrip, { pointerId: 5, clientX: 10 });
fireEvent.pointerUp(rowStrip, { pointerId: 5, clientX: 10 });
const resized = useLogOptions.getState().columnWidths.author;
expect(resized).toBe(160);
expect(release).toHaveBeenCalledWith(5);
// Double-clicking the header divider drops the custom width so the column auto-fits.
const header = screen.getByRole("separator", { name: "Resize Author column" });
fireEvent.doubleClick(header);
expect(useLogOptions.getState().columnWidths.author).toBeUndefined();
});
it("a divider resizes only the two adjacent columns, not the whole table", async () => {
// Signature sits between Author and Date. Dragging the Date divider must
// widen Date and narrow Signature only — Author and Commit stay put.
useLogOptions.setState({
showColumnHeaders: true,
showSignature: true,
showDate: true,
columnOrder: ["author", "signature", "date"],
});
render(<LogView />);
const date = await screen.findByRole("separator", { name: "Resize Date column" });
date.setPointerCapture = vi.fn();
date.hasPointerCapture = () => true;
date.releasePointerCapture = vi.fn();
fireEvent.pointerDown(date, { button: 0, pointerId: 6, clientX: 100 });
fireEvent.pointerMove(date, { pointerId: 6, clientX: 60 });
fireEvent.pointerUp(date, { pointerId: 6, clientX: 60 });
const widths = useLogOptions.getState().columnWidths;
expect(widths.date).toBe(180); // 140 + 40
expect(widths.signature).toBe(60); // 100 - 40
expect(widths.author).toBeUndefined(); // untouched
expect(widths.subject).toBeUndefined(); // flexible column untouched
});
it("keeps pointer resizing separate from reordering and releases its capture on blur", async () => {
useLogOptions.setState({ showColumnHeaders: true });
render(<LogView />);
@@ -187,8 +313,8 @@ describe("log controls", () => {
author.setPointerCapture = vi.fn();
author.hasPointerCapture = () => true;
author.releasePointerCapture = release;
fireEvent.pointerDown(author, { button: 0, pointerId: 1, clientX: 10 });
fireEvent.pointerMove(author, { pointerId: 1, clientX: 40 });
fireEvent.pointerDown(author, { button: 0, pointerId: 1, clientX: 40 });
fireEvent.pointerMove(author, { pointerId: 1, clientX: 10 });
expect(useLogOptions.getState().columnWidths.author).toBe(160);
fireEvent.blur(window);
expect(release).toHaveBeenCalledWith(1);
+55 -70
Переглянути файл
@@ -1,12 +1,14 @@
import { tx } from "@/platform/i18n";
import { lockDragCursor, showContextMenu } from "@/ui";
import { showContextMenu } from "@/ui";
import clsx from "clsx";
import { useCallback, useEffect, useRef, useState } from "react";
import styles from "../GitLog.module.css";
import { logOptions, type LogOptions } from "../logOptions";
import { type LogOptions } from "../logOptions";
import { updateLogOptions } from "../logStore";
import { useVcs } from "../store";
import { ColumnResizeHandle } from "./ColumnResizeHandle";
import { SUBJECT_COLUMN, columnSequence, type LogColumn } from "./shared";
import { columnPrev, resetColumnWidth, type ResizeTarget } from "./useColumnResize";
interface ColumnDrag {
id: string;
@@ -14,6 +16,16 @@ interface ColumnDrag {
after: boolean;
}
/** Fixed columns that can be hidden from the header context menu. */
const HIDDEN_COLUMN_OPTION: Record<string, keyof LogOptions> = {
author: "showAuthor",
date: "showDate",
hash: "showHash",
signature: "showSignature",
"github-checks": "showGitHubChecks",
repository: "showRepository",
};
export function ColumnHeaders({
columns,
options,
@@ -35,7 +47,10 @@ export function ColumnHeaders({
};
const visibleIds = ids.filter((id) => id === SUBJECT_COLUMN.id || columns.some((column) => column.id === id));
return (
<div className={clsx(styles.row, styles.columnHeader)} style={{ minWidth }}>
<div
className={clsx(styles.row, styles.columnHeader, options.showColumnDividers && styles.showDividers)}
style={{ minWidth }}
>
{options.showRepository && useVcs.getState().roots.length > 1 && (
<span className={styles.colRepository}>{tx("Repository")}</span>
)}
@@ -49,6 +64,7 @@ export function ColumnHeaders({
subject={cid === SUBJECT_COLUMN.id}
ids={visibleIds}
options={options}
columns={columns}
drag={drag}
onMove={move}
onDragOver={(id, target, after) =>
@@ -69,6 +85,7 @@ function LogColumnHeader({
subject,
ids,
options,
columns,
drag,
onMove,
onDragOver,
@@ -78,6 +95,7 @@ function LogColumnHeader({
subject?: boolean;
ids: string[];
options: LogOptions;
columns: LogColumn[];
drag: ColumnDrag | null;
onMove(source: string, target: string | null, after: boolean): void;
onDragOver(id: string, target: string | null, after: boolean): void;
@@ -90,26 +108,16 @@ function LogColumnHeader({
element: HTMLElement;
pointerId: number;
} | null>(null);
const resizeDrag = useRef<{
x: number;
width: number;
element: HTMLElement;
pointerId: number;
releaseCursor: () => void;
} | null>(null);
const cancel = useCallback(() => {
const captures = [press.current, resizeDrag.current];
const capture = press.current;
press.current = null;
resizeDrag.current?.releaseCursor();
resizeDrag.current = null;
for (const capture of captures)
if (capture?.element.hasPointerCapture?.(capture.pointerId))
capture.element.releasePointerCapture(capture.pointerId);
if (capture?.element.hasPointerCapture?.(capture.pointerId))
capture.element.releasePointerCapture(capture.pointerId);
onDragCancel();
}, [onDragCancel]);
useEffect(() => {
const escape = (e: globalThis.KeyboardEvent) => {
if (e.key !== "Escape" || (!press.current && !resizeDrag.current)) return;
if (e.key !== "Escape" || !press.current) return;
e.preventDefault();
e.stopPropagation();
cancel();
@@ -123,11 +131,15 @@ function LogColumnHeader({
};
}, [cancel]);
const width = options.columnWidths[column.id] ?? column.width ?? 120;
const resize = (value: number) =>
updateLogOptions({
columnWidths: { ...logOptions().columnWidths, [column.id]: Math.max(40, Math.min(800, value)) },
});
const resizeTarget: ResizeTarget = {
id: column.id,
width,
...columnPrev(ids, column.id, options, columns),
// Commit is flex:1 — dragging its left divider only resizes the left neighbour.
leftOnly: subject || undefined,
};
const index = ids.indexOf(column.id);
const isFirst = index === 0;
const hitColumn = (x: number, y: number) => {
const el = document.elementFromPoint(x, y)?.closest?.("[data-log-column]");
if (!el || el.parentElement !== press.current?.element.parentElement) return null;
@@ -183,59 +195,32 @@ function LogColumnHeader({
disabled: index === ids.length - 1,
run: () => onMove(column.id, ids[index + 1] ?? null, true),
},
...(subject ? [] : [{ label: "Reset Width", run: () => resize(column.width ?? 120) }]),
...(subject
? []
: [
{ label: "Reset Width", run: () => resetColumnWidth(column.id) },
{ kind: "separator" as const },
{
label: tx("Hide Column"),
run: () => {
const key = HIDDEN_COLUMN_OPTION[column.id];
if (key) updateLogOptions({ [key]: false });
},
},
]),
]);
}}
>
{tx(column.title)}
{!subject && (
<span
className={styles.columnResize}
role="separator"
aria-orientation="vertical"
aria-label={tx`Resize ${tx(column.title)} column`}
aria-valuemin={40}
aria-valuemax={800}
aria-valuenow={width}
tabIndex={0}
onPointerDown={(e) => {
if (e.button !== 0) return;
e.preventDefault();
e.stopPropagation();
resizeDrag.current = {
x: e.clientX,
width,
element: e.currentTarget,
pointerId: e.pointerId,
releaseCursor: lockDragCursor("ew-resize"),
};
e.currentTarget.setPointerCapture(e.pointerId);
}}
onPointerMove={(e) => {
if (resizeDrag.current && e.currentTarget.hasPointerCapture(e.pointerId))
resize(resizeDrag.current.width + e.clientX - resizeDrag.current.x);
}}
onPointerUp={(e) => {
resizeDrag.current?.releaseCursor();
resizeDrag.current = null;
if (e.currentTarget.hasPointerCapture(e.pointerId)) e.currentTarget.releasePointerCapture(e.pointerId);
}}
onPointerCancel={() => {
resizeDrag.current?.releaseCursor();
resizeDrag.current = null;
}}
onLostPointerCapture={() => {
resizeDrag.current?.releaseCursor();
resizeDrag.current = null;
}}
onKeyDown={(e) => {
if (e.key !== "ArrowLeft" && e.key !== "ArrowRight") return;
e.preventDefault();
e.stopPropagation();
if (e.altKey)
onMove(column.id, ids[index + (e.key === "ArrowLeft" ? -1 : 1)] ?? null, e.key === "ArrowRight");
else resize(width + (e.key === "ArrowLeft" ? -10 : 10));
}}
{subject ? (
// Commit's left divider exists only in the header. It is decorative when
// Commit is the first column; otherwise it resizes the neighbour on its left.
<ColumnResizeHandle target={resizeTarget} title={column.title} disabled={isFirst} />
) : (
<ColumnResizeHandle
target={resizeTarget}
title={column.title}
onReorder={(delta) => onMove(column.id, ids[index + delta] ?? null, delta === 1)}
/>
)}
</span>
+49
Переглянути файл
@@ -0,0 +1,49 @@
import { tx } from "@/platform/i18n";
import clsx from "clsx";
import styles from "../GitLog.module.css";
import { resizeColumnPair, useColumnResize, type ResizeTarget } from "./useColumnResize";
/**
* Column divider on the column's left edge. A visible rule marks the grab target;
* hovering brightens it. Keyboard users get a focusable separator whose Left/Right
* arrows resize the adjacent pair (Alt+Left/Right reorders, header only).
*
* `disabled` renders the rule without any resize interaction — used for the
* first column's left border, which has no neighbour to give/take space.
*/
export function ColumnResizeHandle({
target,
title,
onReorder,
disabled,
}: {
target: ResizeTarget;
title: string;
onReorder?: (delta: number) => void;
disabled?: boolean;
}) {
const resize = useColumnResize(target);
return (
<span
className={clsx(styles.columnResize, disabled && styles.columnResizeDisabled)}
role="separator"
aria-orientation="vertical"
aria-label={disabled ? tx`${tx(title)} column border` : tx`Resize ${tx(title)} column`}
aria-valuemin={40}
aria-valuemax={800}
aria-valuenow={target.width}
tabIndex={disabled ? -1 : 0}
{...(disabled ? {} : resize)}
onKeyDown={(e) => {
if (disabled || (e.key !== "ArrowLeft" && e.key !== "ArrowRight")) return;
e.preventDefault();
e.stopPropagation();
const delta = e.key === "ArrowLeft" ? -1 : 1;
if (e.altKey && onReorder) onReorder(delta);
// Handle is on the left edge: Left arrow widens this column.
// resizeColumnPair takes positive = widen, so invert the arrow delta.
else resizeColumnPair(target, -delta * 10);
}}
/>
);
}
+12 -3
Переглянути файл
@@ -11,8 +11,10 @@ import { commitKey, commitRepo } from "../multiRoot";
import { repoName, useVcs } from "../store";
import { CommitMessage, RefLabels } from "./CommitMessage";
import { GraphCell } from "./GraphCell";
import { RowResizeHandle } from "./RowResizeHandle";
import { commitMenu } from "./commitMenu";
import { SUBJECT_COLUMN, columnSequence, type LogColumn } from "./shared";
import { columnPrev } from "./useColumnResize";
function CommitRowView({
id,
@@ -152,7 +154,12 @@ function CommitRowView({
id={id}
role="option"
aria-selected={selected}
className={clsx(styles.row, onBranch && styles.currentBranch, selected && styles.selected)}
className={clsx(
styles.row,
onBranch && styles.currentBranch,
selected && styles.selected,
opts.showColumnDividers && styles.showDividers,
)}
style={{ top }}
onMouseDown={(e) => {
if (e.shiftKey) e.preventDefault(); // no text selection on range clicks
@@ -168,10 +175,11 @@ function CommitRowView({
{repoName(commitRepo(c)!)}
</span>
)}
{columnSequence(opts.columnOrder, columns).map((cid) => {
{columnSequence(opts.columnOrder, columns).map((cid, _index, ids) => {
if (cid === SUBJECT_COLUMN.id) return subjectCell;
const column = columns.find((col) => col.id === cid);
if (!column) return null;
const width = opts.columnWidths[column.id] ?? column.width ?? 120;
return (
<span
key={cid}
@@ -181,10 +189,11 @@ function CommitRowView({
column.id === "author" && mine && styles.mine,
column.id === "hash" && styles.hash,
)}
style={{ width: opts.columnWidths[column.id] ?? column.width ?? 120 }}
style={{ width }}
title={column.id === "author" ? `${c.author} <${c.email}>` : undefined}
>
{column.render(c)}
<RowResizeHandle target={{ id: column.id, width, ...columnPrev(ids, column.id, opts, columns) }} />
</span>
);
})}
+1
Переглянути файл
@@ -491,6 +491,7 @@ export function viewOptionsMenu(o: LogOptions): MenuItem[] {
toggle("GitHub Commit Checks", o, "showGitHubChecks"),
{ kind: "separator" },
toggle("Column Headers", o, "showColumnHeaders"),
toggle("Column Dividers", o, "showColumnDividers"),
],
},
{ kind: "separator" },
+9
Переглянути файл
@@ -0,0 +1,9 @@
import clsx from "clsx";
import styles from "../GitLog.module.css";
import { useColumnResize, type ResizeTarget } from "./useColumnResize";
/** Full-height resize strip on a data-row cell (IDEA's column divider). */
export function RowResizeHandle({ target }: { target: ResizeTarget }) {
const resize = useColumnResize(target);
return <span className={clsx(styles.columnResize, styles.columnResizeRow)} aria-hidden="true" {...resize} />;
}
+144
Переглянути файл
@@ -0,0 +1,144 @@
import { lockDragCursor } from "@/ui";
import {
useCallback,
useEffect,
useRef,
type MouseEvent as ReactMouseEvent,
type PointerEvent as ReactPointerEvent,
} from "react";
import { logOptions, type LogOptions } from "../logOptions";
import { updateLogOptions } from "../logStore";
import { SUBJECT_COLUMN, type LogColumn } from "./shared";
const MIN_WIDTH = 40;
const MAX_WIDTH = 800;
const clamp = (value: number) => Math.max(MIN_WIDTH, Math.min(MAX_WIDTH, value));
export type ResizeTarget = {
id: string;
width: number;
/** Column to the left of this divider, or null when this is the first column. */
prevId: string | null;
prevWidth: number;
/** True for the flexible Commit column: only the left neighbour gets a stored width. */
leftOnly?: boolean;
};
/** Resolve the column immediately left of `id` in the visible order. */
export function columnPrev(
ids: string[],
id: string,
options: LogOptions,
columns: LogColumn[],
): { prevId: string | null; prevWidth: number } {
const index = ids.indexOf(id);
const prevId = index > 0 ? ids[index - 1] : null;
// The Commit column is flex:1 and absorbs space on its own — never store a width for it.
// (When *we are* the Commit column the caller handles the left neighbour via leftOnly,
// so this guard only applies to fixed columns whose left neighbour is Commit.)
if (!prevId || (prevId === SUBJECT_COLUMN.id && id !== SUBJECT_COLUMN.id)) return { prevId: null, prevWidth: 0 };
const prev = columns.find((c) => c.id === prevId);
// subject has no fixed width of its own; its "prevWidth" is unused in leftOnly mode.
return { prevId, prevWidth: options.columnWidths[prevId] ?? prev?.width ?? 120 };
}
/**
* Resize the divider between `id` (right) and `prevId` (left): only these two
* columns give/take space, so every other column stays put. When the left neighbour
* is the flexible Commit column, only the right column's width is stored (Commit
* absorbs the rest through flex:1).
*/
export function resizeColumnPair(target: ResizeTarget, delta: number) {
const { id, width, prevId, prevWidth, leftOnly } = target;
const widths = { ...logOptions().columnWidths };
if (prevId == null) {
// First column with no left neighbour (should be non-resizable at the UI layer).
widths[id] = clamp(width + delta);
} else if (leftOnly) {
// The Commit column is flex:1. The handle sits on the boundary (the left
// neighbour's right edge), so the divider follows the pointer: dragging right
// widens the left neighbour and shrinks Commit. `delta` is already -dx, so
// subtracting it makes the neighbour track dx exactly.
widths[prevId] = clamp(prevWidth - delta);
} else {
const left = clamp(prevWidth - delta);
const given = prevWidth - left; // what the left column actually gave up
widths[id] = clamp(width + given);
widths[prevId] = left;
}
updateLogOptions({ columnWidths: widths });
}
/** IDEA's double-click-on-divider behaviour: drop the custom width so the column fits its content again. */
export function resetColumnWidth(id: string) {
const widths = { ...logOptions().columnWidths };
delete widths[id];
updateLogOptions({ columnWidths: widths });
}
type Drag = ResizeTarget & {
x: number;
element: HTMLElement;
pointerId: number;
releaseCursor: () => void;
};
/**
* Pointer-driven column resize with a full-height hit strip on the column's left
* edge. Dragging left widens the column (and narrows only its left neighbour);
* the divider follows the pointer 1:1.
*/
export function useColumnResize(target: ResizeTarget) {
const drag = useRef<Drag | null>(null);
// Listeners are attached imperatively so `cancel` is defined before it is referenced.
const listeners = useRef<{ blur: () => void; escape: (e: KeyboardEvent) => void } | null>(null);
const cancel = useCallback(() => {
const d = drag.current;
if (!d) return;
d.releaseCursor();
drag.current = null;
if (d.element.hasPointerCapture?.(d.pointerId)) d.element.releasePointerCapture(d.pointerId);
if (listeners.current) {
window.removeEventListener("blur", listeners.current.blur);
window.removeEventListener("keydown", listeners.current.escape, true);
listeners.current = null;
}
}, []);
useEffect(() => () => cancel(), [cancel]);
return {
onPointerDown: (e: ReactPointerEvent<HTMLElement>) => {
if (e.button !== 0 || drag.current) return;
// Suppress the compatibility mousedown so a data-row strip doesn't select the row.
e.preventDefault();
e.stopPropagation();
const blur = () => cancel();
const escape = (ev: KeyboardEvent) => {
if (ev.key === "Escape") cancel();
};
drag.current = {
...target,
x: e.clientX,
element: e.currentTarget,
pointerId: e.pointerId,
releaseCursor: lockDragCursor("ew-resize"),
};
listeners.current = { blur, escape };
e.currentTarget.setPointerCapture?.(e.pointerId);
window.addEventListener("blur", blur);
window.addEventListener("keydown", escape, true);
},
onPointerMove: (e: ReactPointerEvent<HTMLElement>) => {
const d = drag.current;
// Handle is on the left edge: drag left -> wider.
if (d && e.currentTarget.hasPointerCapture?.(e.pointerId)) resizeColumnPair(d, -(e.clientX - d.x));
},
onPointerUp: cancel,
onPointerCancel: cancel,
onLostPointerCapture: cancel,
onMouseDown: (e: ReactMouseEvent<HTMLElement>) => e.stopPropagation(),
onDoubleClick: (e: ReactMouseEvent<HTMLElement>) => {
e.stopPropagation();
resetColumnWidth(target.id);
},
};
}
+3
Переглянути файл
@@ -25,6 +25,8 @@ export interface LogOptions {
showGitHubChecks: boolean;
/** The row naming the columns, where they are resized and reordered. */
showColumnHeaders: boolean;
/** Draw a 1px divider on each column's left edge (off by default, like IDEA). */
showColumnDividers: boolean;
highlightMine: boolean;
highlightMerges: boolean;
highlightCurrentBranch: boolean;
@@ -63,6 +65,7 @@ export const DEFAULT_LOG_OPTIONS: LogOptions = {
showSignature: false,
showGitHubChecks: false,
showColumnHeaders: false,
showColumnDividers: false,
highlightMine: true,
highlightMerges: true,
highlightCurrentBranch: true,
+4 -1
Переглянути файл
@@ -1535,7 +1535,7 @@
"Close Agent Task": "Close Agent Task",
"Close and New Agent Task": "Close and New Agent Task",
"Focus Agent Input": "Focus Agent Input",
"Focuses the message input of the current agent task without moving the caret.": "Focuses the message input of the current agent task without moving the caret.",
"Focuses the message input of the current agent task, or of the one on screen when focus is elsewhere and no panel claims the shortcut, without moving the caret.": "Focuses the message input of the current agent task, or of the one on screen when focus is elsewhere and no panel claims the shortcut, without moving the caret.",
"Cycle Agent Effort": "Cycle Agent Effort",
"Cycles the current model's supported effort levels without changing the message.": "Cycles the current model's supported effort levels without changing the message.",
"Effort: {level}": "Effort: {level}",
@@ -2352,6 +2352,9 @@
"Search installed plugins": "Search installed plugins",
"Runs “conda create -n <name> python=<version>”: a new environment with only Python in it, in conda's envs directory; the new interpreter becomes the project interpreter.": "Runs “conda create -n <name> python=<version>”: a new environment with only Python in it, in conda's envs directory; the new interpreter becomes the project interpreter.",
"Java Agents": "Java Agents",
"Hide Column": "Hide Column",
"Column Dividers": "Column Dividers",
"{title} column border": "{title} column border",
"File at a Git revision (read-only).": "File at a Git revision (read-only).",
"Adjust colors for red-green vision deficiency is on, so this scheme shows its red-green colors.": "Adjust colors for red-green vision deficiency is on, so this scheme shows its red-green colors.",
"Appearance settings": "Appearance settings",
+5 -2
Переглянути файл
@@ -4164,7 +4164,7 @@
"Close Agent Task": "关闭 Agent 任务",
"Close and New Agent Task": "关闭并新建 Agent 任务",
"Focus Agent Input": "聚焦 Agent 输入框",
"Focuses the message input of the current agent task without moving the caret.": "聚焦当前 Agent 任务的消息输入框,不移动光标。",
"Focuses the message input of the current agent task, or of the one on screen when focus is elsewhere and no panel claims the shortcut, without moving the caret.": "聚焦当前 Agent 任务的消息输入框;焦点在其他位置且没有面板占用该快捷键时,聚焦屏幕上显示的任务的输入框。不移动光标。",
"Cycle Agent Effort": "循环切换 Agent 思考强度",
"Cycles the current model's supported effort levels without changing the message.": "循环切换当前模型支持的思考强度,不改变消息内容。",
"Effort: {level}": "思考强度:{level}",
@@ -8713,6 +8713,10 @@
"Run code inside the Java applications you start": "在你启动的 Java 应用中运行代码",
"Java agents of {list} were not added: they load only in local projects.": "未添加 {list} 的 Java 代理:Java 代理只加载到本地项目中。",
"Java agent": "Java 代理",
"Java Agents": "Java 代理",
"Hide Column": "隐藏该列",
"Column Dividers": "列分隔线",
"{title} column border": "{title}列边界",
"1 Pull Request": "1 个拉取请求",
"{count} Pull Requests": "{count} 个拉取请求",
"Issues": "议题",
@@ -8728,7 +8732,6 @@
"Session references and artifacts": "会话引用与制品",
"Copy Link": "复制链接",
"Add to Message": "添加到消息",
"Java Agents": "Java 代理",
"File at a Git revision (read-only).": "Git 修订版中的文件(只读)。",
"Adjust colors for red-green vision deficiency is on, so this scheme shows its red-green colors.": "已开启「针对红绿色觉缺陷调整颜色」,此方案显示的是红绿色觉变体的颜色。",
"Appearance settings": "外观设置",
+2
Переглянути файл
@@ -114,6 +114,7 @@ describe("Popup", () => {
);
const popup = screen.getByRole("dialog", { name: "Branches" });
expect([popup.style.width, popup.style.height]).toEqual(["400px", "300px"]);
expect(popup.hasAttribute("data-resized")).toBe(true);
// jsdom lays nothing out: the popup measures what its style says, at the origin.
popup.getBoundingClientRect = () =>
new DOMRect(0, 0, parseFloat(popup.style.width), parseFloat(popup.style.height));
@@ -136,6 +137,7 @@ describe("Popup", () => {
</Popup>,
);
expect(screen.getByRole("dialog", { name: "Menu" }).style.width).toBe("");
expect(screen.getByRole("dialog", { name: "Menu" }).hasAttribute("data-resized")).toBe(false);
expect(screen.queryByRole("separator", { name: "Resize" })).toBeNull();
});
});
+2 -1
Переглянути файл
@@ -69,7 +69,7 @@ export interface PopupProps {
resizable?: "both";
minWidth?: number;
minHeight?: number;
/** Size to open at, such as one remembered from `onResized`. */
/** Size to open at, such as one remembered from `onResized`. While a size applies the popup has `data-resized`. */
initialSize?: { w: number; h: number } | null;
/** The size a resize ended at. */
onResized?: (size: { w: number; h: number }) => void;
@@ -246,6 +246,7 @@ function PopupInner({
tabIndex={-1}
className={clsx(styles.popup, !unstyled && styles.surface, className)}
data-positioned={isPositioned || undefined}
data-resized={size ? "" : undefined}
style={{ ...floatingStyles, ...(size && { width: size.w, height: size.h }), ...style }}
>
<PopupAncestry.Provider value={ancestry}>{children}</PopupAncestry.Provider>