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

...
Автор SHA1 Повідомлення Дата
l0ng-ai 5685e060be fix(plugins): keep the annotation colour of a theme plugin's color scheme
A theme plugin's .icls mapped DEFAULT_METADATA onto the annotation colour
and ignored ANNOTATION_NAME_ATTRIBUTES, so a scheme that only changed
DEFAULT_METADATA repainted Java annotations, which take the annotation
key (Darcula's own when the file has none).
2026-11-26 18:20:31 +08:00
l0ng-ai 08aef06844 fix(java): skip a jdtls on PATH that runs java -jar itself (#6155)
A hand-written jdtls that starts the Equinox launcher with java -jar (opencode puts
one into a JDK's bin) knows none of the release script's options: every --jvm-arg,
the Lombok agent among them, reached jdtls as an application argument, and its own
-data came before the IDE's workspace. When the first jdtls on PATH is such a
wrapper, the next one that isn't is started instead, else the IDE's own install,
which is offered for install while missing.

Fixes #6062
2026-11-26 18:17:04 +08:00
a1oyssтаa1oyss 3d5ec8a147 fix(vcs): show a deleted file's diff with the editor's own line numbers (#6146)
The one-side viewer of a deleted file drew the deleted rows as block widgets over an
empty document, so the gutter numbered nothing but a stray 1 on the phantom line and
the rows had no context menu. A deleted file's one-sided diff now swaps its sides as a
staged deletion already did: the original text is the document and the absent side is
the diff's original, so the editor's own gutter, colours and context menu apply.
The header keeps the request's order (revision -> (deleted)).

Fixes #6145

Co-authored-by: a1oyss <[email protected]>
2026-11-26 18:11:58 +08:00
l0ng-ai 0f14314156 feat(debugger): enhanced class redefinition for Java debug sessions (#6148)
Application and Spring Boot configurations get an "Enhanced class redefinition" option. When debugging on JetBrains Runtime, the JVM starts with -XX:+AllowEnhancedClassRedefinition, so Reload Changed Classes can also apply structural changes such as added or removed methods and fields. On any other JDK (or one that can't be identified) the session starts without the flag, which those JVMs reject, and the Debug console says why. Run is unchanged.

When the JVM refuses a structural change and the session's configuration has the option off, the Hot Swap failure says how to allow such changes.

Refs #4007
2026-11-26 18:05:55 +08:00
txdywmwddhxs 2413cc4b43 fix(editor): preserve C++ namespace colors for library symbols (#6133)
clangd marks std and other standard-library namespaces with the defaultLibrary modifier, so the generic builtin (Predefined symbol) class overrode the Namespace colour. A C++ semantic hook drops the builtin class for namespace tokens only; other symbol kinds, modifiers and languages keep their styling.

Fixes #6123

Co-authored-by: txdywmwddhxs <[email protected]>
2026-11-26 18:02:58 +08:00
l0ng-ai 30291971e1 fix(remote): offer to stop another build's backend that keeps a project (#6147)
A remote daemon of another build refuses to retire while it has terminals, runs, agent sessions or unsaved changes. After an upgrade left such a daemon (its binary gone, so no build can reconnect to it), the project could not be opened and the error only asked to reconnect with the old build.

The refusal now comes back as RemoteBackendBusy and the window asks whether to stop that backend. Agreeing reconnects with `openidea-server --attach <path> --replace`, which sends the old daemon SIGTERM (its own shutdown), kills it after the shutdown timeout if needed, and starts this build's daemon. Works for SSH hosts, WSL and dev containers, and for daemons of earlier builds (found by their --daemon command line).

Fixes #6119
2026-11-26 18:00:44 +08:00
l0ng-ai 9f3d75976f fix(debugger): send each window's breakpoints only to its own sessions (#6138)
The backend kept one breakpoint table for the whole app and sent all of it to every new session. A file whose removal never reached that table (a reloaded window, or the same file recorded under another path) stayed there and was sent to every later session, so a deleted line breakpoint kept suspending the program until restart; one window's breakpoints also reached another window's sessions.

Line, method and field breakpoints are now kept per window (the session owner) and sent only to that window's sessions; a closing window drops its lists. When a window loads its project and right before each session starts, it hands its whole list to the backend (debug_replace_breakpoints), which clears the files it no longer lists in the table and in the window's live sessions.

Fixes #6116
2026-11-26 17:39:11 +08:00
l0ng-ai 72d9aad715 fix(database): complete every table of a large default schema (#6136)
SQL completion read the columns of every non-system schema in one query capped at 50,000 rows, ordered by schema and table. A schema with more columns than that (5,000+ Oracle tables) lost the columns of the tables sorting last, so they were neither completed nor resolved in the console.

completion_columns now takes a CompletionScope: the default schema is read in its own query without the shared cap, and the other schemas keep sharing it. Applies to every driver with a completion query. A PostgreSQL integration test with 52,000 columns in the default schema covers it.

Fixes #6118
2026-11-26 17:32:05 +08:00
l0ng-ai 7264e7d66d test(database): check the shown values in the numeric filter e2e (#6134)
Since #6067 a column's local filter shows the checked values instead of hiding them, so the precise-filter case of databaseNumericSort.spec.ts failed on main and on every PR's E2E leg. The spec now checks the three values it expects to see.
2026-11-26 17:25:54 +08:00
l0ng-ai 10379a54f7 fix(diff): prevent wheel scroll jump-back loop in WebKit (#6115)
Wheel-scrolling a diff in WebKit could jump scrollTop backwards and loop, so the bottom was unreachable.

- collapsedDiffLines replaced the separator row's children synchronously in docViewUpdate, before layout flushed; WebKit then clamped scrollTop back whenever a collapsed-lines separator entered the viewport. The replacement now runs in a keyed requestMeasure write phase.
- In synchronized side-by-side diffs (PaddedPanes / UnalignedPanes), the follower's measure-driven scrollTop adjustments were read as user scrolls and followed in reverse. The wheeled pane now leads for 150 ms after its last wheel event (released on pointerdown), and non-document height changes refresh the expected echo offsets.

Covers the split aligned, split unaligned and unified views.
2026-11-26 17:24:35 +08:00
LU XIANGRUIтаwildcatDownstairs 6564b9e6cb fix(vcs): resize the Repository column from log rows when Commit is first (#6125)
In a multi-root Git Log with column headers hidden (the default) and Commit as the first column (the default), nothing on a data row sat on the Repository/Commit boundary: only fixed columns draw a row resize strip, and the Repository column has no divider of its own. A leading Commit cell now carries the same strip as the header's Commit divider and resizes only the Repository column.

Fixes #6111

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-26 17:16:20 +08:00
l0ng-ai d437cd46f5 fix(settings): keep the annotation colour of imported color schemes (#6130)
Importing a color scheme mapped only DEFAULT_METADATA to the annotation colour. Java annotations use ANNOTATION_NAME_ATTRIBUTES, which the bundled Default and Darcula schemes set themselves, so a scheme based on them that only changes DEFAULT_METADATA lost its annotation colour on import. The importer now reads ANNOTATION_NAME_ATTRIBUTES ahead of DEFAULT_METADATA, applies the parent's value when a Default- or Darcula-based file leaves it out, and exports the colour under that key.

Fixes #6108
2026-11-26 17:08:47 +08:00
langxpтаkradme 925d474274 fix(app): resume interrupted update downloads (#5377)
An interrupted update download started again from zero on the next attempt. The update is now downloaded to a .part checkpoint in the app cache, keyed by version, target and signature so the GitHub and CNB sources share it, and later attempts resume it with an HTTP Range request. A 200 answer or a mismatched range replaces the checkpoint safely (the old bytes stay until the new download completes), a 416 for an already complete file is accepted, and the package is verified against its signature before installing; a resumed file that fails verification is discarded and downloaded again. Check and verification are cancellable, and obsolete checkpoints are removed.

Co-authored-by: kradme <[email protected]>
2026-11-26 17:03:02 +08:00
LU XIANGRUIтаwildcatDownstairs 89463afc18 fix(updates): show release notes on What's New after a Windows update (#6058)
After an in-app update on Windows, What's New always said the version had no release notes. The Windows installer ends the app inside appInstallUpdate, so the notes recorded after the call returned were never stored, and the fallback manifest read app_release_notes was trusted-only, which the project-less window the page opens in is refused. The notes are now recorded before the install starts and restored if the install fails or is cancelled, and app_release_notes is always allowed, like the update check: it reads only the public manifest.

Closes #6056

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-26 16:57:59 +08:00
Akbar Husainтаakbar1214 c884aa4cc6 fix(updates): cap updater connects so an unreachable CDN IP falls back (#5070)
The updater's HTTP client had no connect timeout, so an unreachable first address of the release CDN hostname held the update check until its 60 s deadline instead of falling through to the next address. The client now bounds connection setup (TCP and TLS) to 15 s, which reqwest divides across the resolved addresses.

Co-authored-by: akbar1214 <[email protected]>
2026-11-26 16:55:54 +08:00
Void Et Noxтаvoidetnox 09108e02e3 ci(release): publish the Homebrew cask to l0ng-ai/homebrew-tap (#5883)
After a stable release is published, a new homebrew job downloads both macOS DMGs, writes Casks/openidea.rb (per-arch SHA-256, auto_updates true so the in-app updater and brew upgrade don't fight, the openidea CLI as a binary, zap paths) and pushes it to l0ng-ai/homebrew-tap. It is skipped for prereleases and when HOMEBREW_TAP_TOKEN is unset, and can be run by hand for an existing tag. The README documents brew install --cask l0ng-ai/tap/openidea.

Co-authored-by: voidetnox <[email protected]>
2026-11-26 16:51:45 +08:00
Vladislav Kuzminтаprincipalwater 2b6ca90457 fix(ci): cache Maven plugins for Java build tests (#5966)
The Java build integration tests resolved maven-resources-plugin and maven-compiler-plugin from Maven Central on every run and failed when Central rate-limited the download. On GitHub-hosted runners CI now restores a dedicated local repository from cache, prepares it once with the shared jbuild-maven fixture (retrying 0/10/30 s, 5 minute limit) and saves it only after a successful preparation; both test crates use the same fixture POMs, so the cached plugins are the ones the tests need.

Closes #5964

Co-authored-by: principalwater <[email protected]>
2026-11-26 16:50:53 +08:00
audichuang 3c3681ef2b fix(clipboard): read the macOS clipboard natively for menu paste, without WebKit's Paste callout (#6061)
On macOS, WebKit asks the user to confirm execCommand("paste") and navigator.clipboard reads outside a paste event with a "Paste" callout. readClipboardPlainText fell back to navigator.clipboard.readText() whenever the native read found no text, and the terminal's menu Paste called execCommand("paste") and navigator.clipboard.read() before reading natively. On macOS a null from clipboard_text now means empty text (a refused command still falls back), and in the desktop app the terminal menu Paste reads files, text and images through the backend commands.

Co-authored-by: audichuang <[email protected]>
2026-11-26 16:42:19 +08:00
audichuang b0d7bfef24 fix(vcs): History for Selection no longer lists Local Changes when the newest commit is a merge (#6034)
History for Selection listed a Local Changes row on a clean file whenever the newest commit touching the selected lines was a merge: the list compared the current lines with the newest row's `after` block, and `git log -L` prints no patch for a merge, so that block was empty. The backend now returns HEAD's block (`BlockHistory.head`) and the list compares against it, falling back to the newest row for servers that predate the field.

Co-authored-by: audichuang <[email protected]>
2026-11-26 16:35:31 +08:00
l0ng-ai 527add030a fix(clipboard): read CF_UNICODETEXT pairs with as_chunks (#6126)
Clippy 1.100 adds chunks_exact_to_as_chunks, which failed the workspace clippy run on every PR. unicode_text now reads the UTF-16LE pairs of a CF_UNICODETEXT block with as_chunks::<2>(); behaviour is unchanged.
2026-11-26 16:32:29 +08:00
l0ng-ai 81c2fc9ace fix(vcs): scroll the changes tree horizontally instead of clipping rows (#6121)
Rows in the Commit and Local Changes trees were locked to the pane width and ellipsized, so the end of a long file name and its directory path could only be read by widening the tool window. The tree now keeps rows at their natural width and scrolls horizontally, as the Project view does.

Fixes #6080
2026-11-26 16:10:22 +08:00
101 змінених файлів з 2768 додано та 292 видалено

No files matched your search

+38
Переглянути файл
@@ -156,6 +156,44 @@ jobs:
- run: cargo clippy --workspace --all-targets -- -D warnings
# Test fixtures write LF files; keep Git from converting them on checkout.
- run: git config --global core.autocrlf false
- name: Restore Maven artifacts for Java build tests
id: jbuild-maven-cache
if: runner.environment == 'github-hosted'
uses: actions/cache/restore@v5
with:
path: ${{ runner.temp }}/jbuild-maven-repository
key: jbuild-maven-${{ runner.os }}-${{ hashFiles('crates/ide-build/tests/fixtures/jbuild-maven/**/pom.xml') }}
- name: Prepare Maven artifacts for Java build tests
id: jbuild-maven
if: runner.environment == 'github-hosted'
timeout-minutes: 5
shell: bash
env:
CACHE_HIT: ${{ steps.jbuild-maven-cache.outputs.cache-hit }}
run: |
if [[ -z "${JAVA_HOME:-}" || ! -d "$JAVA_HOME/bin" ]] || ! command -v mvn >/dev/null; then
exit 0
fi
export MAVEN_OPTS="${MAVEN_OPTS:+$MAVEN_OPTS }-Dmaven.repo.local=$RUNNER_TEMP/jbuild-maven-repository"
echo "MAVEN_OPTS=$MAVEN_OPTS" >> "$GITHUB_ENV"
if [[ "$CACHE_HIT" == true ]]; then
exit 0
fi
# The IDE also reads the compiler plugin descriptor when it builds the Maven model.
for delay in 0 10 30; do
sleep "$delay"
if mvn -B -ntp -U -N -f crates/ide-build/tests/fixtures/jbuild-maven/pom.xml resources:resources compiler:compile; then
echo "prepared=true" >> "$GITHUB_OUTPUT"
exit 0
fi
done
exit 1
- name: Save Maven artifacts for Java build tests
if: steps.jbuild-maven.outputs.prepared == 'true'
uses: actions/cache/save@v5
with:
path: ${{ runner.temp }}/jbuild-maven-repository
key: ${{ steps.jbuild-maven-cache.outputs.cache-primary-key }}
- run: cargo nextest run --workspace --no-fail-fast
- name: Remote backend with Docker Compose
# Self-hosted runner containers do not mount /var/run/docker.sock (scripts/selfhost-runner/README.md).
+73
Переглянути файл
@@ -0,0 +1,73 @@
name: Homebrew
# Updates the cask in the project tap, l0ng-ai/homebrew-tap (scripts/homebrew-cask.ts), so
# `brew install --cask l0ng-ai/tap/openidea` installs the new release. Release runs it after
# publishing; run it by hand to write the cask of an existing tag again. Skipped for prereleases
# and without the HOMEBREW_TAP_TOKEN secret (contents: write on l0ng-ai/homebrew-tap).
on:
workflow_call:
inputs:
tag: { type: string, required: true }
workflow_dispatch:
inputs:
tag:
description: "Published stable release to write the cask for (e.g. v0.1.51)"
required: true
permissions:
contents: read
concurrency:
group: homebrew-tap
jobs:
cask:
runs-on: ubuntu-latest
timeout-minutes: 30
env:
TAG: ${{ inputs.tag }}
TAP: l0ng-ai/homebrew-tap
HOMEBREW_TAP_TOKEN: ${{ secrets.HOMEBREW_TAP_TOKEN }}
GH_TOKEN: ${{ github.token }}
steps:
- name: Check tag and token
id: check
run: |
if [[ ! "$TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
echo "::notice::$TAG is not a stable release: the cask stays as is"
echo "skip=true" >> "$GITHUB_OUTPUT"
elif [ -z "$HOMEBREW_TAP_TOKEN" ]; then
echo "::notice::HOMEBREW_TAP_TOKEN unset: not updating the cask for $TAG"
echo "skip=true" >> "$GITHUB_OUTPUT"
fi
- uses: actions/checkout@v5
if: steps.check.outputs.skip != 'true'
with: { sparse-checkout: scripts }
- uses: actions/checkout@v5
if: steps.check.outputs.skip != 'true'
with:
repository: ${{ env.TAP }}
token: ${{ secrets.HOMEBREW_TAP_TOKEN }}
path: tap
- uses: actions/setup-node@v5
if: steps.check.outputs.skip != 'true'
with: { node-version: 22 }
- name: Download DMGs
if: steps.check.outputs.skip != 'true'
run: gh release download "$TAG" -R "$GITHUB_REPOSITORY" -p '*.dmg' -D assets
- name: Write the cask
if: steps.check.outputs.skip != 'true'
run: node scripts/homebrew-cask.ts "$TAG" assets tap/Casks/openidea.rb
- name: Push to the tap
if: steps.check.outputs.skip != 'true'
working-directory: tap
run: |
git add Casks/openidea.rb
if git diff --cached --quiet; then
echo "the cask is already at ${TAG#v}"
exit 0
fi
git config user.name "github-actions[bot]"
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
git commit -m "openidea ${TAG#v}"
git push
+7
Переглянути файл
@@ -178,3 +178,10 @@ jobs:
uses: ./.github/workflows/cnb-mirror.yml
with: { tag: "${{ github.event.inputs.tag || github.ref_name }}" }
secrets: inherit
# The cask in l0ng-ai/homebrew-tap; skipped for prereleases and without HOMEBREW_TAP_TOKEN.
homebrew:
needs: publish
uses: ./.github/workflows/homebrew.yml
with: { tag: "${{ github.event.inputs.tag || github.ref_name }}" }
secrets: inherit
Створено
+1
Переглянути файл
@@ -6745,6 +6745,7 @@ dependencies = [
"objc2-web-kit 0.3.2",
"parking_lot",
"percent-encoding",
"reqwest",
"security-framework",
"serde",
"serde_json",
+6
Переглянути файл
@@ -33,6 +33,12 @@ its search-everything habits — to a native app with a Rust core.
Editor, code insight, debugger, Git, terminal, database and HTTP clients,
for 60+ languages. Builds for macOS, Windows and Linux.
On macOS you can also install it with Homebrew:
```bash
brew install --cask l0ng-ai/tap/openidea
```
## Benchmark
Opening [freqtrade](https://github.com/freqtrade/freqtrade) (Python, ~770 files)
+6
Переглянути файл
@@ -33,6 +33,12 @@ her şeyi arama alışkanlığını) çekirdeği Rust ile yazılmış yerel bir
Editör, kod analizi, hata ayıklayıcı (debugger), Git, terminal, veritabanı ve HTTP istemcileri;
60'tan fazla dil için. macOS, Windows ve Linux sürümleri var.
macOS'ta Homebrew ile de kurabilirsiniz:
```bash
brew install --cask l0ng-ai/tap/openidea
```
## Performans karşılaştırması
[freqtrade](https://github.com/freqtrade/freqtrade) projesini (Python, ~770 dosya)
+6
Переглянути файл
@@ -35,6 +35,12 @@ OpenIDEA 把 IntelliJ IDEA 的使用方式(快捷键、工具窗口、随处
编辑器、代码洞察、调试器、Git、终端、数据库客户端和 HTTP 客户端,支持 60 多种语言。
提供 macOS、Windows 和 Linux 版本。
在 macOS 上也可以用 Homebrew 安装:
```bash
brew install --cask l0ng-ai/tap/openidea
```
## 性能对比
在缓存已预热的情况下打开 [freqtrade](https://github.com/freqtrade/freqtrade)(Python,约 770 个文件),
+3 -9
Переглянути файл
@@ -18,15 +18,9 @@ fn tools() -> Option<(PathBuf, PathBuf)> {
Some((home, mvn))
}
const ROOT_POM: &str = r#"<project><modelVersion>4.0.0</modelVersion><groupId>t</groupId><artifactId>root</artifactId><version>1</version><packaging>pom</packaging>
<modules><module>lib</module><module>app</module></modules>
<properties><maven.compiler.release>11</maven.compiler.release><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties>
<build><pluginManagement><plugins><plugin><artifactId>maven-compiler-plugin</artifactId><version>3.13.0</version>
<configuration><parameters>true</parameters></configuration></plugin></plugins></pluginManagement></build></project>"#;
const LIB_POM: &str = r#"<project><modelVersion>4.0.0</modelVersion><parent><groupId>t</groupId><artifactId>root</artifactId><version>1</version></parent><artifactId>lib</artifactId></project>"#;
const APP_POM: &str = r#"<project><modelVersion>4.0.0</modelVersion><parent><groupId>t</groupId><artifactId>root</artifactId><version>1</version></parent><artifactId>app</artifactId>
<dependencies><dependency><groupId>t</groupId><artifactId>lib</artifactId><version>1</version></dependency></dependencies>
<build><resources><resource><directory>src/main/resources</directory><filtering>true</filtering></resource></resources></build></project>"#;
const ROOT_POM: &str = include_str!("../../tests/fixtures/jbuild-maven/pom.xml");
const LIB_POM: &str = include_str!("../../tests/fixtures/jbuild-maven/lib/pom.xml");
const APP_POM: &str = include_str!("../../tests/fixtures/jbuild-maven/app/pom.xml");
/// A `lib` ← `app` reactor built by the IDE's Java build with a real Maven and JDK.
struct Fixture {
+24
Переглянути файл
@@ -0,0 +1,24 @@
<project>
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>t</groupId>
<artifactId>root</artifactId>
<version>1</version>
</parent>
<artifactId>app</artifactId>
<dependencies>
<dependency>
<groupId>t</groupId>
<artifactId>lib</artifactId>
<version>1</version>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
</project>
+9
Переглянути файл
@@ -0,0 +1,9 @@
<project>
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>t</groupId>
<artifactId>root</artifactId>
<version>1</version>
</parent>
<artifactId>lib</artifactId>
</project>
+35
Переглянути файл
@@ -0,0 +1,35 @@
<project>
<modelVersion>4.0.0</modelVersion>
<groupId>t</groupId>
<artifactId>root</artifactId>
<version>1</version>
<packaging>pom</packaging>
<modules>
<module>lib</module>
<module>app</module>
</modules>
<properties>
<maven.compiler.release>11</maven.compiler.release>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>3.4.0</version>
</plugin>
</plugins>
<pluginManagement>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.13.0</version>
<configuration>
<parameters>true</parameters>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
+2 -2
Переглянути файл
@@ -260,8 +260,8 @@ pub fn decode(bytes: &[u8]) -> Vec<PathBuf> {
/// may be larger than the text, and a malformed one may lack the NUL.
#[cfg(any(windows, test))]
fn unicode_text(bytes: &[u8]) -> String {
let units: Vec<u16> =
bytes.chunks_exact(2).map(|b| u16::from_le_bytes([b[0], b[1]])).take_while(|&unit| unit != 0).collect();
let (pairs, _) = bytes.as_chunks::<2>();
let units: Vec<u16> = pairs.iter().map(|&pair| u16::from_le_bytes(pair)).take_while(|&unit| unit != 0).collect();
String::from_utf16_lossy(&units)
}
+2
Переглянути файл
@@ -46,6 +46,8 @@ pub enum ErrorData {
JavaBuildProblems {
problems: Vec<String>,
},
/// A remote backend of another OpenIDEA build still serves the project and refused to retire.
RemoteBackendBusy,
}
/// Git's reported result for each destination ref. A remote with several push URLs can
+115 -42
Переглянути файл
@@ -308,6 +308,14 @@ pub struct SessionInfo {
pub parent: Option<DebugSessionId>,
}
/// One owner's breakpoints, kept without a session and sent when one of its sessions starts.
#[derive(Default)]
struct OwnerBreakpoints {
lines: BTreeMap<PathBuf, Vec<Breakpoint>>,
functions: Vec<FunctionBreakpoint>,
data: Vec<DataBreakpoint>,
}
/// Who started a session. Every event of the session, and of the child sessions
/// its adapter starts, goes to `sink` only; `key` (e.g. a window label) scopes
/// listings such as [`DebugManager::sessions`].
@@ -336,13 +344,12 @@ pub struct DebugManager {
sessions: Mutex<HashMap<DebugSessionId, Arc<Session>>>,
/// Session start order, for "the first session" semantics.
order: Mutex<Vec<DebugSessionId>>,
breakpoints: Mutex<BTreeMap<PathBuf, Vec<Breakpoint>>>,
/// Breakpoints by owner (window): each window's sessions get only its own.
breakpoints: Mutex<HashMap<String, OwnerBreakpoints>>,
states: Mutex<HashMap<PathBuf, Vec<BreakpointState>>>,
/// Explicit exception filter choices (filter id → enabled); unset filters use the adapter default.
exception_choices: Mutex<BTreeMap<String, bool>>,
exception_classes: Mutex<Vec<ExceptionClassBreakpoint>>,
function_breakpoints: Mutex<Vec<FunctionBreakpoint>>,
data_breakpoints: Mutex<Vec<DataBreakpoint>>,
/// In-flight stops, by session: a second Stop sets `stop_force`, the waiting one kills.
stopping: Mutex<HashMap<DebugSessionId, Arc<Session>>>,
jvm_finder: Mutex<jvm_memory::JvmFinder>,
@@ -818,8 +825,6 @@ impl DebugManager {
states: Mutex::default(),
exception_choices: Mutex::default(),
exception_classes: Mutex::default(),
function_breakpoints: Mutex::default(),
data_breakpoints: Mutex::default(),
stopping: Mutex::default(),
jvm_finder: Mutex::new(Arc::new(jvm_memory::find_local_jvm)),
})
@@ -839,8 +844,24 @@ impl DebugManager {
self.order.lock().iter().filter_map(|id| sessions.get(id).cloned()).collect()
}
pub(crate) fn stored_breakpoints(&self, path: &Path) -> Vec<Breakpoint> {
self.breakpoints.lock().get(path).cloned().unwrap_or_default()
pub(crate) fn stored_breakpoints(&self, owner: &str, path: &Path) -> Vec<Breakpoint> {
self.breakpoints.lock().get(owner).and_then(|b| b.lines.get(path).cloned()).unwrap_or_default()
}
fn function_breakpoints(&self, owner: &str) -> Vec<FunctionBreakpoint> {
self.breakpoints.lock().get(owner).map(|b| b.functions.clone()).unwrap_or_default()
}
fn data_breakpoints(&self, owner: &str) -> Vec<DataBreakpoint> {
self.breakpoints.lock().get(owner).map(|b| b.data.clone()).unwrap_or_default()
}
/// `owner`'s sessions that take breakpoint requests.
fn configured_sessions(&self, owner: &str) -> Vec<Arc<Session>> {
self.live_sessions()
.into_iter()
.filter(|s| s.owner.key == owner && s.configured.load(Ordering::Acquire) && !s.conn.is_closed())
.collect()
}
/// Live sessions of `owner` (all owners when `None`).
@@ -1291,8 +1312,10 @@ impl DebugManager {
let (files, idle): (Vec<_>, Vec<_>) = self
.breakpoints
.lock()
.iter()
.map(|(p, b)| (p.clone(), b.clone()))
.get(&s.owner.key)
.map(|b| b.lines.iter().map(|(p, b)| (p.clone(), b.clone())).collect::<Vec<_>>())
.unwrap_or_default()
.into_iter()
.partition(|(_, b)| b.iter().any(|b| b.enabled));
let sent = join_all(files.iter().map(|(path, bps)| s.send_breakpoints(path, bps, None))).await;
// Breakpoint states follow the owner's first session.
@@ -1310,14 +1333,14 @@ impl DebugManager {
Err(e) => tracing::debug!("setBreakpoints for {} failed: {e}", path.display()),
}
}
let functions = self.function_breakpoints.lock().clone();
let functions = self.function_breakpoints(&s.owner.key);
if !functions.is_empty()
&& s.supports("supportsFunctionBreakpoints")
&& let Err(e) = s.send_function_breakpoints(&functions).await
{
tracing::debug!("setFunctionBreakpoints failed: {e}");
}
let data = self.data_breakpoints.lock().clone();
let data = self.data_breakpoints(&s.owner.key);
if !data.is_empty()
&& s.supports("supportsDataBreakpoints")
&& let Err(e) = s.send_data_breakpoints(&data).await
@@ -1470,26 +1493,59 @@ impl DebugManager {
}
}
/// Breakpoints are kept per file even without a session and sent on start.
/// Returns states from the first live session, or unverified states when none.
/// `owner`'s breakpoints are kept per file even without a session and sent when one of
/// its sessions starts. Returns states from its first live session, or unverified states.
pub async fn set_breakpoints(
&self,
owner: &str,
path: PathBuf,
breakpoints: Vec<Breakpoint>,
) -> IdeResult<Vec<BreakpointState>> {
{
let mut store = self.breakpoints.lock();
let lines = &mut store.entry(owner.to_owned()).or_default().lines;
if breakpoints.is_empty() {
store.remove(&path);
lines.remove(&path);
} else {
store.insert(path.clone(), breakpoints.clone());
lines.insert(path.clone(), breakpoints.clone());
}
}
self.send_file_breakpoints(owner, path, breakpoints).await
}
/// Replaces all of `owner`'s line breakpoints with `files` (the window's whole list), sending
/// the files that changed to its sessions. A file the window no longer lists can't stay
/// behind and be sent to every later session, whatever made the two lists diverge (#6116).
pub async fn replace_breakpoints(&self, owner: &str, files: BTreeMap<PathBuf, Vec<Breakpoint>>) -> IdeResult<()> {
let changed: Vec<(PathBuf, Vec<Breakpoint>)> = {
let mut store = self.breakpoints.lock();
let lines = &mut store.entry(owner.to_owned()).or_default().lines;
let files: BTreeMap<_, _> = files.into_iter().filter(|(_, b)| !b.is_empty()).collect();
let removed = lines.keys().filter(|p| !files.contains_key(*p)).map(|p| (p.clone(), Vec::new()));
let changed = files.iter().filter(|(p, b)| lines.get(*p) != Some(b)).map(|(p, b)| (p.clone(), b.clone()));
let changed = removed.chain(changed).collect();
*lines = files;
changed
};
for (path, breakpoints) in changed {
self.send_file_breakpoints(owner, path, breakpoints).await?;
}
Ok(())
}
/// Drops `owner`'s breakpoints (its window closed).
pub fn forget_breakpoints(&self, owner: &str) {
self.breakpoints.lock().remove(owner);
}
async fn send_file_breakpoints(
&self,
owner: &str,
path: PathBuf,
breakpoints: Vec<Breakpoint>,
) -> IdeResult<Vec<BreakpointState>> {
let mut result: Option<Vec<BreakpointState>> = None;
for s in self.live_sessions() {
if !s.configured.load(Ordering::Acquire) || s.conn.is_closed() {
continue;
}
for s in self.configured_sessions(owner) {
match s.send_breakpoints(&path, &breakpoints, None).await {
Ok(states) => {
result.get_or_insert(states);
@@ -1853,7 +1909,7 @@ impl DebugManager {
if force {
self.suspend_breakpoints(&session, Some(&path)).await?;
}
let stored = self.stored_breakpoints(&path);
let stored = self.stored_breakpoints(&session.owner.key, &path);
let sent: Vec<Breakpoint> =
if force { stored.iter().map(|b| Breakpoint { enabled: false, ..b.clone() }).collect() } else { stored };
session.send_breakpoints(&path, &sent, Some(line)).await?;
@@ -1868,10 +1924,15 @@ impl DebugManager {
let files: Vec<PathBuf> = self
.breakpoints
.lock()
.iter()
.filter(|(path, bps)| Some(path.as_path()) != except && bps.iter().any(|b| b.enabled))
.map(|(path, _)| path.clone())
.collect();
.get(&session.owner.key)
.map(|b| {
b.lines
.iter()
.filter(|(path, bps)| Some(path.as_path()) != except && bps.iter().any(|b| b.enabled))
.map(|(path, _)| path.clone())
.collect()
})
.unwrap_or_default();
let sent = join_all(files.iter().map(|path| session.send_breakpoints(path, &[], None))).await;
let mut failed = None;
for (path, result) in files.into_iter().zip(sent) {
@@ -1885,11 +1946,12 @@ impl DebugManager {
if let Some(e) = failed {
return Err(e.into());
}
if !self.function_breakpoints.lock().is_empty() && session.supports("supportsFunctionBreakpoints") {
if !self.function_breakpoints(&session.owner.key).is_empty() && session.supports("supportsFunctionBreakpoints")
{
session.send_function_breakpoints(&[]).await?;
session.pending_restore.lock().functions = true;
}
if !self.data_breakpoints.lock().is_empty() && session.supports("supportsDataBreakpoints") {
if !self.data_breakpoints(&session.owner.key).is_empty() && session.supports("supportsDataBreakpoints") {
session.send_data_breakpoints(&[]).await?;
session.pending_restore.lock().data = true;
}
@@ -1899,8 +1961,11 @@ impl DebugManager {
/// Re-sends what [`suspend_breakpoints`](Self::suspend_breakpoints) / run to cursor replaced.
pub(crate) async fn restore_breakpoints(&self, session: &Arc<Session>) {
let pending = std::mem::take(&mut *session.pending_restore.lock());
let files: Vec<(PathBuf, Vec<Breakpoint>)> =
pending.files.into_iter().map(|path| (path.clone(), self.stored_breakpoints(&path))).collect();
let files: Vec<(PathBuf, Vec<Breakpoint>)> = pending
.files
.into_iter()
.map(|path| (path.clone(), self.stored_breakpoints(&session.owner.key, &path)))
.collect();
let sent = join_all(files.iter().map(|(path, bps)| session.send_breakpoints(path, bps, None))).await;
for ((path, _), result) in files.iter().zip(sent) {
if let Err(e) = result {
@@ -1908,13 +1973,13 @@ impl DebugManager {
}
}
if pending.functions {
let functions = self.function_breakpoints.lock().clone();
let functions = self.function_breakpoints(&session.owner.key);
if let Err(e) = session.send_function_breakpoints(&functions).await {
tracing::debug!("restoring function breakpoints failed: {e}");
}
}
if pending.data {
let data = self.data_breakpoints.lock().clone();
let data = self.data_breakpoints(&session.owner.key);
if let Err(e) = session.send_data_breakpoints(&data).await {
tracing::debug!("restoring data breakpoints failed: {e}");
}
@@ -2124,14 +2189,17 @@ impl DebugManager {
Ok(hot_swap_result(&body))
}
/// Stores method breakpoints (kept without a session, sent on start) and sends them to
/// every configured session whose adapter supports them. States from the first one.
pub async fn set_function_breakpoints(&self, list: Vec<FunctionBreakpoint>) -> IdeResult<Vec<BreakpointState>> {
*self.function_breakpoints.lock() = list.clone();
/// Stores `owner`'s method breakpoints (kept without a session, sent on start) and sends them
/// to each of its configured sessions whose adapter supports them. States from the first one.
pub async fn set_function_breakpoints(
&self,
owner: &str,
list: Vec<FunctionBreakpoint>,
) -> IdeResult<Vec<BreakpointState>> {
self.breakpoints.lock().entry(owner.to_owned()).or_default().functions = list.clone();
let mut result = None;
for s in self.live_sessions() {
if !s.configured.load(Ordering::Acquire) || s.conn.is_closed() || !s.supports("supportsFunctionBreakpoints")
{
for s in self.configured_sessions(owner) {
if !s.supports("supportsFunctionBreakpoints") {
continue;
}
match s.send_function_breakpoints(&list).await {
@@ -2144,12 +2212,17 @@ impl DebugManager {
Ok(result.unwrap_or_else(|| unverified(list.iter().map(|b| b.enabled))))
}
/// Stores field watchpoints and sends them to every configured session that supports them.
pub async fn set_data_breakpoints(&self, list: Vec<DataBreakpoint>) -> IdeResult<Vec<BreakpointState>> {
*self.data_breakpoints.lock() = list.clone();
/// Stores `owner`'s field watchpoints and sends them to each of its configured sessions that
/// supports them.
pub async fn set_data_breakpoints(
&self,
owner: &str,
list: Vec<DataBreakpoint>,
) -> IdeResult<Vec<BreakpointState>> {
self.breakpoints.lock().entry(owner.to_owned()).or_default().data = list.clone();
let mut result = None;
for s in self.live_sessions() {
if !s.configured.load(Ordering::Acquire) || s.conn.is_closed() || !s.supports("supportsDataBreakpoints") {
for s in self.configured_sessions(owner) {
if !s.supports("supportsDataBreakpoints") {
continue;
}
match s.send_data_breakpoints(&list).await {
+61 -21
Переглянути файл
@@ -899,7 +899,7 @@ async fn full_protocol_flow() {
let path = PathBuf::from("/p/a.py");
let disabled = Breakpoint { enabled: false, ..bp(2) };
let cond = Breakpoint { condition: Some("x > 1".into()), ..bp(7) };
let states = h.manager.set_breakpoints(path.clone(), vec![bp(4), disabled, cond]).await.unwrap();
let states = h.manager.set_breakpoints(&h.owner.key, path.clone(), vec![bp(4), disabled, cond]).await.unwrap();
assert!(states.iter().all(|s| !s.verified), "no session yet");
let id = h.start(config()).await.unwrap();
@@ -981,7 +981,7 @@ async fn full_protocol_flow() {
assert_eq!(asked["arguments"]["frameId"], 10);
// Live breakpoint updates reach the session.
let states = h.manager.set_breakpoints(path.clone(), vec![bp(0)]).await.unwrap();
let states = h.manager.set_breakpoints(&h.owner.key, path.clone(), vec![bp(0)]).await.unwrap();
assert!(states[0].verified);
h.manager.resume(id, 1).await.unwrap();
@@ -1005,7 +1005,7 @@ async fn full_protocol_flow() {
async fn run_to_cursor_uses_temporary_breakpoint() {
let h = harness(Script::default());
let path = PathBuf::from("/p/a.py");
h.manager.set_breakpoints(path.clone(), vec![bp(1)]).await.unwrap();
h.manager.set_breakpoints(&h.owner.key, path.clone(), vec![bp(1)]).await.unwrap();
let id = h.start(config()).await.unwrap();
h.wait_event(|e| matches!(e, DebugEvent::Stopped { .. })).await;
h.manager.run_to(id, 1, path.clone(), 9, false).await.unwrap();
@@ -1037,7 +1037,7 @@ async fn stop_terminates_and_disconnects() {
#[tokio::test]
async fn unity_attach_waits_for_mono_and_disconnects_without_terminating_editor() {
let h = harness(Script { empty_thread_responses: 2, ..Script::default() });
h.manager.set_breakpoints(PathBuf::from("/p/a.cs"), vec![bp(4)]).await.unwrap();
h.manager.set_breakpoints(&h.owner.key, PathBuf::from("/p/a.cs"), vec![bp(4)]).await.unwrap();
let start = h.start(LaunchConfig {
adapter: "unity".into(),
request: "attach".into(),
@@ -1889,7 +1889,7 @@ fn function_bp(name: &str, enabled: bool) -> FunctionBreakpoint {
async fn function_and_data_breakpoints_are_stored_and_sent() {
let h = harness(Script::default());
let cond = FunctionBreakpoint { condition: Some("n > 1".into()), ..function_bp("com.a.B#run", true) };
let states = h.manager.set_function_breakpoints(vec![cond, function_bp("off", false)]).await.unwrap();
let states = h.manager.set_function_breakpoints(&h.owner.key, vec![cond, function_bp("off", false)]).await.unwrap();
assert!(!states[0].verified && states[1].message.as_deref() == Some("Disabled"), "no session yet");
let watch = DataBreakpoint {
data_id: "Req#count".into(),
@@ -1898,7 +1898,7 @@ async fn function_and_data_breakpoints_are_stored_and_sent() {
hit_condition: Some("2".into()),
enabled: true,
};
h.manager.set_data_breakpoints(vec![watch]).await.unwrap();
h.manager.set_data_breakpoints(&h.owner.key, vec![watch]).await.unwrap();
let id = h.start(config()).await.unwrap();
assert_eq!(
@@ -1914,8 +1914,11 @@ async fn function_and_data_breakpoints_are_stored_and_sent() {
let pos = |c: &str| order.iter().position(|x| x == c).unwrap();
assert!(pos("setFunctionBreakpoints") < pos("configurationDone"));
let states =
h.manager.set_function_breakpoints(vec![function_bp("missing", true), function_bp("ok", true)]).await.unwrap();
let states = h
.manager
.set_function_breakpoints(&h.owner.key, vec![function_bp("missing", true), function_bp("ok", true)])
.await
.unwrap();
assert_eq!((states[0].verified, states[1].verified), (false, true), "live states from the session");
let info = h.manager.data_breakpoint_info(id, 101, "count".into(), Some(10)).await.unwrap();
@@ -1958,10 +1961,13 @@ async fn force_stepping_suspends_breakpoints_until_the_next_stop() {
let h = harness(Script::default());
let a = PathBuf::from("/p/a.py");
let b = PathBuf::from("/p/b.py");
h.manager.set_breakpoints(a.clone(), vec![bp(1)]).await.unwrap();
h.manager.set_breakpoints(b.clone(), vec![bp(3)]).await.unwrap();
h.manager.set_breakpoints(PathBuf::from("/p/off.py"), vec![Breakpoint { enabled: false, ..bp(5) }]).await.unwrap();
h.manager.set_function_breakpoints(vec![function_bp("run", true)]).await.unwrap();
h.manager.set_breakpoints(&h.owner.key, a.clone(), vec![bp(1)]).await.unwrap();
h.manager.set_breakpoints(&h.owner.key, b.clone(), vec![bp(3)]).await.unwrap();
h.manager
.set_breakpoints(&h.owner.key, PathBuf::from("/p/off.py"), vec![Breakpoint { enabled: false, ..bp(5) }])
.await
.unwrap();
h.manager.set_function_breakpoints(&h.owner.key, vec![function_bp("run", true)]).await.unwrap();
let id = h.start(config()).await.unwrap();
h.wait_event(|e| matches!(e, DebugEvent::Stopped { .. })).await;
let sent_for = |path: &str| -> Vec<Value> {
@@ -1995,10 +2001,10 @@ async fn force_stepping_suspends_breakpoints_until_the_next_stop() {
#[tokio::test]
async fn startup_sends_every_file_at_once_and_skips_files_with_nothing_enabled() {
let h = harness(Script { hold_set_breakpoints: 2, ..Script::default() });
h.manager.set_breakpoints(PathBuf::from("/p/a.py"), vec![bp(1)]).await.unwrap();
h.manager.set_breakpoints(PathBuf::from("/p/b.py"), vec![bp(3)]).await.unwrap();
h.manager.set_breakpoints(&h.owner.key, PathBuf::from("/p/a.py"), vec![bp(1)]).await.unwrap();
h.manager.set_breakpoints(&h.owner.key, PathBuf::from("/p/b.py"), vec![bp(3)]).await.unwrap();
let off = PathBuf::from("/p/off.py");
h.manager.set_breakpoints(off.clone(), vec![Breakpoint { enabled: false, ..bp(5) }]).await.unwrap();
h.manager.set_breakpoints(&h.owner.key, off.clone(), vec![Breakpoint { enabled: false, ..bp(5) }]).await.unwrap();
// Waiting for each answer before the next request would stall until the request timeout.
tokio::time::timeout(Duration::from_secs(5), h.start(config())).await.expect("requests pipelined").unwrap();
let paths: Vec<Value> = requests(&h, "setBreakpoints").into_iter().map(|r| r["source"]["path"].clone()).collect();
@@ -2009,6 +2015,40 @@ async fn startup_sends_every_file_at_once_and_skips_files_with_nothing_enabled()
);
}
#[tokio::test]
async fn sessions_get_only_their_windows_breakpoints_and_a_replaced_list_drops_stale_files() {
let h = harness(Script::default());
let other = "project-2";
h.manager.set_breakpoints(other, PathBuf::from("/p/other.py"), vec![bp(1)]).await.unwrap();
h.manager.set_function_breakpoints(other, vec![function_bp("elsewhere", true)]).await.unwrap();
let stale = PathBuf::from("/p/stale.py");
h.manager.set_breakpoints(&h.owner.key, stale.clone(), vec![bp(2)]).await.unwrap();
let id = h.start(config()).await.unwrap();
let paths = || -> Vec<(Value, Value)> {
requests(&h, "setBreakpoints")
.into_iter()
.map(|r| (r["source"]["path"].clone(), r["breakpoints"].clone()))
.collect()
};
assert_eq!(paths(), [(json!("/p/stale.py"), json!([{"line": 3}]))], "another window's file is not sent");
assert!(requests(&h, "setFunctionBreakpoints").is_empty(), "nor its method breakpoints");
// The window's list no longer has the stale file (#6116): replacing clears it in the session...
let kept = PathBuf::from("/p/kept.py");
h.manager.replace_breakpoints(&h.owner.key, BTreeMap::from([(kept.clone(), vec![bp(4)])])).await.unwrap();
assert_eq!(paths()[1..], [(json!("/p/stale.py"), json!([])), (json!("/p/kept.py"), json!([{"line": 5}]))]);
// ...unchanged files are not sent again...
h.manager.replace_breakpoints(&h.owner.key, BTreeMap::from([(kept.clone(), vec![bp(4)])])).await.unwrap();
assert_eq!(paths().len(), 3);
h.manager.stop(id).await.unwrap();
// ...and the next session gets only what the window lists.
let h2 = harness(Script::default());
h2.manager.set_breakpoints(&h2.owner.key, stale.clone(), vec![bp(2)]).await.unwrap();
h2.manager.replace_breakpoints(&h2.owner.key, BTreeMap::new()).await.unwrap();
h2.start(config()).await.unwrap();
assert!(requests(&h2, "setBreakpoints").is_empty());
}
#[tokio::test]
async fn hot_reload_sends_its_reason_and_reports_the_flutter_app() {
let h = harness(Script::default());
@@ -2209,7 +2249,7 @@ async fn godot_gets_resolved_paths() {
Arc::new(FakeLauncher { log: log.clone(), script: Script::default() }),
);
let bp = Breakpoint { line: 0, condition: None, hit_condition: None, log_message: None, enabled: true };
manager.set_breakpoints(link.join("player.gd"), vec![bp]).await.unwrap();
manager.set_breakpoints("main", link.join("player.gd"), vec![bp]).await.unwrap();
let id = manager.start(godot_launch(&link), owner).await.unwrap();
let sent = log.lock().iter().find(|m| m["command"] == "setBreakpoints").cloned().unwrap();
assert_eq!(sent["arguments"]["source"]["path"], json!(real.join("player.gd")));
@@ -2236,7 +2276,7 @@ async fn kotlin_configures_without_configuration_done_response() {
let project = tempfile::tempdir().unwrap();
let path = project.path().join("Main.kt");
std::fs::write(&path, "package org.example\nfun main() {}\n").unwrap();
h.manager.set_breakpoints(path.clone(), vec![bp(1)]).await.unwrap();
h.manager.set_breakpoints(&h.owner.key, path.clone(), vec![bp(1)]).await.unwrap();
let mut config = config();
config.adapter = kotlin::ADAPTER.into();
config.request = "attach".into();
@@ -2270,7 +2310,7 @@ async fn kotlin_official_release_ten_no_delay_runs() {
let (owner, events) = recording_owner("kotlin-probe");
let manager = DebugManager::new(Arc::new(LanguageRegistry::from_configs(Vec::new())));
let h = Harness { manager, owner, events, log: Arc::default() };
h.manager.set_breakpoints(source.clone(), vec![bp(5)]).await.unwrap();
h.manager.set_breakpoints(&h.owner.key, source.clone(), vec![bp(5)]).await.unwrap();
let id = h.manager.start_with(config.clone(), h.owner.clone(), |_| Some(adapter.clone())).await.unwrap();
let stopped = h.wait_event(|e| matches!(e, DebugEvent::Stopped { reason, .. } if reason == "breakpoint")).await;
let DebugEvent::Stopped { thread_id, .. } = stopped else { unreachable!() };
@@ -2299,7 +2339,7 @@ async fn netcoredbg_windows_source_paths_round_trip() {
let native = r"D:\work\LoginController.cs";
let h = harness(Script { source_path: Some(native.into()), ..Script::default() });
let path = PathBuf::from(client);
h.manager.set_breakpoints(path.clone(), vec![bp(25)]).await.unwrap();
h.manager.set_breakpoints(&h.owner.key, path.clone(), vec![bp(25)]).await.unwrap();
let mut cfg = config();
cfg.adapter = "netcoredbg".into();
let id = h.start(cfg).await.unwrap();
@@ -2323,7 +2363,7 @@ async fn java_windows_source_paths_for_launch_and_attach() {
] {
let h = harness(Script { source_path: Some(returned.into()), ..Script::default() });
let path = PathBuf::from(client);
h.manager.set_breakpoints(path.clone(), vec![bp(4)]).await.unwrap();
h.manager.set_breakpoints(&h.owner.key, path.clone(), vec![bp(4)]).await.unwrap();
let mut cfg = config();
cfg.adapter = "java-debug".into();
cfg.request = request.into();
@@ -3418,7 +3458,7 @@ async fn kotlin_lsp_gets_real_paths_and_its_link_holds_nothing() {
let project = tempfile::tempdir().unwrap();
let path = project.path().join("Main.kt");
std::fs::write(&path, "package org.example\nfun main() {}\n").unwrap();
h.manager.set_breakpoints(path.clone(), vec![bp(1)]).await.unwrap();
h.manager.set_breakpoints(&h.owner.key, path.clone(), vec![bp(1)]).await.unwrap();
let id = h.start(kotlin_lsp_attach(project.path())).await.unwrap();
assert_eq!(h.request("setBreakpoints")["arguments"]["source"]["path"], json!(path));
let sent = &h.request("attach")["arguments"];
+2 -2
Переглянути файл
@@ -47,7 +47,7 @@ async fn debugpy_end_to_end() {
let sink: SharedSink = Arc::new(move |e: IdeEvent| sink_events.lock().push(e));
let manager = DebugManager::new(Arc::new(LanguageRegistry::from_configs(Vec::new())));
let bp = Breakpoint { line: 3, condition: None, hit_condition: None, log_message: None, enabled: true };
manager.set_breakpoints(script.clone(), vec![bp]).await.unwrap();
manager.set_breakpoints("main", script.clone(), vec![bp]).await.unwrap();
let id = manager
.start(
LaunchConfig {
@@ -74,7 +74,7 @@ async fn debugpy_end_to_end() {
assert!(vars.iter().any(|v| v.name == "total"), "{vars:?}");
let v = manager.evaluate(id, Some(frames[0].id), "total + 100".into()).await.unwrap();
assert_eq!(v.value, "100");
manager.set_breakpoints(script.clone(), vec![]).await.unwrap();
manager.set_breakpoints("main", script.clone(), vec![]).await.unwrap();
manager.resume(id, thread_id).await.unwrap();
wait(&events, |e| matches!(e, DebugEvent::Output { output, .. } if output.contains("total 3"))).await;
wait(&events, |e| matches!(e, DebugEvent::Terminated)).await;
+1
Переглянути файл
@@ -96,6 +96,7 @@ async fn breakpoints_stepping_and_variables_in_a_real_godot() {
let script_as_opened = dir.join("player.gd");
manager
.set_breakpoints(
"main",
script_as_opened.clone(),
vec![Breakpoint {
line: BREAK_LINE,
+1
Переглянути файл
@@ -81,6 +81,7 @@ async fn listens_for_xdebug_until_stopped_with_path_mappings() {
let local_script = local.join("index.php");
manager
.set_breakpoints(
"main",
local_script.clone(),
vec![Breakpoint {
line: BREAK_LINE,
+13 -11
Переглянути файл
@@ -261,7 +261,7 @@ async fn scenario(case: &Case) -> Result<Vec<String>, String> {
let m = &run.manager;
let line_bp =
Breakpoint { line: case.loop_line, condition: None, hit_condition: None, log_message: None, enabled: true };
m.set_breakpoints(case.source.clone(), vec![line_bp]).await.map_err(|e| e.message)?;
m.set_breakpoints("test", case.source.clone(), vec![line_bp]).await.map_err(|e| e.message)?;
let seen = run.seen();
let id = m.start(case.config.clone(), run.owner.clone()).await.map_err(|e| format!("start: {}", e.message))?;
@@ -356,9 +356,9 @@ async fn scenario(case: &Case) -> Result<Vec<String>, String> {
// Method breakpoint: continue → stops in `parse`.
if caps.function_breakpoints {
let fb = FunctionBreakpoint { name: case.function.into(), condition: None, hit_condition: None, enabled: true };
let states = m.set_function_breakpoints(vec![fb]).await.map_err(|e| e.message)?;
let states = m.set_function_breakpoints("test", vec![fb]).await.map_err(|e| e.message)?;
report.push(format!("method breakpoint `{}`: verified={}", case.function, states[0].verified));
m.set_breakpoints(case.source.clone(), vec![]).await.map_err(|e| e.message)?;
m.set_breakpoints("test", case.source.clone(), vec![]).await.map_err(|e| e.message)?;
let seen = run.seen();
m.resume(s, thread).await.map_err(|e| e.message)?;
match run.stopped_after(seen).await {
@@ -368,8 +368,10 @@ async fn scenario(case: &Case) -> Result<Vec<String>, String> {
}
None => report.push("method breakpoint: NOT HIT".into()),
}
m.set_function_breakpoints(vec![]).await.map_err(|e| e.message)?;
m.set_breakpoints(case.source.clone(), vec![line_bp_at(case.loop_line)]).await.map_err(|e| e.message)?;
m.set_function_breakpoints("test", vec![]).await.map_err(|e| e.message)?;
m.set_breakpoints("test", case.source.clone(), vec![line_bp_at(case.loop_line)])
.await
.map_err(|e| e.message)?;
let seen = run.seen();
m.step(s, thread, StepKind::Out).await.map_err(|e| e.message)?;
run.stopped_after(seen).await.ok_or("no stop after step out of parse")?;
@@ -378,7 +380,7 @@ async fn scenario(case: &Case) -> Result<Vec<String>, String> {
}
// Force Step Over ignores the breakpoint inside parse.
m.set_breakpoints(case.source.clone(), vec![line_bp_at(case.loop_line)]).await.map_err(|e| e.message)?;
m.set_breakpoints("test", case.source.clone(), vec![line_bp_at(case.loop_line)]).await.map_err(|e| e.message)?;
let seen = run.seen();
m.force_step_over(s, thread).await.map_err(|e| e.message)?;
let (_, t, reason) = run.stopped_after(seen).await.ok_or("no stop after force step over")?;
@@ -409,8 +411,8 @@ async fn scenario(case: &Case) -> Result<Vec<String>, String> {
hit_condition: None,
enabled: true,
};
let states = m.set_data_breakpoints(vec![wp]).await.map_err(|e| e.message)?;
m.set_breakpoints(case.source.clone(), vec![]).await.map_err(|e| e.message)?;
let states = m.set_data_breakpoints("test", vec![wp]).await.map_err(|e| e.message)?;
m.set_breakpoints("test", case.source.clone(), vec![]).await.map_err(|e| e.message)?;
let seen = run.seen();
m.resume(s, thread).await.map_err(|e| e.message)?;
match run.stopped_after(seen).await {
@@ -425,8 +427,8 @@ async fn scenario(case: &Case) -> Result<Vec<String>, String> {
}
None => report.push(format!("watchpoint `{data_id}`: NOT HIT")),
}
m.set_data_breakpoints(vec![]).await.map_err(|e| e.message)?;
m.set_breakpoints(case.source.clone(), vec![line_bp_at(case.loop_line)])
m.set_data_breakpoints("test", vec![]).await.map_err(|e| e.message)?;
m.set_breakpoints("test", case.source.clone(), vec![line_bp_at(case.loop_line)])
.await
.map_err(|e| e.message)?;
}
@@ -623,7 +625,7 @@ async fn attach_to_processes() {
};
let run = Run::new();
run.manager
.set_breakpoints(case.source.clone(), vec![line_bp_at(case.line)])
.set_breakpoints("test", case.source.clone(), vec![line_bp_at(case.line)])
.await
.map_err(|e| e.message)?;
let id =
+3 -3
Переглянути файл
@@ -253,7 +253,7 @@ async fn scenario(case: &Case) -> Result<Vec<String>, String> {
let mut report = Vec::new();
let run = Run::new();
let m = &run.manager;
m.set_breakpoints(case.source.clone(), vec![bp(LOOP_LINE)]).await.map_err(|e| e.message)?;
m.set_breakpoints("test", case.source.clone(), vec![bp(LOOP_LINE)]).await.map_err(|e| e.message)?;
let id = m.start(case.config.clone(), run.owner.clone()).await.map_err(|e| format!("start: {}", e.message))?;
let (s, thread) = run.stopped(0, "the loop breakpoint").await?;
@@ -312,7 +312,7 @@ async fn scenario(case: &Case) -> Result<Vec<String>, String> {
expect_line(&run.top(s2, t2).await?, LOOP_LINE, "continue")?;
// Without breakpoints, the program runs to its end.
m.set_breakpoints(case.source.clone(), vec![]).await.map_err(|e| e.message)?;
m.set_breakpoints("test", case.source.clone(), vec![]).await.map_err(|e| e.message)?;
let seen = run.seen();
m.resume(s2, t2).await.map_err(|e| e.message)?;
run.wait(seen, "terminated", |s, e| (s == id && matches!(e, DebugEvent::Terminated)).then_some(())).await?;
@@ -333,7 +333,7 @@ async fn scenario(case: &Case) -> Result<Vec<String>, String> {
report.push("continue to exit: output and terminated".into());
// Restart (the UI starts the same configuration again), then Stop while paused.
m.set_breakpoints(case.source.clone(), vec![bp(LOOP_LINE)]).await.map_err(|e| e.message)?;
m.set_breakpoints("test", case.source.clone(), vec![bp(LOOP_LINE)]).await.map_err(|e| e.message)?;
let seen = run.seen();
let again = m.start(case.config.clone(), run.owner.clone()).await.map_err(|e| format!("restart: {}", e.message))?;
let (s, thread) = run.stopped(seen, "the breakpoint after restart").await?;
+1
Переглянути файл
@@ -110,6 +110,7 @@ async fn real_editor_attach_breakpoint_step_variables_and_detach() {
let line = SCRIPT.lines().position(|l| l.contains("int answer =")).unwrap() as u32;
manager
.set_breakpoints(
"smoke",
source.clone(),
vec![Breakpoint { line, condition: None, hit_condition: None, log_message: None, enabled: true }],
)
+25 -12
Переглянути файл
@@ -297,6 +297,8 @@ pub struct DbManager {
type Session = Arc<tokio::sync::Mutex<Option<Held>>>;
const MAX_META_ROWS: usize = 100_000;
/// Completion columns of the default schema, which are read without the shared cap.
const MAX_SCHEMA_COMPLETION_ROWS: usize = 1_000_000;
/// Rows of catalog query `q`, run again as [`sql::postgres_legacy`] when a PostgreSQL server's
/// catalog lacks a column it reads (openGauss, PostgreSQL 9).
@@ -1429,13 +1431,34 @@ impl DbManager {
let pool = self.pool(id).await?;
let driver = pool.driver();
let mut tables: Vec<CompletionTable> = Vec::new();
if let Pool::Jdbc(p) = &*pool {
return self.jdbc_completion(id, p).await;
}
let default_schema = match sql::current_schema(driver) {
None => "main".to_owned(),
Some(q) => pool
.rows(q, 1)
.await?
.into_iter()
.next()
.and_then(|r| r.into_iter().next().flatten())
.unwrap_or_default(),
};
let rows = match &*pool {
Pool::Jdbc(p) => return self.jdbc_completion(id, p).await,
Pool::Snowflake(p) => {
tables = snowflake::meta::completion(p).await?;
Vec::new()
}
_ => pool.rows(sql::completion_columns(driver), MAX_META_ROWS).await?,
// The default schema is read in full: under a shared row cap, a schema with many
// tables lost the columns of the tables sorting last (#6118). Other schemas share the cap.
_ if !default_schema.is_empty() => {
let only = sql::completion_columns(driver, sql::CompletionScope::Only(&default_schema));
let mut rows = pool.rows(&only, MAX_SCHEMA_COMPLETION_ROWS).await?;
let rest = sql::completion_columns(driver, sql::CompletionScope::Except(&default_schema));
rows.extend(pool.rows(&rest, MAX_META_ROWS).await?);
rows
}
_ => pool.rows(&sql::completion_columns(driver, sql::CompletionScope::All), MAX_META_ROWS).await?,
};
for r in rows {
let mut it = r.into_iter().map(Option::unwrap_or_default);
@@ -1471,16 +1494,6 @@ impl DbManager {
})
};
let foreign_keys = group_foreign_keys(fk_rows, &tables);
let default_schema = match sql::current_schema(driver) {
None => "main".to_owned(),
Some(q) => pool
.rows(q, 1)
.await?
.into_iter()
.next()
.and_then(|r| r.into_iter().next().flatten())
.unwrap_or_default(),
};
Ok(CompletionModel { default_schema, tables, foreign_keys })
}
+99 -38
Переглянути файл
@@ -252,31 +252,47 @@ pub fn indexes(driver: DbDriver, schema: &str, table: &str) -> String {
}
}
/// Which schemas a [`completion_columns`] query reads.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CompletionScope<'a> {
/// Every non-system schema, capped at [`COMPLETION_ROW_CAP`] rows.
All,
/// One schema, in full.
Only(&'a str),
/// Every non-system schema but this one, capped at [`COMPLETION_ROW_CAP`] rows.
Except(&'a str),
}
/// Rows a [`CompletionScope::All`] or [`CompletionScope::Except`] query returns at most.
pub const COMPLETION_ROW_CAP: usize = 50_000;
/// Rows: `schema, table, kind (table/view), column, type, nullable (YES/NO), is_pk (0/1), has_default (0/1)`
/// for SQL completion, grouped by table in column order.
pub fn completion_columns(driver: DbDriver) -> &'static str {
match driver {
pub fn completion_columns(driver: DbDriver, scope: CompletionScope) -> String {
let (query, schema, order) = match driver {
DbDriver::Jdbc => unreachable!("JDBC introspection uses DatabaseMetaData"),
DbDriver::Clickhouse => {
DbDriver::Clickhouse => (
"SELECT c.database, c.table, CASE t.engine WHEN 'View' THEN 'view' \
WHEN 'MaterializedView' THEN 'materialized view' WHEN 'WindowView' THEN 'view' ELSE 'table' END, \
c.name, c.type, CASE WHEN startsWith(c.type, 'Nullable(') \
OR startsWith(c.type, 'LowCardinality(Nullable(') THEN 'YES' ELSE 'NO' END, c.is_in_primary_key, 1 \
FROM system.columns c JOIN system.tables t ON t.database = c.database AND t.name = c.table \
WHERE lower(c.database) NOT IN ('system', 'information_schema') AND t.is_temporary = 0 \
ORDER BY c.database, c.table, c.position LIMIT 50000"
}
DbDriver::Sqlite => {
WHERE lower(c.database) NOT IN ('system', 'information_schema') AND t.is_temporary = 0",
"c.database",
"c.database, c.table, c.position",
),
DbDriver::Sqlite => (
"SELECT 'main', m.name, m.type, p.name, p.type, CASE WHEN p.\"notnull\" = 0 THEN 'YES' ELSE 'NO' END, \
CASE WHEN p.pk > 0 THEN 1 ELSE 0 END, \
CASE WHEN p.dflt_value IS NOT NULL THEN 1 \
WHEN p.pk = 1 AND upper(p.type) = 'INTEGER' \
AND (SELECT count(*) FROM pragma_table_info(m.name) k WHERE k.pk > 0) = 1 THEN 1 ELSE 0 END \
FROM sqlite_master m JOIN pragma_table_info(m.name) p \
WHERE m.type IN ('table', 'view') AND m.name NOT LIKE 'sqlite\\_%' ESCAPE '\\' ORDER BY m.name, p.cid"
}
// Identity columns own their sequence through an internal dependency (`attidentity` is PostgreSQL 10+).
DbDriver::Postgres => {
WHERE m.type IN ('table', 'view') AND m.name NOT LIKE 'sqlite\\_%' ESCAPE '\\'",
"'main'",
"m.name, p.cid",
),
DbDriver::Postgres => (
"SELECT n.nspname, c.relname, CASE c.relkind WHEN 'v' THEN 'view' WHEN 'm' THEN 'materialized view' ELSE 'table' END, a.attname, \
format_type(a.atttypid, a.atttypmod), CASE WHEN a.attnotnull THEN 'NO' ELSE 'YES' END, \
CASE WHEN EXISTS (SELECT 1 FROM pg_index i WHERE i.indrelid = c.oid AND i.indisprimary \
@@ -287,19 +303,21 @@ pub fn completion_columns(driver: DbDriver) -> &'static str {
FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace JOIN pg_attribute a ON a.attrelid = c.oid \
WHERE c.relkind IN ('r', 'v', 'm', 'p', 'f') AND a.attnum > 0 AND NOT a.attisdropped \
AND n.nspname NOT IN ('pg_catalog', 'information_schema') \
AND n.nspname NOT LIKE 'pg\\_toast%' AND n.nspname NOT LIKE 'pg\\_temp%' \
ORDER BY n.nspname, c.relname, a.attnum LIMIT 50000"
}
DbDriver::Mysql => {
AND n.nspname NOT LIKE 'pg\\_toast%' AND n.nspname NOT LIKE 'pg\\_temp%'",
"n.nspname",
"n.nspname, c.relname, a.attnum",
),
DbDriver::Mysql => (
"SELECT c.table_schema, c.table_name, CASE WHEN t.table_type LIKE '%VIEW%' THEN 'view' ELSE 'table' END, \
c.column_name, c.column_type, c.is_nullable, CASE WHEN c.column_key = 'PRI' THEN 1 ELSE 0 END, \
CASE WHEN c.column_default IS NOT NULL OR c.extra LIKE '%auto_increment%' THEN 1 ELSE 0 END \
FROM information_schema.columns c JOIN information_schema.tables t \
ON t.table_schema = c.table_schema AND t.table_name = c.table_name \
WHERE c.table_schema NOT IN ('information_schema', 'mysql', 'performance_schema', 'sys') \
ORDER BY c.table_schema, c.table_name, c.ordinal_position LIMIT 50000"
}
DbDriver::SqlServer => {
WHERE c.table_schema NOT IN ('information_schema', 'mysql', 'performance_schema', 'sys')",
"c.table_schema",
"c.table_schema, c.table_name, c.ordinal_position",
),
DbDriver::SqlServer => (
"SELECT c.TABLE_SCHEMA, c.TABLE_NAME, CASE WHEN t.TABLE_TYPE LIKE '%VIEW%' THEN 'view' ELSE 'table' END, \
c.COLUMN_NAME, c.DATA_TYPE, c.IS_NULLABLE, \
CASE WHEN EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc \
@@ -310,19 +328,21 @@ pub fn completion_columns(driver: DbDriver) -> &'static str {
CASE WHEN c.COLUMN_DEFAULT IS NOT NULL THEN 1 ELSE 0 END \
FROM INFORMATION_SCHEMA.COLUMNS c JOIN INFORMATION_SCHEMA.TABLES t \
ON t.TABLE_SCHEMA = c.TABLE_SCHEMA AND t.TABLE_NAME = c.TABLE_NAME \
WHERE c.TABLE_SCHEMA NOT IN ('sys', 'INFORMATION_SCHEMA') \
ORDER BY c.TABLE_SCHEMA, c.TABLE_NAME, c.ORDINAL_POSITION"
}
DbDriver::Snowflake => {
WHERE c.TABLE_SCHEMA NOT IN ('sys', 'INFORMATION_SCHEMA')",
"c.TABLE_SCHEMA",
"c.TABLE_SCHEMA, c.TABLE_NAME, c.ORDINAL_POSITION",
),
DbDriver::Snowflake => (
"SELECT c.table_schema, c.table_name, CASE t.table_type WHEN 'VIEW' THEN 'view' \
WHEN 'MATERIALIZED VIEW' THEN 'materialized view' ELSE 'table' END, c.column_name, c.data_type, \
c.is_nullable, 0, CASE WHEN c.column_default IS NOT NULL THEN 1 ELSE 0 END \
FROM information_schema.columns c JOIN information_schema.tables t \
ON t.table_schema = c.table_schema AND t.table_name = c.table_name \
WHERE c.table_schema <> 'INFORMATION_SCHEMA' \
ORDER BY c.table_schema, c.table_name, c.ordinal_position LIMIT 50000"
}
DbDriver::Oracle => {
WHERE c.table_schema <> 'INFORMATION_SCHEMA'",
"c.table_schema",
"c.table_schema, c.table_name, c.ordinal_position",
),
DbDriver::Oracle => (
"SELECT c.owner, c.table_name, CASE WHEN v.view_name IS NOT NULL THEN 'view' ELSE 'table' END, \
c.column_name, c.data_type, DECODE(c.nullable, 'Y', 'YES', 'NO'), \
CASE WHEN k.column_name IS NOT NULL THEN 1 ELSE 0 END, \
@@ -334,10 +354,22 @@ pub fn completion_columns(driver: DbDriver) -> &'static str {
AND kc.constraint_name = con.constraint_name WHERE con.constraint_type = 'P') k \
ON k.owner = c.owner AND k.table_name = c.table_name AND k.column_name = c.column_name \
WHERE c.owner NOT IN ('CTXSYS', 'DBSFWUSER', 'DVSYS', 'GSMADMIN_INTERNAL', 'LBACSYS', 'MDDATA', \
'MDSYS', 'OLAPSYS', 'OUTLN', 'SYS', 'SYSTEM', 'XDB', 'XS$NULL') \
ORDER BY c.owner, c.table_name, c.column_id FETCH FIRST 50000 ROWS ONLY"
}
}
'MDSYS', 'OLAPSYS', 'OUTLN', 'SYS', 'SYSTEM', 'XDB', 'XS$NULL')",
"c.owner",
"c.owner, c.table_name, c.column_id",
),
};
let filter = match scope {
CompletionScope::All => String::new(),
CompletionScope::Only(s) => format!(" AND {schema} = {}", quote_literal(driver, s)),
CompletionScope::Except(s) => format!(" AND {schema} <> {}", quote_literal(driver, s)),
};
let cap = match (scope, driver) {
(CompletionScope::Only(_), _) | (_, DbDriver::Sqlite | DbDriver::SqlServer) => String::new(),
(_, DbDriver::Oracle) => format!(" FETCH FIRST {COMPLETION_ROW_CAP} ROWS ONLY"),
_ => format!(" LIMIT {COMPLETION_ROW_CAP}"),
};
format!("{query}{filter} ORDER BY {order}{cap}")
}
/// Rows: `schema, table, constraint, column, ref schema, ref table, ref column`
@@ -950,7 +982,7 @@ mod tests {
let keys = indexes(driver, "default", "events");
assert!(keys.contains("'PRIMARY KEY' AS index_name, 0 AS is_unique, primary_key AS expression"));
assert!(keys.contains("SELECT name, 0, expr FROM system.data_skipping_indices"));
let completion = completion_columns(driver);
let completion = completion_columns(driver, CompletionScope::All);
assert!(completion.contains("c.is_in_primary_key, 1"));
assert!(completion.contains("ORDER BY c.database, c.table, c.position LIMIT 50000"));
}
@@ -1060,7 +1092,7 @@ mod tests {
assert!(indexes(DbDriver::SqlServer, "dbo", "t").contains("sys.indexes"));
assert!(foreign_keys(DbDriver::SqlServer).contains("sys.foreign_key_columns"));
assert!(table_foreign_keys(DbDriver::SqlServer, "dbo", "t").contains("OBJECT_ID(N'[dbo].[t]')"));
assert!(completion_columns(DbDriver::SqlServer).contains("INFORMATION_SCHEMA.COLUMNS"));
assert!(completion_columns(DbDriver::SqlServer, CompletionScope::All).contains("INFORMATION_SCHEMA.COLUMNS"));
}
/// Under a case-sensitive or binary collation, catalog names only resolve as declared:
@@ -1074,7 +1106,7 @@ mod tests {
tables(d, "dbo"),
columns(d, "dbo", "t"),
indexes(d, "dbo", "t"),
completion_columns(d).to_owned(),
completion_columns(d, CompletionScope::All),
foreign_keys(d).to_owned(),
table_foreign_keys(d, "dbo", "t"),
routines(d, "dbo").unwrap(),
@@ -1141,7 +1173,7 @@ mod tests {
assert!(indexes(DbDriver::Oracle, "hr", "t").contains("all_indexes"));
assert!(foreign_keys(DbDriver::Oracle).contains("constraint_type = 'R'"));
assert!(table_foreign_keys(DbDriver::Oracle, "hr", "t").contains("all_cons_columns"));
assert!(completion_columns(DbDriver::Oracle).contains("all_tab_columns"));
assert!(completion_columns(DbDriver::Oracle, CompletionScope::All).contains("all_tab_columns"));
assert!(triggers(DbDriver::Oracle, "hr", "t").contains("all_triggers"));
assert!(routines(DbDriver::Oracle, "hr").unwrap().contains("all_objects"));
assert!(packages(DbDriver::Oracle, "hr").unwrap().contains("object_type = 'PACKAGE'"));
@@ -1256,7 +1288,7 @@ mod tests {
let columns = columns(driver, "PUBLIC", "ORDERS");
assert!(columns.contains("'NUMBER(' || numeric_precision"), "{columns}");
assert!(columns.contains("table_name = 'ORDERS' ORDER BY ordinal_position"), "{columns}");
assert!(completion_columns(driver).contains("LIMIT 50000"));
assert!(completion_columns(driver, CompletionScope::All).contains("LIMIT 50000"));
assert!(routines(driver, "PUBLIC").unwrap().contains("information_schema.procedures"));
assert!(sequences(driver, "PUBLIC").unwrap().contains("information_schema.sequences"));
assert_eq!(
@@ -1268,6 +1300,35 @@ mod tests {
assert_eq!(crate::plan::explain_statement(driver, "select 1;"), "EXPLAIN USING TABULAR select 1");
}
#[test]
fn completion_reads_the_default_schema_without_the_shared_cap() {
// #6118: 5,000+ tables in one Oracle schema overflowed the shared cap, so tables
// sorting last had no columns.
let only = completion_columns(DbDriver::Oracle, CompletionScope::Only("APP's"));
assert!(only.ends_with("AND c.owner = 'APP''s' ORDER BY c.owner, c.table_name, c.column_id"), "{only}");
let rest = completion_columns(DbDriver::Oracle, CompletionScope::Except("APP"));
assert!(rest.contains("AND c.owner <> 'APP' ORDER BY"), "{rest}");
assert!(rest.ends_with(" FETCH FIRST 50000 ROWS ONLY"), "{rest}");
let all = completion_columns(DbDriver::Oracle, CompletionScope::All);
assert!(all.ends_with("'XS$NULL') ORDER BY c.owner, c.table_name, c.column_id FETCH FIRST 50000 ROWS ONLY"));
for (driver, column) in [
(DbDriver::Postgres, "n.nspname"),
(DbDriver::Mysql, "c.table_schema"),
(DbDriver::Clickhouse, "c.database"),
(DbDriver::Snowflake, "c.table_schema"),
(DbDriver::SqlServer, "c.TABLE_SCHEMA"),
(DbDriver::Sqlite, "'main'"),
] {
let only = completion_columns(driver, CompletionScope::Only("app"));
assert!(only.contains(&format!(" AND {column} = 'app' ORDER BY ")), "{only}");
assert!(!only.contains("LIMIT") && !only.contains("FETCH FIRST"), "{only}");
let rest = completion_columns(driver, CompletionScope::Except("app"));
assert!(rest.contains(&format!(" AND {column} <> 'app' ORDER BY ")), "{rest}");
let capped = !matches!(driver, DbDriver::Sqlite | DbDriver::SqlServer);
assert_eq!(rest.ends_with(" LIMIT 50000"), capped, "{rest}");
}
}
#[test]
fn postgres_catalog_queries_run_on_older_servers() {
let pg = DbDriver::Postgres;
@@ -1279,7 +1340,7 @@ mod tests {
tables(pg, "s"),
columns(pg, "s", "t"),
indexes(pg, "s", "t"),
completion_columns(pg).to_owned(),
completion_columns(pg, CompletionScope::All),
foreign_keys(pg).to_owned(),
table_foreign_keys(pg, "s", "t"),
triggers(pg, "s", "t"),
@@ -1290,7 +1351,7 @@ mod tests {
let upper = q.to_uppercase();
assert!(!["LATERAL", "ORDINALITY", "ATTIDENTITY"].iter().any(|w| upper.contains(w)), "{q}");
}
assert_eq!(postgres_legacy(completion_columns(pg)), None);
assert_eq!(postgres_legacy(&completion_columns(pg, CompletionScope::All)), None);
let routines = postgres_legacy(&routines(pg, "s").unwrap()).unwrap();
assert!(!routines.contains("prokind") && routines.contains("NOT p.proisagg"));
assert_eq!(postgres_legacy(&indexes(pg, "s", "t")), None);
+37
Переглянути файл
@@ -779,3 +779,40 @@ async fn table_grants_expand_the_acl_per_grantee() -> IdeResult<()> {
}
Ok(())
}
/// Completion reads the default schema in full: 52,000 columns there passed the cap shared with
/// the other schemas, and the tables sorting last lost theirs (#6118).
#[tokio::test]
async fn completion_reads_every_column_of_a_wide_default_schema() -> IdeResult<()> {
let tmp = tempfile::tempdir().unwrap();
let Some(db) = manager(&tmp).await else { return Ok(()) };
let c = CancellationToken::new();
let schema = format!("oi_wide_{}", uuid::Uuid::new_v4().simple());
let mut sources = db.sources()?;
let mut source = sources[0].clone();
source.id = "wide".into();
source.options.startup_script = format!("SET search_path = {schema}");
sources.push(source);
let password = server().map(|(.., password)| password);
db.save_sources(sources).await?;
db.set_password("wide", password, false).await?;
db.execute("p", &format!("CREATE SCHEMA {schema}"), 1, &c).await?;
let fill = format!(
"DO $$ DECLARE cols text; BEGIN \
SELECT string_agg('c' || g || ' int', ', ') INTO cols FROM generate_series(1, 200) g; \
FOR i IN 1..260 LOOP EXECUTE format('CREATE TABLE {schema}.t%s (%s)', lpad(i::text, 3, '0'), cols); \
END LOOP; END $$"
);
let result = async {
db.execute("p", &fill, 1, &c).await?;
let completion = db.completion("wide").await?;
assert_eq!(completion.default_schema, schema);
let wide: Vec<_> = completion.tables.iter().filter(|t| t.schema == schema).collect();
assert_eq!(wide.len(), 260);
assert!(wide.iter().all(|t| t.columns.len() == 200), "a table lost columns");
Ok(())
}
.await;
db.execute("p", &format!("DROP SCHEMA {schema} CASCADE"), 1, &c).await?;
result
}
+1 -1
Переглянути файл
@@ -187,7 +187,7 @@ async fn sqlserver_introspection_works_under_a_case_sensitive_collation() {
let fk = ["dbo", "Child", "FK_Child_Parent", "ParentId", "dbo", "Parent", "Id"];
assert_eq!(cells(pool.rows(&sql::table_foreign_keys(d, "dbo", "Child"), 100).await.unwrap()), [fk]);
assert_eq!(cells(pool.rows(sql::foreign_keys(d), 100).await.unwrap()), [fk]);
assert_eq!(cells(pool.rows(sql::completion_columns(d), 100).await.unwrap()).len(), 4);
assert_eq!(cells(pool.rows(&sql::completion_columns(d, sql::CompletionScope::All), 100).await.unwrap()).len(), 4);
assert_eq!(cells(pool.rows(&sql::routines(d, "dbo").unwrap(), 100).await.unwrap())[0][..2], ["Touch", "procedure"]);
drop(pool);
master
+17 -9
Переглянути файл
@@ -46,18 +46,26 @@ fn main() {
#[cfg(unix)]
if args.first().is_some_and(|a| a == "--attach") {
let Some(project_path) = args.get(1).filter(|p| !p.is_empty()) else {
eprintln!("usage: openidea-server --attach <project-path>");
eprintln!("usage: openidea-server --attach <project-path> [--replace]");
std::process::exit(2);
};
// `--replace`: stop another build's backend that still holds the project.
let replace = args.get(2).is_some_and(|a| a == "--replace");
let home = dirs::home_dir().unwrap_or_default();
let code =
match ide_host::daemon::attach(&base, &home, project_path, std::io::stdin(), std::io::stdout().lock()) {
Ok(()) => 0,
Err(e) => {
eprintln!("{e}");
1
}
};
let code = match ide_host::daemon::attach(
&base,
&home,
project_path,
replace,
std::io::stdin(),
std::io::stdout().lock(),
) {
Ok(()) => 0,
Err(e) => {
eprintln!("{e}");
1
}
};
std::process::exit(code);
}
let mode = match args.as_slice() {
+84 -9
Переглянути файл
@@ -121,11 +121,13 @@ fn ensure_private_dir(dir: &Path) -> io::Result<()> {
}
/// Connects to the daemon for `project_path` (spawning it if needed) and bridges
/// `input` / `output` to its Unix socket.
/// `input` / `output` to its Unix socket. With `replace`, a daemon of another build that
/// refuses to retire is stopped first.
pub fn attach(
base: &Path,
home: &Path,
project_path: &str,
replace: bool,
input: impl Read + Send + 'static,
output: impl Write,
) -> Result<(), String> {
@@ -137,11 +139,11 @@ pub fn attach(
.map_err(|e| format!("cannot identify openidea-server build: {e}"))?;
let hex = hasher.finalize().to_hex();
let build = &hex.as_str()[..16];
let stream = connect_or_spawn(&exe, &paths, build)?;
let stream = connect_or_spawn(&exe, &paths, build, replace)?;
bridge(stream, input, output).map_err(|e| format!("daemon relay failed: {e}"))
}
fn connect_or_spawn(exe: &Path, paths: &DaemonPaths, build: &str) -> Result<UnixStream, String> {
fn connect_or_spawn(exe: &Path, paths: &DaemonPaths, build: &str, replace: bool) -> Result<UnixStream, String> {
let lock_file = OpenOptions::new()
.create(true)
.truncate(false)
@@ -153,8 +155,11 @@ fn connect_or_spawn(exe: &Path, paths: &DaemonPaths, build: &str) -> Result<Unix
flock(&lock_file, FlockOperation::LockExclusive)
.map_err(|e| format!("cannot lock {}: {e}", paths.lock.display()))?;
if let Some(stream) = existing_daemon(paths, build)? {
return Ok(stream);
match existing_daemon(paths, build) {
Ok(Some(stream)) => return Ok(stream),
Ok(None) => {}
Err(e) if replace && e.contains(rpc::OTHER_BUILD_BUSY) => stop_daemon(&paths.socket)?,
Err(e) => return Err(e),
}
match std::fs::remove_file(&paths.socket) {
@@ -232,10 +237,7 @@ fn existing_daemon(paths: &DaemonPaths, build: &str) -> Result<Option<UnixStream
Err(io::Error::other("unexpected response from stopping daemon"))
}
}
BUSY => Err(io::Error::other(
"Another build of OpenIDEA still has this project open, is running tasks, or has unsaved changes. \
Reconnect with that build, then stop the remote backend before upgrading.",
)),
BUSY => Err(io::Error::other(rpc::OTHER_BUILD_BUSY)),
_ => Err(io::Error::other("unrecognized remote backend response")),
}
};
@@ -247,6 +249,63 @@ fn existing_daemon(paths: &DaemonPaths, build: &str) -> Result<Option<UnixStream
exchange(stream).map_err(|e| format!("cannot attach to {}: {e}", paths.socket.display()))
}
/// Stops the daemon serving `socket` (another build's, which refused to retire): asks it to
/// shut down like the remote Stop Backend action does, and kills it if it hasn't after a while.
fn stop_daemon(socket: &Path) -> Result<(), String> {
let pids = daemon_pids(socket)?;
if pids.is_empty() {
return Err(format!("cannot find the backend serving {}", socket.display()));
}
let signal = |sig| {
for pid in &pids {
if let Some(pid) = rustix::process::Pid::from_raw(*pid) {
let _ = rustix::process::kill_process(pid, sig);
}
}
};
let alive = || pids.iter().any(|pid| process_exists(*pid));
signal(rustix::process::Signal::TERM);
let deadline = Instant::now() + rpc::SHUTDOWN_TIMEOUT;
while alive() && Instant::now() < deadline {
std::thread::sleep(Duration::from_millis(50));
}
if alive() {
signal(rustix::process::Signal::KILL);
std::thread::sleep(Duration::from_millis(200));
}
Ok(())
}
/// Whether `pid` still runs: an exited process its parent hasn't reaped yet (a zombie) doesn't.
fn process_exists(pid: i32) -> bool {
if !rustix::process::Pid::from_raw(pid).is_some_and(|pid| rustix::process::test_kill_process(pid).is_ok()) {
return false;
}
Command::new("ps")
.args(["-o", "stat=", "-p", &pid.to_string()])
.output()
.map_or(true, |out| !String::from_utf8_lossy(&out.stdout).trim_start().starts_with('Z'))
}
/// Processes started as `openidea-server --daemon <socket> <build>`.
fn daemon_pids(socket: &Path) -> Result<Vec<i32>, String> {
let out = Command::new("ps")
.args(["-axww", "-o", "pid=", "-o", "args="])
.output()
.map_err(|e| format!("cannot list processes: {e}"))?;
Ok(daemon_pids_in(&String::from_utf8_lossy(&out.stdout), &socket.to_string_lossy()))
}
fn daemon_pids_in(ps: &str, socket: &str) -> Vec<i32> {
ps.lines()
.filter_map(|line| {
let (pid, args) = line.trim_start().split_once(char::is_whitespace)?;
let mut words = args.split_whitespace().skip_while(|w| *w != "--daemon").skip(1);
(words.next() == Some(socket)).then(|| pid.parse().ok()).flatten()
})
.collect()
}
fn read_log_tail(file: &mut File, offset: u64) -> String {
if file.seek(SeekFrom::Start(offset)).is_err() {
return String::new();
@@ -480,3 +539,19 @@ fn has_live_work(host: &Host) -> bool {
.iter()
.any(|project| project.agents.has_live_work() || project.documents.has_unsaved_changes())
}
#[cfg(test)]
mod tests {
use super::daemon_pids_in;
#[test]
fn finds_the_daemon_of_a_socket_in_the_process_list() {
let ps = " 1 /sbin/init\n\
581660 /root/.openidea/server/0.1.51/634a/openidea-server --daemon /root/.openidea/run/s-de2d.sock 634a\n\
141712 /root/.openidea/server/0.1.53/e116/openidea-server --daemon /root/.openidea/run/s-a67f.sock e116\n\
582484 /bin/bash --init-file /tmp/openidea-shell-integration-0.1.51/bash/openidea.bashrc -i\n\
590000 grep --daemon /root/.openidea/run/s-de2d.sock.bak\n";
assert_eq!(daemon_pids_in(ps, "/root/.openidea/run/s-de2d.sock"), [581660]);
assert!(daemon_pids_in(ps, "/root/.openidea/run/s-none.sock").is_empty());
}
}
+1
Переглянути файл
@@ -378,6 +378,7 @@ impl Host {
self.mcp_reports.forget_window(window);
self.mcp_requests.forget_window(window);
self.mcp_agent_runs.forget_window(window);
self.debugger.forget_breakpoints(self.owner_window(window));
self.external_logs.write().remove(self.owner_window(window));
for request in self.project_requests.write().remove(self.owner_window(window)).unwrap_or_default() {
self.cancel_request(request);
+85 -5
Переглянути файл
@@ -32,12 +32,19 @@ pub async fn debug_start(host: &Host, window: &str, config: LaunchConfig) -> Ide
} else {
None
};
let mut config = config;
let enhanced = take_enhanced_redefinition(&mut config);
let java_exec = java_exec_path(&config);
let agents = if is_jvm_launch(&config) {
let mut agents = if is_jvm_launch(&config) {
ide_run::java_agent::current_for(java_exec.as_deref())
} else {
Default::default()
ide_run::java_agent::Agents::default()
};
match enhanced {
Some(Ok(option)) => agents.options.insert(0, option.to_owned()),
Some(Err(note)) => agents.notes.push(note),
None => {}
}
let config = add_java_agents(config, &agents.options);
let mut config = match_java_debug_encoding(start_java_attach_listener(config, cfg!(windows)), cfg!(windows));
if config.adapter == "debugpy"
@@ -249,6 +256,21 @@ fn java_exec_path(config: &LaunchConfig) -> Option<std::path::PathBuf> {
extra.get("javaExec").and_then(|v| v.as_str()).filter(|s| !s.is_empty()).map(std::path::PathBuf::from)
}
/// The configuration's Enhanced class redefinition (`enhancedClassRedefinition` in the launch
/// extras, which this removes): for a JVM the debugger starts, JetBrains Runtime's flag, or the
/// console line saying why the session runs without it.
fn take_enhanced_redefinition(config: &mut LaunchConfig) -> Option<Result<&'static str, String>> {
let Some(serde_json::Value::Object(mut extra)) =
config.extra_json.as_deref().and_then(|e| serde_json::from_str(e).ok())
else {
return None;
};
let on = extra.remove("enhancedClassRedefinition")?.as_bool() == Some(true);
config.extra_json = Some(serde_json::Value::Object(extra).to_string());
(on && is_jvm_launch(config))
.then(|| ide_run::java_hotswap::enhanced_redefinition(java_exec_path(config).as_deref()))
}
/// Plugins' Java agents ([`ide_run::java_agent`]) after the configuration's VM options:
/// java-debug's and java-analyzer's `vmArgs` (one line, or a list) or the Kotlin debugger's
/// `vmArguments` (a list).
@@ -380,13 +402,25 @@ fn match_java_debug_encoding(mut config: LaunchConfig, windows: bool) -> LaunchC
config
}
/// This window's breakpoints of `path`.
#[command(trust = trusted)]
pub async fn debug_set_breakpoints(
host: &Host,
window: &str,
path: PathBuf,
breakpoints: Vec<Breakpoint>,
) -> IdeResult<Vec<BreakpointState>> {
host.debugger.set_breakpoints(path, breakpoints).await
host.debugger.set_breakpoints(host.owner_window(window), path, breakpoints).await
}
/// Replaces all of this window's line breakpoints with `files`.
#[command(trust = trusted)]
pub async fn debug_replace_breakpoints(
host: &Host,
window: &str,
files: std::collections::BTreeMap<PathBuf, Vec<Breakpoint>>,
) -> IdeResult<()> {
host.debugger.replace_breakpoints(host.owner_window(window), files).await
}
#[command(trust = trusted)]
@@ -629,18 +663,20 @@ pub fn debug_capabilities(host: &Host, session: DebugSessionId) -> IdeResult<Deb
#[command(trust = trusted)]
pub async fn debug_set_function_breakpoints(
host: &Host,
window: &str,
breakpoints: Vec<FunctionBreakpoint>,
) -> IdeResult<Vec<BreakpointState>> {
host.debugger.set_function_breakpoints(breakpoints).await
host.debugger.set_function_breakpoints(host.owner_window(window), breakpoints).await
}
/// Field watchpoints; states aligned with `breakpoints`.
#[command(trust = trusted)]
pub async fn debug_set_data_breakpoints(
host: &Host,
window: &str,
breakpoints: Vec<DataBreakpoint>,
) -> IdeResult<Vec<BreakpointState>> {
host.debugger.set_data_breakpoints(breakpoints).await
host.debugger.set_data_breakpoints(host.owner_window(window), breakpoints).await
}
#[command(trust = trusted)]
@@ -916,6 +952,49 @@ mod tests {
assert_eq!(add_java_agents(config.clone(), &[]).extra_json, config.extra_json);
}
#[test]
fn enhanced_class_redefinition_is_taken_from_the_launch_extras() {
let tmp = tempfile::tempdir().unwrap();
let jdk = |name: &str, implementor: &str| {
let home = tmp.path().join(name);
std::fs::create_dir_all(home.join("bin")).unwrap();
std::fs::write(home.join("release"), format!("IMPLEMENTOR=\"{implementor}\"\n")).unwrap();
std::fs::write(home.join("bin/java"), "").unwrap();
home.join("bin/java").to_string_lossy().into_owned()
};
let (jbr, temurin) = (jdk("jbr", "JetBrains s.r.o."), jdk("temurin", "Eclipse Adoptium"));
let extras = |config: &LaunchConfig| {
serde_json::from_str::<serde_json::Value>(config.extra_json.as_deref().unwrap()).unwrap()
};
let mut config = launch(
"java-debug",
"launch",
serde_json::json!({"javaExec": jbr, "vmArgs": "-Xmx1g", "enhancedClassRedefinition": true}),
);
assert_eq!(take_enhanced_redefinition(&mut config), Some(Ok(ide_run::java_hotswap::OPTION)));
assert!(extras(&config).get("enhancedClassRedefinition").is_none(), "not passed on to the adapter");
assert_eq!(extras(&config)["vmArgs"], "-Xmx1g");
let mut config =
launch("java-debug", "launch", serde_json::json!({"javaExec": temurin, "enhancedClassRedefinition": true}));
let note = take_enhanced_redefinition(&mut config).unwrap().unwrap_err();
assert!(note.contains("is not a JetBrains Runtime"), "{note}");
let mut config = launch("java-debug", "launch", serde_json::json!({"enhancedClassRedefinition": true}));
assert!(take_enhanced_redefinition(&mut config).unwrap().unwrap_err().contains("is unknown"));
// Off, absent, or not a JVM the debugger starts: nothing to add, and no note.
for (adapter, request, extra) in [
("java-debug", "launch", serde_json::json!({"javaExec": jbr, "enhancedClassRedefinition": false})),
("java-debug", "launch", serde_json::json!({"javaExec": jbr})),
("java-debug", "attach", serde_json::json!({"javaExec": jbr, "enhancedClassRedefinition": true})),
] {
let mut config = launch(adapter, request, extra);
assert_eq!(take_enhanced_redefinition(&mut config), None);
assert!(extras(&config).get("enhancedClassRedefinition").is_none());
}
}
#[test]
fn debug_server_port_only_for_local_java_debug() {
let port = |adapter: &str, request: &str, extra| debug_server_port(&launch(adapter, request, extra));
@@ -962,6 +1041,7 @@ ide_command::domain!(
debug_listen_for_jvm,
debug_pause,
debug_redefine_classes,
debug_replace_breakpoints,
debug_resolve_variable,
debug_restart_frame,
debug_resume,
+3
Переглянути файл
@@ -222,6 +222,9 @@ impl Host {
ide_sdk::apply::configure_python_extra_paths(cfg, &paths);
}
if cfg.name == "jdtls" {
// Before anything reads the install the command resolves to.
let managed = ide_tools::tools_dir(&data_dir).join("jdtls").join("bin").join("jdtls");
ide_sdk::jdtls::skip_plain_launcher_wrappers(cfg, &managed);
// A workspace member keeps its build model under its own key (Build Project).
let cache = match &member {
Some(member) if member != window_root => build_cache.join(crate::project::project_key(member)),
+4
Переглянути файл
@@ -32,6 +32,10 @@ use std::sync::{Arc, OnceLock};
/// doesn't know the event would show stale output.
pub const PROTOCOL_VERSION: u32 = 4;
pub const SESSION_REPLACED: &str = "session_replaced";
/// What `openidea-server --attach` reports when another build's backend keeps the project
/// (clients match it to offer stopping that backend).
pub const OTHER_BUILD_BUSY: &str = "Another build of OpenIDEA still has this project open, is running tasks, or has \
unsaved changes. Reconnect with that build, or stop its backend and open the project again.";
pub const SHUTDOWN_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(90);
/// Advertised only by a persistent backend with an editable idle timeout.
+3 -18
Переглянути файл
@@ -27,24 +27,9 @@ async fn maven_launch_compiles_with_the_ides_java_build() {
let temp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(temp.path()).unwrap();
let root = base.join("project");
write(
&root,
"pom.xml",
r#"<project><modelVersion>4.0.0</modelVersion><groupId>t</groupId><artifactId>root</artifactId><version>1</version><packaging>pom</packaging>
<modules><module>lib</module><module>app</module></modules>
<properties><maven.compiler.release>11</maven.compiler.release><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties></project>"#,
);
write(
&root,
"lib/pom.xml",
r#"<project><modelVersion>4.0.0</modelVersion><parent><groupId>t</groupId><artifactId>root</artifactId><version>1</version></parent><artifactId>lib</artifactId></project>"#,
);
write(
&root,
"app/pom.xml",
r#"<project><modelVersion>4.0.0</modelVersion><parent><groupId>t</groupId><artifactId>root</artifactId><version>1</version></parent><artifactId>app</artifactId>
<dependencies><dependency><groupId>t</groupId><artifactId>lib</artifactId><version>1</version></dependency></dependencies></project>"#,
);
write(&root, "pom.xml", include_str!("../../ide-build/tests/fixtures/jbuild-maven/pom.xml"));
write(&root, "lib/pom.xml", include_str!("../../ide-build/tests/fixtures/jbuild-maven/lib/pom.xml"));
write(&root, "app/pom.xml", include_str!("../../ide-build/tests/fixtures/jbuild-maven/app/pom.xml"));
write(
&root,
"lib/src/main/java/l/L.java",
+55 -1
Переглянути файл
@@ -782,7 +782,7 @@ async fn upgraded_build_refuses_live_work_and_then_replaces_idle_backend() {
.unwrap()
.unwrap();
assert!(!rejected.status.success());
assert!(String::from_utf8_lossy(&rejected.stderr).contains("Another build of OpenIDEA"), "{rejected:?}");
assert!(String::from_utf8_lossy(&rejected.stderr).contains(ide_host::rpc::OTHER_BUILD_BUSY), "{rejected:?}");
assert!(previous_build.try_wait().unwrap().is_none(), "the live backend was replaced");
let resumed = old_open().await;
assert_eq!(invoke(&resumed, "term_list", json!({})).await.unwrap()[0]["id"], term["id"]);
@@ -798,6 +798,60 @@ async fn upgraded_build_refuses_live_work_and_then_replaces_idle_backend() {
shutdown(&new).await;
}
/// `--attach --replace` stops another build's backend that refuses to retire (#6119).
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn replace_stops_another_builds_busy_backend() {
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::UnixStream;
const OLD_BUILD: &str = "fedcba9876543210";
let tmp = tempfile::tempdir().unwrap();
let home = tmp.path().join("h");
let base = tmp.path().join("s");
let project = home.join("demo");
std::fs::create_dir_all(&project).unwrap();
let guard = DaemonGuard(ide_host::daemon::paths_for(&base, &home, "~/demo").unwrap().socket);
let mut previous_build = tokio::process::Command::new(SERVER)
.arg("--daemon")
.arg(&guard.0)
.arg(OLD_BUILD)
.envs(server_env(&home, &base, 10_800))
.kill_on_drop(true)
.spawn()
.unwrap();
until("old backend socket", || guard.0.exists()).await;
let mut stream = 'connect: {
for _ in 0..600 {
match UnixStream::connect(&guard.0).await {
Err(e) if e.kind() == std::io::ErrorKind::ConnectionRefused => {
tokio::time::sleep(Duration::from_millis(15)).await;
}
other => break 'connect other.unwrap(),
}
}
panic!("the old backend never accepted a connection");
};
stream.write_all(OLD_BUILD.as_bytes()).await.unwrap();
assert_eq!(stream.read_u8().await.unwrap(), b'A');
let (reader, writer) = stream.into_split();
let old = Peer::connect(reader, writer, Arc::new(Client::default()));
initialize(&old).await;
let term = looping_terminal(&old, &project).await;
old.kill();
old.closed().await;
let client = Arc::new(Client::default());
let args = ["--attach", "~/demo", "--replace"].map(str::to_owned).to_vec();
let env = server_env(&home, &base, 10_800);
let new = Peer::spawn(SERVER, &args, &home, &env, client, Box::new(|line| eprintln!("{line}"))).unwrap();
initialize(&new).await;
let old_exit = tokio::time::timeout(Duration::from_secs(15), previous_build.wait()).await.unwrap().unwrap();
assert!(old_exit.success(), "the old backend did not shut down cleanly: {old_exit:?}");
until("its terminal stopped", || !pid_alive(term["pid"].as_u64().unwrap() as u32)).await;
assert!(invoke(&new, "term_list", json!({})).await.unwrap().as_array().unwrap().is_empty());
shutdown(&new).await;
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
#[ignore = "requires a Docker context with Docker Compose and the busybox image"]
async fn compose_service_survives_disconnect_and_is_removed_on_stop() {
+63
Переглянути файл
@@ -0,0 +1,63 @@
//! Enhanced class redefinition for Java debug sessions: on JetBrains Runtime,
//! `-XX:+AllowEnhancedClassRedefinition` lets HotSwap (Reload Changed Classes) apply
//! structural changes such as added or removed methods and fields. Other JVMs refuse to
//! start with the flag, so it is added only when the launched JDK is JetBrains Runtime.
use std::path::Path;
/// The JVM flag JetBrains Runtime takes.
pub const OPTION: &str = "-XX:+AllowEnhancedClassRedefinition";
/// The flag when `java` (the launched `bin/java`; `None` when unknown) is JetBrains Runtime,
/// else the console line saying why the session runs without it.
pub fn enhanced_redefinition(java: Option<&Path>) -> Result<&'static str, String> {
let java = java.filter(|java| java.components().count() > 1);
match java {
Some(java) if crate::java_agent::jdk_allows(Some(java), Some("jetbrains")) => Ok(OPTION),
Some(java) => Err(format!(
"Enhanced class redefinition is off for this session: {} is not a JetBrains Runtime. \
Choose a JetBrains Runtime as the configuration's JRE.",
java.display()
)),
None => Err("Enhanced class redefinition is off for this session: the JDK it runs on is unknown. \
Choose a JetBrains Runtime as the configuration's JRE."
.to_owned()),
}
}
#[cfg(test)]
mod tests {
use super::*;
fn jdk(dir: &Path, implementor: &str) -> std::path::PathBuf {
let bin = dir.join("bin");
std::fs::create_dir_all(&bin).unwrap();
std::fs::write(dir.join("release"), format!("JAVA_VERSION=\"21\"\nIMPLEMENTOR=\"{implementor}\"\n")).unwrap();
let java = bin.join("java");
std::fs::write(&java, "").unwrap();
java
}
#[test]
fn jetbrains_runtime_gets_the_flag() {
let tmp = tempfile::tempdir().unwrap();
let java = jdk(tmp.path(), "JetBrains s.r.o.");
assert_eq!(enhanced_redefinition(Some(&java)), Ok(OPTION));
}
#[test]
fn other_jdks_get_a_note_instead() {
let tmp = tempfile::tempdir().unwrap();
let java = jdk(tmp.path(), "Eclipse Adoptium");
let note = enhanced_redefinition(Some(&java)).unwrap_err();
assert!(note.contains("is not a JetBrains Runtime"), "{note}");
assert!(note.contains(&java.display().to_string()), "{note}");
}
#[test]
fn an_unknown_jdk_gets_a_note() {
assert!(enhanced_redefinition(None).unwrap_err().contains("is unknown"));
// A bare `java` names no JDK.
assert!(enhanced_redefinition(Some(Path::new("java"))).unwrap_err().contains("is unknown"));
}
}
+1
Переглянути файл
@@ -10,6 +10,7 @@ pub mod gradle_jvm;
pub mod import;
pub mod java_agent;
pub mod java_cmdline;
pub mod java_hotswap;
pub mod junit;
mod process;
pub mod python_path;
+90
Переглянути файл
@@ -228,6 +228,45 @@ pub fn java_args(install: &JdtlsInstall, java_major: u32, script_args: &[String]
args
}
/// Whether `script` is a hand-written `jdtls` that starts the Equinox launcher with `java -jar`
/// itself, like the one opencode puts into a JDK's `bin` (#6062). It knows none of the release
/// script's options: each `--jvm-arg=` (the Lombok agent, heap, proxy) reaches jdtls as an
/// application argument instead of a JVM option, and its own `-data` comes before the IDE's.
fn is_plain_launcher_wrapper(script: &Path) -> bool {
if std::fs::metadata(script).map_or(true, |m| m.len() > 64 * 1024) {
return false;
}
let Ok(bytes) = std::fs::read(script) else { return false };
let text = String::from_utf8_lossy(&bytes);
text.contains("org.eclipse.equinox.launcher") && !text.contains("--jvm-arg")
}
/// Picks the `jdtls` to start when the first one on `PATH` is a [plain launcher
/// wrapper](is_plain_launcher_wrapper): the next one there that isn't, else the IDE's own
/// install (`managed`, `<tools>/jdtls/bin/jdtls`), which is offered for install while missing.
/// A command naming a path is the user's choice and kept.
pub fn skip_plain_launcher_wrappers(cfg: &mut LanguageServerConfig, managed: &Path) {
if cfg.name != "jdtls" || Path::new(&cfg.command).components().count() != 1 {
return;
}
let search = cfg.env.get("PATH").map(std::ffi::OsString::from).unwrap_or_else(ide_core::tool_path::search_path);
let mut candidates = std::env::split_paths(&search)
.filter(|dir| !dir.as_os_str().is_empty())
.filter_map(|dir| ide_core::process::find_executable(&cfg.command, dir.as_os_str()));
let Some(first) = candidates.next() else { return };
if !is_plain_launcher_wrapper(&first) {
return;
}
let chosen = candidates.find(|c| !is_plain_launcher_wrapper(c)).unwrap_or_else(|| managed.to_path_buf());
tracing::warn!(
"{} starts jdtls with `java -jar` itself and ignores the IDE's JVM arguments (Lombok agent, \
workspace); using {} instead",
first.display(),
chosen.display()
);
cfg.command = chosen.to_string_lossy().into_owned();
}
/// The release script a `jdtls` command on `PATH` resolves to: itself when it
/// already is one, or the script its Scoop shim launches. `None` for a command
/// that is neither a release script nor a jdtls Scoop shim.
@@ -560,6 +599,57 @@ mod tests {
assert_eq!(find_install(home, "macos", "aarch64").unwrap().config, home.join("config_mac_arm"));
}
#[test]
fn a_plain_java_jar_wrapper_first_on_path_is_skipped() {
let dir = tempfile::tempdir().unwrap();
let exe = |dir: &Path, text: &str| {
std::fs::create_dir_all(dir).unwrap();
let name = if cfg!(windows) { "jdtls.cmd" } else { "jdtls" };
std::fs::write(dir.join(name), text).unwrap();
#[cfg(unix)]
std::fs::set_permissions(dir.join(name), std::os::unix::fs::PermissionsExt::from_mode(0o755)).unwrap();
dir.join(name)
};
// opencode's wrapper (#6062), then a release script.
let wrapper = exe(
&dir.path().join("jdk/bin"),
"\"%JAVA_HOME%\\bin\\java\" -jar \"%JDTLS_HOME%\\plugins\\org.eclipse.equinox.launcher_1.7.100.jar\" -data \"%DATA_DIR%\" %*\n",
);
let release = exe(
&dir.path().join("jdtls/bin"),
"parser.add_argument('--jvm-arg', action='append')\nlauncher = 'org.eclipse.equinox.launcher_*.jar'\n",
);
let managed = dir.path().join("tools/jdtls/bin/jdtls");
let cfg = |dirs: &[&Path]| -> LanguageServerConfig {
let mut cfg: LanguageServerConfig = toml::from_str("name = \"jdtls\"\ncommand = \"jdtls\"").unwrap();
let path = std::env::join_paths(dirs.iter().map(|d| d.parent().unwrap())).unwrap();
cfg.env.insert("PATH".into(), path.to_string_lossy().into_owned());
cfg
};
let mut next = cfg(&[&wrapper, &release]);
skip_plain_launcher_wrappers(&mut next, &managed);
assert_eq!(Path::new(&next.command), release);
let mut only = cfg(&[&wrapper]);
skip_plain_launcher_wrappers(&mut only, &managed);
assert_eq!(Path::new(&only.command), managed, "the IDE's install, offered while missing");
let mut release_first = cfg(&[&release, &wrapper]);
skip_plain_launcher_wrappers(&mut release_first, &managed);
assert_eq!(release_first.command, "jdtls");
// Wrappers that delegate (Homebrew's, a Scoop shim) and named commands are kept.
let brew = exe(&dir.path().join("brew/bin"), "#!/bin/bash\nexec \"/opt/jdtls/libexec/bin/jdtls\" \"$@\"\n");
let mut delegating = cfg(&[&brew, &release]);
skip_plain_launcher_wrappers(&mut delegating, &managed);
assert_eq!(delegating.command, "jdtls");
let mut named = cfg(&[&wrapper]);
named.command = wrapper.to_string_lossy().into_owned();
skip_plain_launcher_wrappers(&mut named, &managed);
assert_eq!(Path::new(&named.command), wrapper);
}
#[cfg(unix)]
#[test]
fn rewrites_the_release_script_to_java() {
+9 -3
Переглянути файл
@@ -24,7 +24,7 @@ pub(crate) fn block_history(
crate::repo::blob_at(&repo, &rel, "HEAD")?
};
let Some(head) = head else {
return Ok(BlockHistory { head_lines: None, revisions: Vec::new() });
return Ok(BlockHistory { head_lines: None, head: None, revisions: Vec::new() });
};
let head = decode(&head, encoding);
let current = match current_text {
@@ -32,12 +32,18 @@ pub(crate) fn block_history(
None => decode(&std::fs::read(r.abs_path(&rel))?, encoding).into_owned(),
};
let Some((start, end)) = head_range(&crate::diff::line_hunks(&head, &current), lines) else {
return Ok(BlockHistory { head_lines: None, revisions: Vec::new() });
return Ok(BlockHistory { head_lines: None, head: None, revisions: Vec::new() });
};
let range = format!("-L{},{}:{rel}", start + 1, end + 1);
let args = ["log", "--no-color", "--no-ext-diff", "--no-textconv", FORMAT, &range, "HEAD"];
let out = cli::run_cancellable(r.root(), &args, cancel)?;
Ok(BlockHistory { head_lines: Some((start, end)), revisions: parse_log(&out.stdout, encoding) })
// The newest row's block can't stand in for HEAD's: a merge row has none.
let mut block = String::new();
for line in head.lines().skip(start as usize).take((end - start) as usize + 1) {
push_line(&mut block, line);
}
let revisions = parse_log(&out.stdout, encoding);
Ok(BlockHistory { head_lines: Some((start, end)), head: Some(block), revisions })
}
/// The HEAD lines (0-based, inclusive) of `lines` in the current text, given the
+3
Переглянути файл
@@ -139,6 +139,9 @@ pub struct BlameLine {
pub struct BlockHistory {
/// The selected lines in HEAD (0-based, inclusive); None when none of them is committed.
pub head_lines: Option<(u32, u32)>,
/// Those lines as HEAD has them, each ending with `\n`; None from servers that predate it.
#[serde(default)]
pub head: Option<String>,
pub revisions: Vec<BlockRevision>,
}
+23 -1
Переглянути файл
@@ -76,6 +76,8 @@ fn follows_the_block_through_edits_and_a_rename() {
let fx = renamed_history();
let h = history(&fx.repo(), &fx.path("b.txt"), None, (1, 2));
assert_eq!(h.head_lines, Some((1, 2)));
// Without a merge on top, HEAD's block is the newest row's.
assert_eq!(h.head.as_deref(), Some(h.revisions[0].after.as_str()));
let shown: Vec<_> = h.revisions.iter().map(|r| (r.summary.as_str(), r.path.as_str())).collect();
// Edits outside the block and the pure rename are left out.
assert_eq!(shown, [("Shout three", "b.txt"), ("Shout two", "a.txt"), ("Add a", "a.txt")]);
@@ -86,6 +88,26 @@ fn follows_the_block_through_edits_and_a_rename() {
assert!(newest.id.starts_with(&newest.short_id) && newest.time_ms > 0.0);
}
#[test]
fn newest_row_a_merge_without_a_diff() {
let fx = Fixture::new();
fx.write("a.txt", "a\nb\nc\nd\n");
fx.commit("Add a");
fx.git(&["switch", "-q", "-c", "side"]);
fx.write("a.txt", "A\nb\nc\nd\n");
fx.commit("Side edit");
fx.git(&["switch", "-q", "main"]);
fx.write("a.txt", "a\nb\nc\nD\n");
fx.commit("Main edit");
fx.git(&["merge", "-q", "--no-edit", "side"]);
let h = history(&fx.repo(), &fx.path("a.txt"), None, (0, 3));
let newest = &h.revisions[0];
assert!(newest.summary.starts_with("Merge"), "{newest:?}");
// Git prints no patch for the merge, so its block says nothing about HEAD.
assert_eq!((newest.before.as_str(), newest.after.as_str()), ("", ""));
assert_eq!(h.head.as_deref(), Some("A\nb\nc\nD\n"));
}
#[test]
fn maps_an_edited_selection_to_head_lines() {
let fx = renamed_history();
@@ -93,7 +115,7 @@ fn maps_an_edited_selection_to_head_lines() {
// Two unsaved lines inserted at the top: lines 3..=4 are HEAD's 1..=2.
let edited = "new\nnew\none\nTWO\nTHREE\nfour\nFIVE\n";
let h = history(&repo, &fx.path("b.txt"), Some(edited), (3, 4));
assert_eq!(h.head_lines, Some((1, 2)));
assert_eq!((h.head_lines, h.head.as_deref()), (Some((1, 2)), Some("TWO\nTHREE\n")));
assert_eq!(h.revisions.len(), 3);
// Only new lines selected, or a file Git does not know: nothing committed to show.
let h = history(&repo, &fx.path("b.txt"), Some(edited), (0, 1));
+35
Переглянути файл
@@ -0,0 +1,35 @@
import { EditorView } from "@codemirror/view";
import { commands } from "../src/platform/ipc";
import { setInvokeRoute } from "../src/platform/tauriCore";
import { schemeCss } from "../src/platform/colorScheme";
import { lspDoc } from "../src/editor/lsp/lsp";
import { semanticExtension } from "../src/editor/lsp/semantic";
import { lspTheme } from "../src/editor/lsp/theme";
setInvokeRoute(() => null);
commands.lspSemanticTokens = async () => ({
status: "ok",
data: {
tokenTypes: ["namespace"],
tokenModifiers: ["defaultLibrary", "globalScope"],
data: [0, 0, 7, 0, 2, 1, 0, 3, 0, 3],
},
});
const mode = new URLSearchParams(location.search).has("light") ? "light" : "dark";
const style = document.createElement("style");
style.textContent = schemeCss(mode, {
[mode]: {
packageReference: { foreground: "#446688" },
predefined: { foreground: "#cc5500" },
},
});
document.head.append(style);
new EditorView({
parent: document.body,
doc: "example::hello();\nstd::cout << 1;",
extensions: [
lspTheme,
lspDoc.of({ doc: 1, path: "demo.cpp", language: "cpp", uiMode: "C++", readOnly: false }),
semanticExtension(),
],
});
+9
Переглянути файл
@@ -0,0 +1,9 @@
<!doctype html>
<html>
<head>
<meta charset="UTF-8" />
</head>
<body>
<script type="module" src="./cppNamespaceStyle.fixture.ts"></script>
</body>
</html>
+12
Переглянути файл
@@ -0,0 +1,12 @@
import { expect, test } from "@playwright/test";
for (const mode of ["dark", "light"]) {
test(`C++ standard and user namespaces share the namespace colour (${mode})`, async ({ page }) => {
await page.goto(`/e2e/cppNamespaceStyle.html${mode === "light" ? "?light" : ""}`);
const namespaces = page.locator(".cm-sem-namespace");
await expect(namespaces).toHaveCount(2);
for (const namespace of await namespaces.all()) {
await expect(namespace).toHaveCSS("color", "rgb(68, 102, 136)");
}
});
}
+2 -1
Переглянути файл
@@ -78,7 +78,8 @@ test("precise filter values are ordered and filtering composes with result sorti
const values = page.getByRole("group", { name: "Values", exact: true });
const ascending = [integers[3]!, integers[2]!, integers[1]!, integers[0]!];
await expect(values.locator("label")).toHaveText(ascending);
await values.getByRole("checkbox", { name: integers[3], exact: true }).uncheck();
// Checked values are the rows shown.
for (const value of ascending.slice(1)) await values.getByRole("checkbox", { name: value, exact: true }).check();
await page.keyboard.press("Escape");
await grid
.getByRole("columnheader", { name: /^value\b/ })
+47
Переглянути файл
@@ -0,0 +1,47 @@
// @vitest-environment node
import { describe, expect, it } from "vitest";
import { dmgName, renderCask, stableVersion } from "./homebrew-cask.ts";
const ARM = "5fc404ab470bb9ca5168ab5d1769ad5892d657a8992fb26adf192f2c60bd8279";
const INTEL = "38b3b06bbbc46503889ab43f16131f87037d3499cac7792e9fc221bcaac0bc05";
describe("stableVersion", () => {
it("takes the version of a stable tag", () => {
expect(stableVersion("v0.1.51")).toBe("0.1.51");
});
it("skips prereleases and other refs", () => {
expect(stableVersion("v0.2.0-beta.1")).toBeNull();
expect(stableVersion("0.1.51")).toBeNull();
expect(stableVersion("main")).toBeNull();
});
});
describe("dmgName", () => {
it("names the release's DMG of each arch", () => {
expect(dmgName("0.1.51", "arm")).toBe("OpenIDEA_0.1.51_aarch64.dmg");
expect(dmgName("0.1.51", "intel")).toBe("OpenIDEA_0.1.51_x64.dmg");
});
});
describe("renderCask", () => {
it("pins the version and the checksum of each arch", () => {
const cask = renderCask("0.1.51", { arm: ARM, intel: INTEL });
expect(cask).toContain(`version "0.1.51"`);
expect(cask).toContain(`sha256 arm: "${ARM}",\n intel: "${INTEL}"`);
expect(cask).toContain(
`url "https://github.com/l0ng-ai/openidea/releases/download/v#{version}/OpenIDEA_#{version}_#{arch}.dmg"`,
);
});
it("leaves updates to the app and installs the CLI", () => {
const cask = renderCask("0.1.51", { arm: ARM, intel: INTEL });
expect(cask).toContain("auto_updates true");
expect(cask).toContain(`binary "#{appdir}/OpenIDEA.app/Contents/Resources/bin/openidea"`);
expect(cask).toContain(`"~/Library/Application Support/ai.l0ng.openidea"`);
});
it("refuses a checksum that isn't SHA-256", () => {
expect(() => renderCask("0.1.51", { arm: ARM, intel: "abc" })).toThrow(/intel/);
});
});
+105
Переглянути файл
@@ -0,0 +1,105 @@
/**
* Writes the Homebrew cask for a published release:
* `node scripts/homebrew-cask.ts <tag> <dir> <out>`. `<dir>` holds the release's macOS DMGs
* (`gh release download <tag> -p '*.dmg'`); `<out>` is the cask file to write, e.g.
* `Casks/openidea.rb` in a checkout of the tap (l0ng-ai/homebrew-tap). The cask lets the app
* update itself (`auto_updates true`): the Tauri updater and `brew upgrade` don't fight.
*/
import { createHash } from "node:crypto";
import { createReadStream, existsSync, mkdirSync, writeFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
const GITHUB_REPO = "l0ng-ai/openidea";
const IDENTIFIER = "ai.l0ng.openidea";
/** The DMG of each Homebrew arch, as the release names it. */
export const DMG_ARCH = { arm: "aarch64", intel: "x64" } as const;
export interface Checksums {
arm: string;
intel: string;
}
/** The version of a stable release tag (`v0.1.51` → `0.1.51`); prereleases have none. */
export function stableVersion(tag: string): string | null {
const match = /^v(\d+\.\d+\.\d+)$/.exec(tag);
return match ? match[1]! : null;
}
export function dmgName(version: string, arch: keyof typeof DMG_ARCH): string {
return `OpenIDEA_${version}_${DMG_ARCH[arch]}.dmg`;
}
export function renderCask(version: string, sha256: Checksums): string {
for (const [arch, sum] of Object.entries(sha256)) {
if (!/^[0-9a-f]{64}$/.test(sum)) throw new Error(`${arch}: ${sum} is not a SHA-256`);
}
return `cask "openidea" do
arch arm: "${DMG_ARCH.arm}", intel: "${DMG_ARCH.intel}"
version "${version}"
sha256 arm: "${sha256.arm}",
intel: "${sha256.intel}"
url "https://github.com/${GITHUB_REPO}/releases/download/v#{version}/OpenIDEA_#{version}_#{arch}.dmg"
name "OpenIDEA"
desc "IDE inspired by IntelliJ IDEA, rebuilt in Rust"
homepage "https://openidea.sh/"
livecheck do
url :url
strategy :github_latest
end
auto_updates true
depends_on :macos
app "OpenIDEA.app"
binary "#{appdir}/OpenIDEA.app/Contents/Resources/bin/openidea"
zap trash: [
"~/Library/Application Support/${IDENTIFIER}",
"~/Library/Caches/${IDENTIFIER}",
"~/Library/HTTPStorages/${IDENTIFIER}",
"~/Library/Logs/${IDENTIFIER}",
"~/Library/Preferences/${IDENTIFIER}.plist",
"~/Library/Saved Application State/${IDENTIFIER}.savedState",
"~/Library/WebKit/${IDENTIFIER}",
]
end
`;
}
function sha256File(path: string): Promise<string> {
return new Promise((resolve, reject) => {
const hash = createHash("sha256");
createReadStream(path)
.on("data", (chunk) => hash.update(chunk))
.on("error", reject)
.on("end", () => resolve(hash.digest("hex")));
});
}
async function main() {
const [tag, dir, out] = process.argv.slice(2);
if (!tag || !dir || !out) throw new Error("usage: node scripts/homebrew-cask.ts <tag> <dir> <out>");
const version = stableVersion(tag);
if (!version) throw new Error(`${tag} is not a stable release tag`);
const sum = async (arch: keyof typeof DMG_ARCH) => {
const path = join(dir, dmgName(version, arch));
if (!existsSync(path)) throw new Error(`${path} is missing`);
return sha256File(path);
};
const cask = renderCask(version, { arm: await sum("arm"), intel: await sum("intel") });
mkdirSync(dirname(out), { recursive: true });
writeFileSync(out, cask);
console.log(`wrote ${out} for OpenIDEA ${version}`);
}
if (process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]) {
main().catch((e) => {
console.error(e instanceof Error ? e.message : e);
process.exit(1);
});
}
+1
Переглянути файл
@@ -31,6 +31,7 @@ serde_json.workspace = true
base64.workspace = true
percent-encoding = "2"
tokio.workspace = true
reqwest.workspace = true
parking_lot.workspace = true
blake3.workspace = true
tracing.workspace = true
+69 -35
Переглянути файл
@@ -597,7 +597,19 @@ fn source_endpoints(official: Vec<String>, source: UpdateSource) -> Vec<String>
}
}
fn updater(app: &AppHandle, source: UpdateSource) -> IdeResult<Option<tauri_plugin_updater::Updater>> {
/// Bounds connection establishment (TCP and TLS) for the updater. reqwest divides this
/// across a host's resolved addresses, so a CDN hostname with four A records gets about
/// 3.75s each — enough for a slow link, while still leaving the 60s check budget intact.
const UPDATER_CONNECT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(15);
fn configure_updater_client(
builder: reqwest::ClientBuilder,
proxy: &ide_core::proxy_settings::ProxySettings,
) -> reqwest::ClientBuilder {
ide_http::client::with_proxy(builder, proxy).connect_timeout(UPDATER_CONNECT_TIMEOUT)
}
pub(crate) fn updater(app: &AppHandle, source: UpdateSource) -> IdeResult<Option<tauri_plugin_updater::Updater>> {
use tauri_plugin_updater::UpdaterExt;
if !updates_configured(app) {
return Ok(None);
@@ -620,7 +632,7 @@ fn updater(app: &AppHandle, source: UpdateSource) -> IdeResult<Option<tauri_plug
builder = builder.target(target);
}
builder
.configure_client(move |b| ide_http::client::with_proxy(b, &proxy))
.configure_client(move |b| configure_updater_client(b, &proxy))
.endpoints(endpoints)
.map_err(|e| IdeError::invalid(e.to_string()))?
.build()
@@ -695,24 +707,23 @@ pub enum UpdateProgress {
/// Limits download events to one per whole percent (or per 256 KiB without a length).
#[derive(Default)]
struct ProgressThrottle {
downloaded: u64,
last_step: Option<u64>,
}
impl ProgressThrottle {
const UNKNOWN_STEP: u64 = 256 * 1024;
fn chunk(&mut self, len: usize, total: Option<u64>) -> Option<UpdateProgress> {
self.downloaded += len as u64;
/// Converts the downloader's absolute byte count into a throttled event.
fn report(&mut self, downloaded: u64, total: Option<u64>) -> Option<UpdateProgress> {
let step = match total {
Some(t) if t > 0 => self.downloaded.min(t) * 100 / t,
_ => self.downloaded / Self::UNKNOWN_STEP,
Some(t) if t > 0 => downloaded.min(t) * 100 / t,
_ => downloaded / Self::UNKNOWN_STEP,
};
if self.last_step == Some(step) {
return None;
}
self.last_step = Some(step);
Some(UpdateProgress::Downloading { downloaded: self.downloaded as f64, total: total.map(|t| t as f64) })
Some(UpdateProgress::Downloading { downloaded: downloaded as f64, total: total.map(|t| t as f64) })
}
}
@@ -750,28 +761,22 @@ pub async fn app_install_update(
InstallingGuard::acquire().ok_or_else(|| IdeError::unavailable("an update is already being installed"))?;
let token = state.host.begin_request(request);
let result = async {
let updater = updater(&app, source)?.ok_or_else(|| IdeError::unavailable("updates are not configured"))?;
let update = tokio::select! {
r = updater.check() => r.map_err(|e| IdeError::unavailable(e.to_string()))?,
_ = token.cancelled() => return Err(IdeError::cancelled()),
}
.ok_or_else(|| IdeError::not_found("no update available"))?;
let mut throttle = ProgressThrottle::default();
let progress = on_progress.clone();
let download = update.download(
move |len, total| {
if let Some(p) = throttle.chunk(len, total) {
let downloaded = tokio::select! {
result = crate::updates::download_update(&app, source, &token, move |done, total| {
if let Some(p) = throttle.report(done, total) {
let _ = progress.send(p);
}
},
|| {},
);
let bytes = tokio::select! {
r = download => r.map_err(|e| IdeError::unavailable(e.to_string()))?,
}) => result?,
_ = token.cancelled() => return Err(IdeError::cancelled()),
};
let crate::updates::DownloadedUpdate { update, bytes, path } = downloaded;
if token.is_cancelled() {
return Err(IdeError::cancelled());
}
let _ = on_progress.send(UpdateProgress::Installing);
tauri::async_runtime::spawn_blocking(move || {
let installed = tauri::async_runtime::spawn_blocking(move || {
#[cfg(windows)]
if update.target.ends_with("-portable") {
let exe = tauri::utils::platform::current_exe()?;
@@ -780,7 +785,11 @@ pub async fn app_install_update(
update.install(bytes).map_err(|e| IdeError::internal(e.to_string()))
})
.await
.map_err(|e| IdeError::internal(e.to_string()))?
.map_err(|e| IdeError::internal(e.to_string()))?;
if installed.is_ok() {
let _ = tokio::fs::remove_file(path).await;
}
installed
}
.await;
state.host.end_request(request);
@@ -793,7 +802,9 @@ pub async fn app_install_update(
/// can show the UI's language and fall back to English. An install records the
/// notes it saw, so this is only for an update installed outside the app.
/// `Ok(None)` when the manifest covers another version or carries no notes.
#[desktop_command(trust = trusted)]
/// Reads only the public manifest, like the update check: the page usually opens
/// in a window without a project.
#[desktop_command(trust = always)]
#[tauri::command]
#[specta::specta]
pub async fn app_release_notes(
@@ -909,22 +920,33 @@ mod tests {
#[test]
fn throttle_reports_each_whole_percent_once() {
let mut t = ProgressThrottle::default();
assert_eq!(downloading(t.chunk(1, Some(1000))), Some((1.0, Some(1000.0))));
assert_eq!(downloading(t.chunk(5, Some(1000))), None);
assert_eq!(downloading(t.chunk(4, Some(1000))), Some((10.0, Some(1000.0))));
let reported = (0..99).filter(|_| t.chunk(10, Some(1000)).is_some()).count();
assert_eq!(reported, 99);
assert_eq!(t.downloaded, 1000);
assert_eq!(downloading(t.report(1, Some(1000))), Some((1.0, Some(1000.0))));
assert_eq!(downloading(t.report(9, Some(1000))), None);
assert_eq!(downloading(t.report(10, Some(1000))), Some((10.0, Some(1000.0))));
let reported = (11..=100).filter(|percent| t.report(percent * 10, Some(1000)).is_some()).count();
assert_eq!(reported, 90);
}
#[test]
fn throttle_without_length_reports_per_step() {
let mut t = ProgressThrottle::default();
assert!(t.chunk(10, None).is_some());
assert!(t.chunk(1024, None).is_none());
assert_eq!(downloading(t.chunk(256 * 1024, None)), Some(((256 * 1024 + 1034) as f64, None)));
assert!(t.report(10, None).is_some());
assert!(t.report(1024, None).is_none());
assert_eq!(downloading(t.report(256 * 1024 + 1034, None)), Some(((256 * 1024 + 1034) as f64, None)));
// A zero length is treated as unknown, not divided by.
assert!(ProgressThrottle::default().chunk(1, Some(0)).is_some());
assert!(ProgressThrottle::default().report(1, Some(0)).is_some());
}
#[test]
fn throttle_uses_absolute_bytes_after_a_full_download_restart() {
let mut t = ProgressThrottle::default();
let total = 100 * 1024 * 1024;
assert_eq!(downloading(t.report(40 * 1024 * 1024, None)), Some(((40 * 1024 * 1024) as f64, None)));
assert_eq!(downloading(t.report(1024, Some(total))), Some((1024.0, Some(total as f64))));
assert_eq!(
downloading(t.report(50 * 1024 * 1024, Some(total))),
Some(((50 * 1024 * 1024) as f64, Some(total as f64)))
);
}
#[test]
@@ -936,6 +958,18 @@ mod tests {
assert!(source_endpoints(Vec::new(), UpdateSource::Cnb).is_empty());
}
#[test]
fn updater_client_bounds_connection_setup() {
let proxy = ide_core::proxy_settings::ProxySettings::default();
let builder = configure_updater_client(reqwest::ClientBuilder::new(), &proxy);
// reqwest has no getter for this; its ClientBuilder Debug prints non-default settings.
let debug = format!("{builder:?}");
assert!(
debug.contains(&format!("connect_timeout: {:?}", UPDATER_CONNECT_TIMEOUT)),
"the updater must not wait forever on an unreachable CDN address: {debug}"
);
}
#[test]
fn only_one_install_at_a_time() {
let first = InstallingGuard::acquire().expect("first install starts");
+19 -8
Переглянути файл
@@ -164,7 +164,7 @@ async fn install(
/// The arguments of `docker` that start the server in the container: in the project folder, told
/// that the folder is trusted and that the CLI already ran the lifecycle commands.
fn server_args(up: &Up, bin: &str) -> Vec<String> {
fn server_args(up: &Up, bin: &str, replace: bool) -> Vec<String> {
let mut args: Vec<String> = ["exec", "-i", "-u", &up.user, "-w", &up.folder].map(str::to_owned).into();
for var in [
format!("{}={}", ide_host::trust::TRUSTED_ROOT_ENV, up.folder),
@@ -173,6 +173,9 @@ fn server_args(up: &Up, bin: &str) -> Vec<String> {
args.extend(["-e".to_owned(), var]);
}
args.extend([up.container.clone(), bin.to_owned(), "--attach".to_owned(), up.folder.clone()]);
if replace {
args.push("--replace".to_owned());
}
args
}
@@ -183,6 +186,7 @@ pub(crate) async fn connect(
state: &crate::state::AppState,
folder: &str,
config: &str,
replace: bool,
handler: Arc<dyn Handler>,
tail: &Tail,
progress: &Arc<Progress>,
@@ -215,16 +219,23 @@ pub(crate) async fn connect(
let up = up(&cli, &docker, &local, config, tail).await?;
let bin = ensure_server(state, &docker, &up, progress).await?;
progress(RemoteStage::Starting, None);
let peer = spawn(&docker, &up, &bin, handler, tail)?;
let peer = spawn(&docker, &up, &bin, replace, handler, tail)?;
let folder = up.folder.clone();
Ok((peer, folder, Exec::new(docker, up, bin)))
}
fn spawn(docker: &Path, up: &Up, bin: &str, handler: Arc<dyn Handler>, tail: &Tail) -> IdeResult<Peer> {
fn spawn(docker: &Path, up: &Up, bin: &str, replace: bool, handler: Arc<dyn Handler>, tail: &Tail) -> IdeResult<Peer> {
let tail = tail.clone();
let program = docker.to_string_lossy();
Peer::spawn(&program, &server_args(up, bin), &std::env::temp_dir(), &[], handler, Box::new(move |l| tail.push(l)))
.map_err(|e| IdeError::unavailable(format!("cannot start docker: {e}")))
Peer::spawn(
&program,
&server_args(up, bin, replace),
&std::env::temp_dir(),
&[],
handler,
Box::new(move |l| tail.push(l)),
)
.map_err(|e| IdeError::unavailable(format!("cannot start docker: {e}")))
}
#[cfg(test)]
@@ -237,7 +248,7 @@ mod tests {
#[test]
fn the_server_starts_in_the_folder_trusted_and_without_the_lifecycle() {
let up = Up { container: ID.into(), user: "vscode".into(), folder: "/workspaces/my app".into() };
let args = server_args(&up, "/home/vscode/.openidea/server/1/ab/openidea-server");
let args = server_args(&up, "/home/vscode/.openidea/server/1/ab/openidea-server", false);
assert_eq!(
args,
[
@@ -374,7 +385,7 @@ echo '{{"outcome":"success","containerId":"{ID}","remoteUser":"vscode","remoteWo
let dir = version_dir(&found.home, "0.0.0-test");
let bin = install(&docker, &up, &dir, "b1", &server, &progress).await.unwrap();
assert_eq!(probe(&docker, &up, "0.0.0-test").await.unwrap().installed, std::slice::from_ref(&bin));
let peer = spawn(&docker, &up, &bin, Arc::new(Silent), &tail).unwrap();
let peer = spawn(&docker, &up, &bin, false, Arc::new(Silent), &tail).unwrap();
let info: ide_host::rpc::ServerInfo = peer
.request("initialize", serde_json::json!({ "version": ide_host::rpc::PROTOCOL_VERSION }), None)
.await
@@ -446,7 +457,7 @@ echo '{{"outcome":"success","containerId":"{ID}","remoteUser":"vscode","remoteWo
let live = || docker_sh(&docker, &up.container, &format!("kill -0 {pid} 2>/dev/null && printf live"));
assert_eq!(live(), "live", "the terminal must outlive the window in a dev container");
let peer = spawn(&docker, &up, &bin, Arc::new(Silent), &Tail::default()).unwrap();
let peer = spawn(&docker, &up, &bin, false, Arc::new(Silent), &Tail::default()).unwrap();
tokio::time::timeout(Duration::from_secs(30), async {
let project: Value = peer.request("invoke", invoke("project_current", json!({})), None).await.unwrap();
assert_eq!(project["root"], up.folder);
+10 -3
Переглянути файл
@@ -673,6 +673,7 @@ pub async fn remote_connect(
state: State<'_, AppState>,
target: RemoteTarget,
mut path: String,
replace: bool,
on_progress: Channel<RemoteProgress>,
) -> IdeResult<RemoteProject> {
let progress: Arc<Progress> = Arc::new(move |stage, fraction| {
@@ -704,9 +705,10 @@ pub async fn remote_connect(
let attach_arg = if path.trim().is_empty() { "~" } else { path.trim() };
let stream = session
.exec_stream(&format!(
"{} --attach {} 2>&1",
"{} --attach {}{} 2>&1",
ide_ssh::shell::tilde_quote(&bin),
ide_ssh::shell::quote(attach_arg),
if replace { " --replace" } else { "" },
))
.await
.map_err(|e| IdeError::unavailable(format!("cannot start openidea-server: {e}")))?;
@@ -723,12 +725,12 @@ pub async fn remote_connect(
let bin = crate::remote_wsl::ensure_server(&state, distro, progress.clone()).await?;
progress(RemoteStage::Starting, None);
let attach_arg = if path.trim().is_empty() { "~" } else { path.trim() };
let peer = crate::remote_wsl::spawn(distro, &bin, attach_arg, handler, &tail)?;
let peer = crate::remote_wsl::spawn(distro, &bin, attach_arg, replace, handler, &tail)?;
(peer, None, distro.clone(), format!("WSL: {distro}"))
}
RemoteTarget::DevContainer { folder, config } => {
let (peer, root, run) =
crate::remote_container::connect(&state, folder, config, handler, &tail, &progress).await?;
crate::remote_container::connect(&state, folder, config, replace, handler, &tail, &progress).await?;
path = root;
exec = Some(Arc::new(run));
let name = std::path::Path::new(folder)
@@ -740,6 +742,11 @@ pub async fn remote_connect(
// A server that dies on start-up says why on stderr (`wsl.exe` prints its own errors too).
let with_output = |e: IdeError| match tail.text() {
t if t.is_empty() => e,
// Another build's backend holds the project: the window offers to stop it (#6119).
t if t.contains(ide_host::rpc::OTHER_BUILD_BUSY) => IdeError {
data: Some(ide_core::error::ErrorData::RemoteBackendBusy),
..IdeError::unavailable(ide_host::rpc::OTHER_BUILD_BUSY)
},
t => IdeError::unavailable(format!("{}: {t}", e.message)),
};
let info: ServerInfo = peer
+12 -4
Переглянути файл
@@ -187,10 +187,11 @@ pub(crate) fn spawn(
distro: &str,
bin: &str,
project_path: &str,
replace: bool,
handler: Arc<dyn Handler>,
tail: &Tail,
) -> IdeResult<Peer> {
spawn_with(ide_core::wsl::EXE, distro, bin, project_path, handler, tail)
spawn_with(ide_core::wsl::EXE, distro, bin, project_path, replace, handler, tail)
}
/// [`spawn`] through `launcher` instead of `wsl.exe` (tests put a stand-in there).
@@ -199,10 +200,15 @@ fn spawn_with(
distro: &str,
bin: &str,
project_path: &str,
replace: bool,
handler: Arc<dyn Handler>,
tail: &Tail,
) -> IdeResult<Peer> {
let args: Vec<String> = ["-d", checked(distro)?, "--exec", bin, "--attach", project_path].map(str::to_owned).into();
let mut args: Vec<String> =
["-d", checked(distro)?, "--exec", bin, "--attach", project_path].map(str::to_owned).into();
if replace {
args.push("--replace".to_owned());
}
let tail = tail.clone();
Peer::spawn(launcher, &args, &std::env::temp_dir(), &[], handler, Box::new(move |line| tail.push(line)))
.map_err(|e| IdeError::unavailable(format!("cannot start wsl.exe: {e}")))
@@ -305,7 +311,8 @@ printf 'Content-Length: %s\r\n\r\n%s' "${{#body}}" "$body"
std::fs::write(&launcher, script).unwrap();
std::fs::set_permissions(&launcher, std::fs::Permissions::from_mode(0o755)).unwrap();
let tail = Tail::default();
let peer = spawn_with(launcher.to_str().unwrap(), distro, bin, project, Arc::new(Silent), &tail).unwrap();
let peer =
spawn_with(launcher.to_str().unwrap(), distro, bin, project, false, Arc::new(Silent), &tail).unwrap();
let reply: String = peer.request("ping", serde_json::Value::Null, None).await.unwrap_or_else(|e| {
panic!("{e:?}; launcher said: {}", tail.text());
});
@@ -314,7 +321,8 @@ printf 'Content-Length: %s\r\n\r\n%s' "${{#body}}" "$body"
#[tokio::test]
async fn a_bad_distro_name_never_starts_the_launcher() {
let err = spawn_with("does-not-exist", "-d", "/x", "~", Arc::new(Silent), &Tail::default()).err().unwrap();
let err =
spawn_with("does-not-exist", "-d", "/x", "~", false, Arc::new(Silent), &Tail::default()).err().unwrap();
assert!(err.message.contains("not a valid"), "{}", err.message);
}
}
+160 -2
Переглянути файл
@@ -1,16 +1,28 @@
//! Desktop updater coordination shared by all webviews.
use crate::commands::window::{UpdateSource, check_update, update_endpoint_env, updates_configured};
mod download;
use crate::commands::window::{UpdateSource, check_update, update_endpoint_env, updater, updates_configured};
use crate::state::AppState;
use ide_core::updates::{UpdateCheck, UpdatePolicy};
use ide_core::{IdeEvent, IdeResult};
use ide_core::{CancellationToken, IdeError, IdeEvent, IdeResult};
use parking_lot::Mutex;
use std::collections::HashSet;
use std::future::Future;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Instant, SystemTime, UNIX_EPOCH};
use tauri::{AppHandle, Manager};
use tauri_plugin_updater::Update;
use tokio::sync::Notify;
/// One verified download, kept on disk until its installer has finished.
pub(crate) struct DownloadedUpdate {
pub update: Update,
pub bytes: Vec<u8>,
pub path: PathBuf,
}
/// Tauri patches the installer copies; the raw exe shipped in the portable zip keeps no bundle type.
pub fn portable_target(os: &str, arch: &str, bundle: Option<tauri::utils::config::BundleType>) -> Option<String> {
(os == "windows" && bundle.is_none()).then(|| format!("windows-{arch}-portable"))
@@ -129,6 +141,105 @@ pub async fn check(app: &AppHandle, source: Option<UpdateSource>) -> IdeResult<U
result
}
/// Downloads an update to a signature-keyed `.part` file, resuming from bytes
/// kept by a previous attempt or process, and verifies the completed package.
pub(crate) async fn download_update(
app: &AppHandle,
source: UpdateSource,
token: &CancellationToken,
mut progress: impl FnMut(u64, Option<u64>),
) -> IdeResult<DownloadedUpdate> {
let updater = updater(app, source)?.ok_or_else(|| IdeError::unavailable("updates are not configured"))?;
let update =
cancellable(token, async { updater.check().await.map_err(|error| IdeError::unavailable(error.to_string())) })
.await?
.ok_or_else(|| IdeError::not_found("no update available"))?;
let directory = app
.path()
.app_cache_dir()
.map_err(|error| IdeError::internal(format!("update cache directory: {error}")))?
.join("updates");
tokio::fs::create_dir_all(&directory).await?;
let key = cache_key(&update.version, &update.target, &update.signature);
let path = directory.join(format!("{key}.part"));
if let Err(error) = cleanup_stale_cache_files(&path).await {
tracing::warn!(%error, "cannot clean obsolete update downloads");
}
let client = ide_http::client::shared()?;
for attempt in 0..3 {
let outcome =
cancellable(token, download::fetch(&client, update.download_url.as_str(), &path, &mut progress)).await?;
match cancellable(token, verify_file(update.clone(), path.clone())).await {
Ok(bytes) => return Ok(DownloadedUpdate { update, bytes, path }),
Err(error) if outcome.resumed && attempt < 2 => {
tracing::warn!(%error, "discarding a mixed update checkpoint");
tokio::fs::remove_file(&path).await?;
}
Err(_) if outcome.total.is_none() && attempt < 2 => {
tracing::warn!("an update response of unknown length failed verification; resuming");
}
Err(error) => {
if outcome.resumed || outcome.total.is_some() {
tokio::fs::remove_file(&path).await?;
}
return Err(error);
}
}
}
Err(IdeError::internal("update download did not produce a verified package"))
}
/// Runs one fallible stage until it finishes or the command is cancelled. The
/// check and signature-verification stages previously escaped cancellation
/// while the download itself was cancellable.
async fn cancellable<T>(token: &CancellationToken, future: impl Future<Output = IdeResult<T>>) -> IdeResult<T> {
tokio::select! {
result = future => result,
_ = token.cancelled() => Err(IdeError::cancelled()),
}
}
/// Stable cache identity shared by GitHub and CNB for the same signed artifact.
fn cache_key(version: &str, target: &str, signature: &str) -> String {
let hash = blake3::hash(format!("{version}\0{target}\0{signature}").as_bytes()).to_hex();
format!("{version}-{target}-{hash}")
}
/// Reads and verifies a completed checkpoint on the blocking pool.
async fn verify_file(update: Update, path: PathBuf) -> IdeResult<Vec<u8>> {
tauri::async_runtime::spawn_blocking(move || {
let bytes = std::fs::read(path)?;
update.verify(&bytes).map_err(|error| IdeError::internal(error.to_string()))?;
Ok(bytes)
})
.await
.map_err(|error| IdeError::internal(error.to_string()))?
}
/// Keeps the current signed artifact's checkpoint and backup while removing
/// obsolete releases and abandoned fallback temporaries.
async fn cleanup_stale_cache_files(path: &Path) -> IdeResult<()> {
let Some(directory) = path.parent() else { return Ok(()) };
let keep_part = path.file_name();
let mut keep_backup = path.file_name().unwrap_or_default().to_os_string();
keep_backup.push(".backup");
let mut entries = tokio::fs::read_dir(directory).await?;
while let Some(entry) = entries.next_entry().await? {
if !entry.file_type().await?.is_file() {
continue;
}
let name = entry.file_name();
if Some(name.as_os_str()) == keep_part || name == keep_backup {
continue;
}
let text = name.to_string_lossy();
if text.ends_with(".part") || text.ends_with(".ready") || text.ends_with(".full") || text.ends_with(".backup") {
let _ = tokio::fs::remove_file(entry.path()).await;
}
}
Ok(())
}
fn emit_status(state: &AppState) {
let status = state.updates.state.lock().policy.status.clone();
state.sink.emit(IdeEvent::UpdateStatusChanged { status });
@@ -195,4 +306,51 @@ mod tests {
assert_eq!(ready_owner(Some("main"), &live, &HashSet::new()), None);
assert_eq!(ready_owner(Some("closed-window"), &[], &ready), None);
}
/// The cache identity stays stable across mirrors only while the signed bytes do.
#[test]
fn cache_identity_follows_the_signature_not_the_download_url() {
let first = cache_key("0.1.50", "darwin-aarch64", "signature-a");
assert_eq!(first, cache_key("0.1.50", "darwin-aarch64", "signature-a"));
assert_ne!(first, cache_key("0.1.50", "darwin-aarch64", "signature-b"));
assert_ne!(first, cache_key("0.1.51", "darwin-aarch64", "signature-a"));
}
/// Starting a download keeps its signed artifact's checkpoint and restores
/// its backup, while obsolete releases and fallback temporaries go away.
#[tokio::test]
async fn stale_update_cache_files_are_removed() {
let dir = tempfile::tempdir().unwrap();
let current = dir.path().join("current.part");
for name in
["current.part", "current.part.backup", "current.part.full", "old.part", "old.ready", "old.part.backup"]
{
tokio::fs::write(dir.path().join(name), b"x").await.unwrap();
}
tokio::fs::write(dir.path().join("unrelated.json"), b"{}").await.unwrap();
cleanup_stale_cache_files(&current).await.unwrap();
assert!(current.exists());
assert!(dir.path().join("current.part.backup").exists());
assert!(dir.path().join("unrelated.json").exists());
for name in ["current.part.full", "old.part", "old.ready", "old.part.backup"] {
assert!(!dir.path().join(name).exists(), "{name} was kept");
}
}
/// Signature verification is wrapped in the same cancellation boundary as
/// network work, so a late Cancel cannot fall through into installation.
#[tokio::test]
async fn cancelled_stage_stops_before_installation() {
let token = CancellationToken::new();
token.cancel();
let error = cancellable(&token, async {
tokio::time::sleep(std::time::Duration::from_secs(1)).await;
Ok(())
})
.await
.unwrap_err();
assert_eq!(error.kind, ide_core::error::ErrorKind::Cancelled);
}
}
+338
Переглянути файл
@@ -0,0 +1,338 @@
//! Resumable update downloads for the existing install-and-restart flow.
use ide_core::{IdeError, IdeResult};
use reqwest::header::{ACCEPT, ACCEPT_ENCODING, CONTENT_LENGTH, CONTENT_RANGE, RANGE};
use reqwest::{Client, StatusCode};
use std::path::{Path, PathBuf};
use tokio::fs::OpenOptions;
use tokio::io::AsyncWriteExt;
/// How one request completed: whether it appended to the partial file, and
/// whether the response advertised a total size.
#[derive(Debug, PartialEq, Eq)]
pub(crate) struct Outcome {
pub resumed: bool,
pub total: Option<u64>,
}
/// Appends `url` to `path`, resuming from its current length when the server
/// honours Range. An unsupported Range falls back to replacing the partial file
/// because installing bytes from different representations would be unsafe.
pub(crate) async fn fetch(
client: &Client,
url: &str,
path: &Path,
mut progress: impl FnMut(u64, Option<u64>),
) -> IdeResult<Outcome> {
let backup = beside(path, "backup");
if !path.exists() && backup.exists() {
tokio::fs::rename(&backup, path).await?;
} else if path.exists() {
let _ = tokio::fs::remove_file(backup).await;
}
let mut offset = match tokio::fs::metadata(path).await {
Ok(metadata) => metadata.len(),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => 0,
Err(error) => return Err(error.into()),
};
loop {
progress(offset, None);
let mut request = client
.get(url)
.header(ACCEPT, "application/octet-stream")
// A byte offset is only meaningful for the representation the server
// advertised. Automatic content decoding would break that contract.
.header(ACCEPT_ENCODING, "identity");
if offset > 0 {
request = request.header(RANGE, format!("bytes={offset}-"));
}
let response = request.send().await.map_err(|error| IdeError::unavailable(error.to_string()))?;
let status = response.status();
if status == StatusCode::RANGE_NOT_SATISFIABLE && offset > 0 {
let total =
response.headers().get(CONTENT_RANGE).and_then(|value| value.to_str().ok()).and_then(unsatisfied_total);
if total == Some(offset) {
return Ok(Outcome { resumed: true, total });
}
tokio::fs::remove_file(path).await?;
offset = 0;
continue;
}
if status == StatusCode::PARTIAL_CONTENT {
let (start, total) = response
.headers()
.get(CONTENT_RANGE)
.and_then(|value| value.to_str().ok())
.and_then(partial_range)
.ok_or_else(|| IdeError::unavailable("update server sent an invalid Content-Range header"))?;
if start != offset {
// This is not the byte range we asked for. Keep the partial file:
// another mirror may resume it correctly, and this response is not
// safe to append.
return Err(IdeError::unavailable(format!(
"update server returned byte {start} while {offset} was requested"
)));
}
let mut file = OpenOptions::new().append(true).open(path).await?;
let downloaded = append_body(&mut file, response, offset, total, &mut progress).await?;
ensure_complete(downloaded, total)?;
return Ok(Outcome { resumed: offset > 0, total });
}
if status == StatusCode::OK {
let total = response
.headers()
.get(CONTENT_LENGTH)
.and_then(|value| value.to_str().ok())
.and_then(|value| value.parse().ok());
if offset > 0 {
replace_with_full(response, path, total, &mut progress).await?;
} else {
let mut file = OpenOptions::new().create(true).write(true).truncate(true).open(path).await?;
let downloaded = append_body(&mut file, response, 0, total, &mut progress).await?;
ensure_complete(downloaded, total)?;
}
return Ok(Outcome { resumed: false, total });
}
return Err(IdeError::unavailable(format!("update download failed with HTTP {status}")));
}
}
/// Downloads a full response beside the existing partial file. The old bytes
/// stay resumable if the replacement connection fails before completion.
async fn replace_with_full(
response: reqwest::Response,
path: &Path,
total: Option<u64>,
progress: &mut impl FnMut(u64, Option<u64>),
) -> IdeResult<()> {
let temporary = beside(path, "full");
let backup = beside(path, "backup");
let result = async {
let mut file = OpenOptions::new()
.create(true)
.write(true)
.truncate(true)
.open(&temporary)
.await
.map_err(IdeError::from)?;
let downloaded = append_body(&mut file, response, 0, total, progress).await?;
ensure_complete(downloaded, total)?;
let _ = tokio::fs::remove_file(&backup).await;
let had_old = path.exists();
if had_old {
tokio::fs::rename(path, &backup).await.map_err(IdeError::from)?;
}
if let Err(error) = tokio::fs::rename(&temporary, path).await {
if had_old {
let _ = tokio::fs::rename(&backup, path).await;
}
return Err(IdeError::from(error));
}
if had_old {
let _ = tokio::fs::remove_file(&backup).await;
}
Ok(())
}
.await;
if result.is_err() {
let _ = tokio::fs::remove_file(&temporary).await;
}
result
}
/// Returns a sibling of `path` whose name has `suffix` appended after its full
/// extension sequence, e.g. `update.part` and `full` → `update.part.full`.
fn beside(path: &Path, suffix: &str) -> PathBuf {
let mut name = path.file_name().unwrap_or_default().to_os_string();
name.push(format!(".{suffix}"));
path.with_file_name(name)
}
/// Copies one response body into the persistent file and reports absolute
/// progress, including bytes recovered from an earlier process.
async fn append_body(
file: &mut tokio::fs::File,
mut response: reqwest::Response,
offset: u64,
total: Option<u64>,
progress: &mut impl FnMut(u64, Option<u64>),
) -> IdeResult<u64> {
let mut downloaded = offset;
while let Some(chunk) = response.chunk().await.map_err(|error| IdeError::unavailable(error.to_string()))? {
file.write_all(&chunk).await?;
downloaded += chunk.len() as u64;
progress(downloaded, total);
}
file.flush().await?;
file.sync_all().await?;
Ok(downloaded)
}
/// Rejects a body that ended before the advertised length instead of promoting
/// a truncated installer to the ready state.
fn ensure_complete(downloaded: u64, total: Option<u64>) -> IdeResult<()> {
match total {
Some(total) if downloaded != total => {
Err(IdeError::unavailable(format!("update download ended at {downloaded} of {total} bytes")))
}
_ => Ok(()),
}
}
/// Parses `bytes start-end/total`, returning the start and known total.
fn partial_range(value: &str) -> Option<(u64, Option<u64>)> {
let value = value.strip_prefix("bytes ")?;
let (range, total) = value.split_once('/')?;
let (start, _) = range.split_once('-')?;
let start = start.parse().ok()?;
let total = (total != "*").then(|| total.parse().ok()).flatten();
Some((start, total))
}
/// Parses the total from a `bytes */total` unsatisfied-range response.
fn unsatisfied_total(value: &str) -> Option<u64> {
value.strip_prefix("bytes */")?.parse().ok()
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::{Read, Write};
use std::net::TcpListener;
use std::thread;
/// Starts a one-request HTTP server and returns its URL plus the request line.
fn serve(response: Vec<u8>) -> (String, thread::JoinHandle<String>) {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let address = listener.local_addr().unwrap();
let handle = thread::spawn(move || {
let (mut socket, _) = listener.accept().unwrap();
let mut request = Vec::new();
let mut byte = [0];
while !request.ends_with(b"\r\n\r\n") {
socket.read_exact(&mut byte).unwrap();
request.push(byte[0]);
}
socket.write_all(&response).unwrap();
String::from_utf8(request).unwrap()
});
(format!("http://{address}/update"), handle)
}
/// Builds a complete HTTP response with a fixed body.
fn http(status: &str, headers: &[(&str, &str)], body: &[u8]) -> Vec<u8> {
let mut response = format!("HTTP/1.1 {status}\r\nConnection: close\r\n");
for (name, value) in headers {
response.push_str(&format!("{name}: {value}\r\n"));
}
response.push_str("\r\n");
response.into_bytes().into_iter().chain(body.iter().copied()).collect()
}
/// Drops a body early, then resumes from the bytes already on disk.
#[tokio::test]
async fn a_broken_download_resumes_with_range() {
let client = ide_http::client::shared().unwrap();
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("update.part");
let (url, first) = serve(http("200 OK", &[("Content-Length", "10")], b"abcd"));
assert!(fetch(&client, &url, &path, |_, _| {}).await.is_err());
first.join().unwrap();
assert_eq!(tokio::fs::read(&path).await.unwrap(), b"abcd");
let (url, second) = serve(http(
"206 Partial Content",
&[("Content-Range", "bytes 4-9/10"), ("Content-Length", "6")],
b"efghij",
));
let outcome = fetch(&client, &url, &path, |_, _| {}).await.unwrap();
let request = second.join().unwrap().to_ascii_lowercase();
assert!(request.contains("range: bytes=4-"), "{request}");
assert_eq!(outcome, Outcome { resumed: true, total: Some(10) });
assert_eq!(tokio::fs::read(path).await.unwrap(), b"abcdefghij");
}
/// Replaces a stale partial file when a proxy or mirror ignores Range.
#[tokio::test]
async fn a_full_response_after_a_partial_replaces_the_file() {
let client = ide_http::client::shared().unwrap();
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("update.part");
tokio::fs::write(&path, b"stale").await.unwrap();
let (url, request) = serve(http("200 OK", &[("Content-Length", "7")], b"fresh!!"));
let outcome = fetch(&client, &url, &path, |_, _| {}).await.unwrap();
assert!(request.join().unwrap().to_ascii_lowercase().contains("range: bytes=5-"));
assert_eq!(outcome, Outcome { resumed: false, total: Some(7) });
assert_eq!(tokio::fs::read(&path).await.unwrap(), b"fresh!!");
assert!(!path.with_file_name("update.part.full").exists());
}
/// Keeps the older checkpoint when a proxy ignores Range and its full
/// replacement download breaks before completion.
#[tokio::test]
async fn a_broken_full_fallback_preserves_the_previous_partial() {
let client = ide_http::client::shared().unwrap();
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("update.part");
tokio::fs::write(&path, b"stale").await.unwrap();
let (url, _) = serve(http("200 OK", &[("Content-Length", "10")], b"fresh"));
assert!(fetch(&client, &url, &path, |_, _| {}).await.is_err());
assert_eq!(tokio::fs::read(&path).await.unwrap(), b"stale");
assert!(!path.with_file_name("update.part.full").exists());
}
/// Accepts `bytes */length` as the only completion signal for an already
/// complete partial file after a process restart.
#[tokio::test]
async fn an_already_complete_partial_file_is_returned_on_416() {
let client = ide_http::client::shared().unwrap();
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("update.part");
tokio::fs::write(&path, b"done").await.unwrap();
let (url, _) = serve(http("416 Range Not Satisfiable", &[("Content-Range", "bytes */4")], b""));
assert_eq!(fetch(&client, &url, &path, |_, _| {}).await.unwrap(), Outcome { resumed: true, total: Some(4) });
}
/// A close-delimited response has no length to prove a clean EOF; the caller
/// uses this signal to resume instead of discarding a failed checkpoint.
#[tokio::test]
async fn a_close_delimited_response_reports_an_unknown_total() {
let client = ide_http::client::shared().unwrap();
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("update.part");
let (url, _) = serve(http("200 OK", &[], b"body"));
assert_eq!(fetch(&client, &url, &path, |_, _| {}).await.unwrap(), Outcome { resumed: false, total: None });
assert_eq!(tokio::fs::read(path).await.unwrap(), b"body");
}
/// A crash during the full-response swap leaves the old checkpoint in the
/// backup name; the next fetch restores it before calculating Range.
#[tokio::test]
async fn a_backup_checkpoint_is_restored_before_resuming() {
let client = ide_http::client::shared().unwrap();
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("update.part");
tokio::fs::write(beside(&path, "backup"), b"old").await.unwrap();
let (url, request) = serve(http("416 Range Not Satisfiable", &[("Content-Range", "bytes */3")], b""));
let outcome = fetch(&client, &url, &path, |_, _| {}).await.unwrap();
assert!(request.join().unwrap().to_ascii_lowercase().contains("range: bytes=3-"));
assert_eq!(outcome, Outcome { resumed: true, total: Some(3) });
assert_eq!(tokio::fs::read(&path).await.unwrap(), b"old");
assert!(!beside(&path, "backup").exists());
}
/// Rejects malformed range metadata instead of appending to an unknown slice.
#[test]
fn content_range_parser_only_accepts_byte_ranges() {
assert_eq!(partial_range("bytes 4-9/10"), Some((4, Some(10))));
assert_eq!(partial_range("bytes 0-0/*"), Some((0, None)));
assert_eq!(partial_range("items 4-9/10"), None);
assert_eq!(unsatisfied_total("bytes */10"), Some(10));
assert_eq!(unsatisfied_total("bytes 0-1/10"), None);
}
}
+2 -1
Переглянути файл
@@ -71,7 +71,7 @@ app_install_update always desktop bin
app_log_location always desktop bindings sync
app_metrics always desktop bindings async
app_quit always desktop bindings sync
app_release_notes trusted desktop bindings async
app_release_notes always desktop bindings async
app_restart always desktop bindings sync
app_update_announcement always desktop bindings sync
app_update_status always desktop bindings sync
@@ -188,6 +188,7 @@ debug_jvm_thread_dump trusted project_host bin
debug_listen_for_jvm trusted project_host bindings async
debug_pause trusted project_host bindings async
debug_redefine_classes trusted project_host bindings async
debug_replace_breakpoints trusted project_host bindings async
debug_resolve_variable trusted project_host bindings async
debug_restart_frame trusted project_host bindings async
debug_resume trusted project_host bindings async
+11 -2
Переглянути файл
@@ -227,6 +227,8 @@ export const commands = {
* can show the UI's language and fall back to English. An install records the
* notes it saw, so this is only for an update installed outside the app.
* `Ok(None)` when the manifest covers another version or carries no notes.
* Reads only the public manifest, like the update check: the page usually opens
* in a window without a project.
*/
appReleaseNotes: (version: string, source: UpdateSource) => typedError<{ [key in string]: string } | null, IdeError>(__TAURI_INVOKE("app_release_notes", { version, source })),
/** Quits through every window's unsaved-changes check, then starts again. */
@@ -478,6 +480,8 @@ export const commands = {
debugPause: (session: DebugSessionId, threadId: number) => typedError<null, IdeError>(__TAURI_INVOKE("debug_pause", { session, threadId })),
/** HotSwap (Reload Changed Classes) in a java-debug session. */
debugRedefineClasses: (session: DebugSessionId) => typedError<HotSwapResult, IdeError>(__TAURI_INVOKE("debug_redefine_classes", { session })),
/** Replaces all of this window's line breakpoints with `files`. */
debugReplaceBreakpoints: (files: { [key in string]: Breakpoint[] }) => typedError<null, IdeError>(__TAURI_INVOKE("debug_replace_breakpoints", { files })),
debugResolveVariable: (session: DebugSessionId, variable: Variable_Deserialize) => typedError<Variable_Serialize, IdeError>(__TAURI_INVOKE("debug_resolve_variable", { session, variable })),
/** Reset Frame (Drop Frame). */
debugRestartFrame: (session: DebugSessionId, frameId: number) => typedError<null, IdeError>(__TAURI_INVOKE("debug_restart_frame", { session, frameId })),
@@ -488,6 +492,7 @@ export const commands = {
debugSendInput: (session: DebugSessionId, text: string) => typedError<null, IdeError>(__TAURI_INVOKE("debug_send_input", { session, text })),
/** This window's live sessions, including adapter-started child sessions. */
debugSessions: () => typedError<SessionInfo[], IdeError>(__TAURI_INVOKE("debug_sessions")),
/** This window's breakpoints of `path`. */
debugSetBreakpoints: (path: string, breakpoints: Breakpoint[]) => typedError<BreakpointState[], IdeError>(__TAURI_INVOKE("debug_set_breakpoints", { path, breakpoints })),
/** Field watchpoints; states aligned with `breakpoints`. */
debugSetDataBreakpoints: (breakpoints: DataBreakpoint[]) => typedError<BreakpointState[], IdeError>(__TAURI_INVOKE("debug_set_data_breakpoints", { breakpoints })),
@@ -1512,7 +1517,7 @@ export const commands = {
* dev container, whose project folder is the container's own) in this window (installs /
* starts the server as needed).
*/
remoteConnect: (target: RemoteTarget, path: string, onProgress: Channel<RemoteProgress>) => typedError<RemoteProject_Serialize, IdeError>(__TAURI_INVOKE("remote_connect", { target, path, onProgress })),
remoteConnect: (target: RemoteTarget, path: string, replace: boolean, onProgress: Channel<RemoteProgress>) => typedError<RemoteProject_Serialize, IdeError>(__TAURI_INVOKE("remote_connect", { target, path, replace, onProgress })),
/** The remote session of this window (a settings window: its parent's), if any. */
remoteCurrent: () => __TAURI_INVOKE<{
target: RemoteTarget,
@@ -3780,6 +3785,8 @@ export type BlameLine_Serialize = {
export type BlockHistory = {
/** The selected lines in HEAD (0-based, inclusive); None when none of them is committed. */
headLines: [number, number] | null,
/** Those lines as HEAD has them, each ending with `\n`; None from servers that predate it. */
head?: string | null,
revisions: BlockRevision[],
};
@@ -6848,7 +6855,9 @@ report?: PushReport | null } |
* jdtls could not set a module up as a Java project: the errors on its build files and
* the builds enclosing it (`path: message`, the path relative to the project), nearest first.
*/
{ type: "javaBuildProblems"; problems: string[] };
{ type: "javaBuildProblems"; problems: string[] } |
/** A remote backend of another OpenIDEA build still serves the project and refused to retire. */
{ type: "remoteBackendBusy" };
export type ErrorKind = "notFound" | "alreadyExists" | "permissionDenied" | "invalidInput" |
/** The requested state is stale; the UI must use the current snapshot. */
+35
Переглянути файл
@@ -0,0 +1,35 @@
import { describe, expect, it } from "vitest";
import { Text } from "@codemirror/state";
import { semanticRanges } from "../index";
const doc = Text.of(["std"]);
const token = (type: string, modifiers: string[], language = "cpp") =>
semanticRanges(
doc,
{ tokenTypes: [type], tokenModifiers: modifiers, data: [0, 0, 3, 0, (1 << modifiers.length) - 1] },
false,
language,
)[0]?.className.split(" ");
describe("C++ namespace semantic tokens", () => {
it.each(["cpp", "CPP"])("keeps standard-library namespaces in the namespace colour (%s)", (language) => {
expect(token("namespace", ["defaultLibrary", "globalScope"], language)).toEqual(["cm-sem-namespace"]);
expect(token("namespace", ["defaultLibrary"], language)).toEqual(token("namespace", [], language));
});
it("preserves namespace declaration and deprecation styles", () => {
expect(token("namespace", ["defaultLibrary", "declaration", "deprecated"])).toEqual([
"cm-sem-namespace",
"cm-sem-declaration",
"cm-sem-deprecated",
]);
});
it.each(["class", "function", "variable"])("preserves builtin colouring for %s tokens", (type) => {
expect(token(type, ["defaultLibrary"])).toContain("cm-sem-builtin");
});
it("leaves other languages' namespace colouring unchanged", () => {
expect(token("namespace", ["defaultLibrary"], "rust")).toEqual(["cm-sem-namespace", "cm-sem-builtin"]);
});
});
+10
Переглянути файл
@@ -0,0 +1,10 @@
import { registerLanguageSemantics } from "../languages";
registerLanguageSemantics("cpp", {
tokenClasses({ type, classes }) {
// clangd marks std and other library namespaces as defaultLibrary; keep their namespace colour.
if (type !== "namespace") return;
const builtin = classes.indexOf("cm-sem-builtin");
if (builtin >= 0) classes.splice(builtin, 1);
},
});
+1
Переглянути файл
@@ -33,6 +33,7 @@ import "./php";
import "./go";
import "./java";
import "./javascript";
import "./cpp";
const semanticBackoff = featureBackoff();
+16 -2
Переглянути файл
@@ -36,7 +36,8 @@ const appRestart = vi.fn(async () => null);
const cancelRequest = vi.fn(async () => null);
const appBuildInfo = vi.fn(async () => ({ version: "0.1.21" }));
const settingsSet = vi.fn(async () => ({ status: "ok", data: { general: {}, appearance: {} } }));
const recordInstalledUpdate = vi.fn();
const undoRecord = vi.fn();
const recordInstalledUpdate = vi.fn((_version: string, _notes: string | null) => undoRecord);
vi.mock("@/platform/releaseNotes", () => ({ recordInstalledUpdate }));
@@ -171,12 +172,24 @@ describe("Install and Restart", () => {
expect(appInstallUpdate).toHaveBeenCalledTimes(2);
});
it("records the notes before the install starts: the Windows installer ends the app inside it", async () => {
void installUpdate("0.1.22", "github", "## Fixed\n- a crash");
expect(appInstallUpdate).toHaveBeenCalledTimes(1);
expect(recordInstalledUpdate).toHaveBeenCalledWith("0.1.22", "## Fixed\n- a crash");
expect(recordInstalledUpdate.mock.invocationCallOrder[0]).toBeLessThan(
appInstallUpdate.mock.invocationCallOrder[0]!,
);
install.resolve(ok(null));
await tick();
expect(undoRecord).not.toHaveBeenCalled();
});
it("reports a failure with Retry, and a cancellation", async () => {
const failed = installUpdate("0.1.22");
install.resolve({ status: "error", error: { kind: "unavailable", message: "connection reset" } });
await failed;
expect(appRestart).not.toHaveBeenCalled();
expect(recordInstalledUpdate).not.toHaveBeenCalled();
expect(undoRecord).toHaveBeenCalledTimes(1);
expect(task(INSTALL_TASK_ID)?.done).toBe(true);
expect(notes.at(-1)).toMatchObject({
level: "error",
@@ -194,6 +207,7 @@ describe("Install and Restart", () => {
await cancelled;
expect(notes.at(-1)).toMatchObject({ level: "info", title: "Update cancelled", key: UPDATE_KEY });
expect(appRestart).not.toHaveBeenCalled();
expect(undoRecord).toHaveBeenCalledTimes(2);
});
it.each([
+4 -2
Переглянути файл
@@ -229,9 +229,13 @@ async function runInstall(version: string, source: UpdateSource, notes: string |
upsertTask({ id: INSTALL_TASK_ID, title, message: null, fraction: null, done: false, cancel });
// Replaces the notification whose action is now spent.
balloon([{ label: t("app.update.cancel"), run: cancel }]);
// The restarted app reads this to show the What's New page of the version it now runs.
// Recorded first: the Windows installer ends the app before the install returns.
const undoRecord = recordInstalledUpdate(version, notes);
try {
await call(commands.appInstallUpdate(source, request, channel));
} catch (e) {
undoRecord();
if (isCancelled(e)) {
notifications().notify({
level: "info",
@@ -257,8 +261,6 @@ async function runInstall(version: string, source: UpdateSource, notes: string |
} finally {
upsertTask({ id: INSTALL_TASK_ID, title, message: null, fraction: 1, done: true });
}
// The restarted app reads this to show the What's New page of the version it now runs.
recordInstalledUpdate(version, notes);
const restart = () => void commands.appRestart();
// Stays if a window cancels the restart (unsaved changes): the update applies on the next start.
notifications().notify({
+31
Переглянути файл
@@ -266,6 +266,37 @@ describe("HotSwap", () => {
}
});
it("points a refused structural change to Enhanced class redefinition when the configuration has it off", async () => {
const refused = "Failed to redefine classes: add method not implemented";
const hint = "turn on Enhanced class redefinition in the run configuration";
expect(hotSwapMessage(0, [refused], false, true).body).toContain(hint);
expect(hotSwapMessage(0, [refused], false, false).body).toBe(refused);
expect(hotSwapMessage(0, ["boom"], false, true).body).toBe("boom");
const withConfig = (kind: string, params: Record<string, string>) => ({
...session(1, true),
runConfig: { id: kind, kind, params } as unknown as NonNullable<DebugSession["runConfig"]>,
});
ipc.debugRedefineClasses.mockImplementation(() => ipc.ok({ changedClasses: [], errorMessage: refused }));
for (const [s, shown] of [
[withConfig("application", {}), true],
[withConfig("spring-boot", {}), true],
[withConfig("application", { enhancedClassRedefinition: "true" }), false],
[withConfig("tomcat", {}), false],
[session(1, true), false],
] as const) {
useDebug.setState({ sessions: { 1: s } });
// oxlint-disable-next-line no-await-in-loop -- one reload per session shape; each assertion reads its notification
await reloadChangedClasses(false);
expect(notes.at(-1)).toMatchObject({ level: "error", title: "Hot Swap failed" });
expect(String(notes.at(-1)!.body).includes(hint)).toBe(shown);
}
useDebug.setState({ sessions: { 1: withConfig("application", {}) } });
onHotCodeReplace(1 as DebugSessionId, { kind: "hotCodeReplace", changeType: "ERROR", message: refused });
expect(notes.at(-1)).toMatchObject({ title: "Hot Swap", body: expect.stringContaining(hint) });
});
function pausedFrames(names: string[], restartFrame = true): DebugSession {
return {
...session(1, true),
+8
Переглянути файл
@@ -157,6 +157,14 @@ describe("Java debugging (java-debug through jdtls)", () => {
});
});
it("asks the host for enhanced class redefinition when the configuration turns it on", async () => {
const on = { ...app, params: { enhancedClassRedefinition: "true" } };
expect(JSON.parse((await javaLaunchConfig(on, "/p")).extraJson!).enhancedClassRedefinition).toBe(true);
expect(JSON.parse((await javaLaunchConfig(app, "/p")).extraJson!)).not.toHaveProperty("enhancedClassRedefinition");
const kotlin = { ...on, debugAdapter: "kotlin-debug-adapter" };
expect(JSON.parse((await javaLaunchConfig(kotlin, "/p")).extraJson!).enhancedClassRedefinition).toBe(true);
});
it("lets java-debug shorten a classpath too long for the OS, as Run does", async () => {
for (const how of ["jarmanifest", "argfile"]) {
shortenCommandLine = how;
+19
Переглянути файл
@@ -25,6 +25,7 @@ import {
const ipc = vi.hoisted(() => ({
debugSetBreakpoints: vi.fn(),
debugReplaceBreakpoints: vi.fn(async () => ({ status: "ok", data: null })),
debugStart: vi.fn(async () => ({ status: "ok", data: 42 })),
debugStop: vi.fn(async () => ({ status: "ok", data: null })),
debugCapabilities: vi.fn(async () => ({ status: "ok", data: {} })),
@@ -169,6 +170,24 @@ it("drains an in-flight update and sends pending removals before startup", async
expect(ipc.debugStart).toHaveBeenCalledOnce();
});
it("hands the window's whole list to the backend before startup, even after a failed removal (#6116)", async () => {
ipc.debugSetBreakpoints.mockResolvedValueOnce({ status: "ok", data: [] }).mockRejectedValueOnce(new Error("lost"));
addBreakpoint("/p/Main.java", 4);
await vi.advanceTimersByTimeAsync(120);
removeAllBreakpoints();
await vi.advanceTimersByTimeAsync(120);
addBreakpoint("/p/Other.java", 7);
ipc.debugSetBreakpoints.mockResolvedValue({ status: "ok", data: [] });
ipc.debugReplaceBreakpoints.mockClear();
await startSession(config("launch"));
expect(ipc.debugReplaceBreakpoints).toHaveBeenCalledExactlyOnceWith({
"/p/Other.java": [expect.objectContaining({ line: 7, enabled: true })],
});
expect(ipc.debugReplaceBreakpoints.mock.invocationCallOrder[0]).toBeLessThan(
ipc.debugStart.mock.invocationCallOrder[0]!,
);
});
it("flushes persisted breakpoints immediately after project loading", async () => {
ipc.debugSetBreakpoints.mockResolvedValue({ status: "ok", data: [] });
localStorage.setItem(
+13
Переглянути файл
@@ -87,6 +87,8 @@ export function loadBreakpoints(root: string | null) {
}
const previous = Object.keys(useBreakpoints.getState().byFile);
useBreakpoints.setState({ root, byFile, muted, status: {} });
// The backend may still hold files this window no longer lists (a reloaded window).
void replaceBreakpoints().catch((e) => console.warn("debugReplaceBreakpoints failed", e));
for (const path of new Set([...previous, ...Object.keys(byFile)])) scheduleSync(path);
}
@@ -129,6 +131,17 @@ async function drainBreakpoints() {
await Promise.all([...paths].map((path) => syncFile(path)));
paths = new Set([...timers.keys(), ...inFlight.keys()]);
}
// The new session gets exactly the files listed here, even if a removal never reached the
// backend (#6116). Failing that, the session still starts with what the backend has.
await replaceBreakpoints().catch((e) => console.warn("debugReplaceBreakpoints failed", e));
}
/** Makes this window's whole list the backend's: files it no longer lists are cleared there. */
async function replaceBreakpoints() {
if (!isTauri() || useProject.getState().project?.trusted === false) return;
const { byFile, muted } = useBreakpoints.getState();
const files = Object.fromEntries(Object.entries(byFile).map(([path, list]) => [path, toBackend(list, muted, path)]));
await call(commands.debugReplaceBreakpoints(files));
}
export function syncFile(path: string): Promise<void> {
+28 -2
Переглянути файл
@@ -59,15 +59,40 @@ const classesText = (n: number) => (n === 1 ? tx`${n} class` : tx`${n} classes`)
// java-debug reports this after redefineClasses succeeds, with no changedClasses count.
const obsoleteMethods = (message: string) => message.trim() === "JVM contains obsolete methods";
// JDI's refusals of a structural change: "add method not implemented", "schema change not implemented", …
const structuralChange = (message: string) => /\bnot implemented\b/i.test(message);
/** Application and Spring Boot configurations offer Enhanced class redefinition (JetBrains Runtime's DCEVM). */
const ENHANCEABLE_KINDS = new Set(["application", "spring-boot"]);
/** Whether the session's configuration could turn on Enhanced class redefinition but has not. */
export function canEnhanceRedefinition(s: DebugSession): boolean {
const rc = s.runConfig;
return !!rc && ENHANCEABLE_KINDS.has(rc.kind) && rc.params?.enhancedClassRedefinition !== "true";
}
/** The failure text, plus how to allow structural changes when JDI refused one and the configuration can. */
function failureBody(errors: string[], enhanceable: boolean): string {
const body = errors.join("\n");
if (!enhanceable || !errors.some(structuralChange)) return body;
return (
body +
"\n\n" +
tx(
"To add or remove methods and fields, turn on Enhanced class redefinition in the run configuration and debug on JetBrains Runtime.",
)
);
}
/** Message for the reload result (IDEA wording). */
export function hotSwapMessage(
changed: number,
errors: string[],
bottomFrame = false,
enhanceable = false,
): { level: "info" | "warning" | "error"; title: string; body?: string } {
if (errors.some((e) => !obsoleteMethods(e)))
return { level: "error", title: "Hot Swap failed", body: errors.join("\n") };
return { level: "error", title: "Hot Swap failed", body: failureBody(errors, enhanceable) };
if (errors.length)
return {
level: "warning",
@@ -226,6 +251,7 @@ export async function reloadChangedClasses(build = true, configId?: string, allo
changed.size,
errors,
affected.some((s) => s.status === "paused" && s.frames.length === 1),
sessions.some(canEnhanceRedefinition),
);
notifications().notify({
group: "run",
@@ -308,7 +334,7 @@ export function onHotCodeReplace(session: DebugSessionId, event: Extract<DebugEv
level: event.changeType === "ERROR" ? "error" : "warning",
key: KEY,
title: "Hot Swap",
body: event.message,
body: failureBody([event.message], canEnhanceRedefinition(useDebug.getState().sessions[session]!)),
});
break;
}
+5
Переглянути файл
@@ -174,6 +174,8 @@ export async function javaLaunchConfig(
preparation?.report?.(`${joinJavaArgs([resolved.command, ...resolved.args])}\n`);
const agentNote = await remoteJavaAgentNote(rc);
if (agentNote) preparation?.report?.(agentNote);
// The host adds JetBrains Runtime's flag for it, or says in the console why the session runs without.
const enhanced = rc.params?.enhancedClassRedefinition === "true" ? { enhancedClassRedefinition: true } : {};
if (kotlin) {
return {
name: rc.name,
@@ -191,6 +193,7 @@ export async function javaLaunchConfig(
javaExec: resolved.command,
vmArguments: [...consoleVmArgs(rc), ...parsed.vmArgs],
programArgs: parsed.programArgs,
...enhanced,
}),
};
}
@@ -212,6 +215,7 @@ export async function javaLaunchConfig(
javaExec: resolved.command === "java" ? undefined : resolved.command,
vmArgs: [...consoleVmArgs(rc), ...parsed.vmArgs],
args: parsed.programArgs,
...enhanced,
}),
};
}
@@ -243,6 +247,7 @@ export async function javaLaunchConfig(
shortenCommandLine: info.shortenCommandLine ?? "none",
console: "internalConsole",
stopOnEntry: false,
...enhanced,
}),
};
}
+27
Переглянути файл
@@ -0,0 +1,27 @@
import { describe, expect, it } from "vitest";
import { convertIcls } from "../intellijTheme";
const opt = (name: string, value: string) =>
`<option name="${name}"><value><option name="FOREGROUND" value="${value}"/></value></option>`;
const scheme = (parent: string, ...options: string[]) =>
`<scheme name="t" version="142" parent_scheme="${parent}"><attributes>${options.join("")}</attributes></scheme>`;
describe("annotation colour of a theme plugin's scheme (#6108)", () => {
it("keeps Darcula's annotation colour when the file only changes DEFAULT_METADATA", () => {
const { tokens } = convertIcls(scheme("Darcula", opt("DEFAULT_METADATA", "1d8711")));
expect(tokens["--syn-annotation"]).toBe("#bbb529");
expect(tokens["--syn-decorator"]).toBe("#1d8711");
});
it("takes the file's annotation key for annotations", () => {
const { tokens } = convertIcls(
scheme("Darcula", opt("DEFAULT_METADATA", "1d8711"), opt("ANNOTATION_NAME_ATTRIBUTES", "9e880d")),
);
expect(tokens["--syn-annotation"]).toBe("#9e880d");
});
it("leaves a light parent's annotation colour to the base theme", () => {
const { tokens } = convertIcls(scheme("Default", opt("DEFAULT_METADATA", "1d8711")));
expect(tokens["--syn-annotation"]).toBeUndefined();
});
});
+3 -4
Переглянути файл
@@ -163,10 +163,9 @@ export const ICLS_ATTRIBUTES: Record<string, Array<[Part, string]>> = {
DEFAULT_PARAMETER: [["FOREGROUND", "--syn-param"]],
DEFAULT_GLOBAL_VARIABLE: [["FOREGROUND", "--syn-global"]],
DEFAULT_PREDEFINED_SYMBOL: [["FOREGROUND", "--syn-builtin"]],
DEFAULT_METADATA: [
["FOREGROUND", "--syn-annotation"],
["FOREGROUND", "--syn-decorator"],
],
// Java annotations take the scheme's (or its parent's) annotation key, not DEFAULT_METADATA.
ANNOTATION_NAME_ATTRIBUTES: [["FOREGROUND", "--syn-annotation"]],
DEFAULT_METADATA: [["FOREGROUND", "--syn-decorator"]],
DEFAULT_OPERATION_SIGN: [["FOREGROUND", "--syn-punct"]],
DEFAULT_VALID_STRING_ESCAPE: [["FOREGROUND", "--syn-escape"]],
DEFAULT_TAG: [["FOREGROUND", "--syn-tag"]],
+11 -1
Переглянути файл
@@ -4,7 +4,7 @@
* to it (platform/remote.ts).
*/
import { registerActions } from "@/platform/actions";
import { disconnectRemote, stopRemoteBackend, useRemote } from "@/platform/remote";
import { disconnectRemote, provideBackendBusyPrompt, stopRemoteBackend, useRemote } from "@/platform/remote";
import { lazyComponent } from "@/ui";
import { maybeEditorService, registerOverlay, registerStatusItem, registerToolWindow } from "@/workbench/contributions";
import { confirm } from "@/workbench/messages";
@@ -57,6 +57,16 @@ function trackPortsWindow(): () => void {
export function activate(): () => void {
const disposers = [
provideBackendBusyPrompt(() =>
confirm({
title: tx("Stop Remote Backend"),
message: tx(
"The backend of another OpenIDEA build, for example the one from before an upgrade, still has this project open, so this build can't open it. Stop that backend and open the project? Its terminals, runs and agent sessions end, and changes it hasn't saved are lost.",
),
ok: tx("Stop Backend and Open"),
icon: "warning",
}),
),
trackPortsWindow(),
installReconnect(),
installDirenvNotifications(),
+10
Переглянути файл
@@ -146,6 +146,16 @@ describe("Application / Spring Boot command line", () => {
expect(parsed.programArgs).toEqual(["--server.port=8081", "two words"]);
});
it.each([
["application", applicationType],
["spring-boot", springBootType],
] as const)("%s offers Enhanced class redefinition for Debug without changing the Run command", (_, type) => {
expect(type.fields.find((f) => f.key === "enhancedClassRedefinition")).toMatchObject({ control: "checkbox" });
const params = { mainClass: "a.Main", classpath: "${classpath}" };
expect(type.commandLine({ ...params, enhancedClassRedefinition: "true" })).toEqual(type.commandLine(params));
expect(jarApplicationType.fields.some((f) => f.key === "enhancedClassRedefinition")).toBe(false);
});
it("reads VM options over several lines and with quoted spaces", () => {
const line = applicationType.commandLine({
mainClass: "a.Main",
+12
Переглянути файл
@@ -78,6 +78,17 @@ const jreField: RunConfigTypeField = {
})),
};
/**
* JetBrains Runtime's `-XX:+AllowEnhancedClassRedefinition` for Debug, so Reload Changed Classes can add or
* remove methods and fields. The host adds it only on JetBrains Runtime (other JVMs refuse to start with it).
*/
const enhancedRedefinitionField: RunConfigTypeField = {
key: "enhancedClassRedefinition",
label: "Enhanced class redefinition",
control: "checkbox",
hint: "When debugging on JetBrains Runtime, Reload Changed Classes can also add or remove methods and fields",
};
/** IDEA's "Use classpath of module": the module whose classpath and build the run uses. */
const moduleField: RunConfigTypeField = {
key: "module",
@@ -119,6 +130,7 @@ function jvmApplicationType(spring: boolean): RunConfigTypeContribution {
...(spring ? [profilesField("Comma separated; passed as --spring.profiles.active")] : []),
...(spring ? updatePolicyFields(false) : []),
jreField,
enhancedRedefinitionField,
moduleField,
{
key: "classpath",
+73 -1
Переглянути файл
@@ -13,6 +13,7 @@ beforeEach(() => {
notify.mockClear();
});
afterEach(() => {
usePlatform.setState({ os: "macos" });
vi.restoreAllMocks();
vi.unstubAllGlobals();
});
@@ -181,6 +182,7 @@ function remoteTarget(current = () => true): TerminalPasteTarget {
}
it.each(["event", "menu"])("rejects oversized %s images before reading or uploading", async (route) => {
usePlatform.setState({ os: "windows" }); // the WebView menu path; macOS reads natively
const read = vi.fn(async () => new ArrayBuffer(0));
const blob = image(read, 20 * 1024 * 1024 + 1);
const store = vi.spyOn(commands, "termStoreImage");
@@ -246,6 +248,7 @@ it("claims remote image events before xterm and pastes a quoted path only after
});
it("reads an image from the explicit paste menu after text and file recovery", async () => {
usePlatform.setState({ os: "windows" }); // the WebView menu path; macOS reads natively
vi.spyOn(commands, "clipboardFileList").mockResolvedValue({ status: "ok", data: ["/local/stale.png"] });
const store = vi.spyOn(commands, "termStoreImage").mockResolvedValue({ status: "ok", data: "/remote/image.png" });
const getType = vi.fn(async () => image());
@@ -261,6 +264,7 @@ it("reads an image from the explicit paste menu after text and file recovery", a
});
it("recovers remote menu file paths when image clipboard reading is unavailable", async () => {
usePlatform.setState({ os: "windows" }); // the WebView menu path; macOS reads natively
vi.spyOn(commands, "clipboardFileList").mockResolvedValue({ status: "ok", data: ["/local/file.txt"] });
const store = vi.spyOn(commands, "termStoreImage");
Object.defineProperty(navigator, "clipboard", { configurable: true, value: { readText: async () => "" } });
@@ -271,6 +275,7 @@ it("recovers remote menu file paths when image clipboard reading is unavailable"
});
it("uploads a menu image even if reading clipboard text is rejected", async () => {
usePlatform.setState({ os: "windows" }); // the WebView menu path; macOS reads natively
const store = vi.spyOn(commands, "termStoreImage").mockResolvedValue({ status: "ok", data: "/remote/image.png" });
Object.defineProperty(navigator, "clipboard", {
configurable: true,
@@ -304,6 +309,7 @@ it("uploads image events instead of recovering a local image path", async () =>
});
it("does not upload a menu image when the target changes while reading", async () => {
usePlatform.setState({ os: "windows" }); // the WebView menu path; macOS reads natively
let valid = true;
let finish!: (value: Blob) => void;
const getType = vi.fn(
@@ -446,6 +452,7 @@ function localTarget(shell = "sh", current = () => true): TerminalPasteTarget {
}
it.each(["event", "menu"])("stores raw local clipboard media through %s paste", async (route) => {
usePlatform.setState({ os: "windows" }); // the WebView menu path; macOS reads natively
const store = vi.spyOn(commands, "termStoreImage").mockResolvedValue({ status: "ok", data: "/tmp/a'b c.png" });
const host = document.createElement("div");
const paste = vi.fn();
@@ -632,7 +639,7 @@ it.each([
{ os: "linux", native: "ls -la", expected: ["ls -la"], execCommand: 0 },
// An image-only clipboard keeps the WebView paths.
{ os: "linux", native: "", expected: [], execCommand: 1 },
{ os: "macos", native: "ls -la", expected: ["ls -la"], execCommand: 1 },
{ os: "macos", native: "ls -la", expected: ["ls -la"], execCommand: 0 },
] as const)("menu paste on $os with native text '$native'", async ({ os, native, expected, execCommand }) => {
usePlatform.setState({ os });
vi.spyOn(commands, "clipboardText").mockResolvedValue({ status: "ok", data: native });
@@ -651,3 +658,68 @@ it.each([
expect(exec).toHaveBeenCalledTimes(execCommand);
expect(paste.mock.calls).toEqual(expected.map((text) => [text]));
});
// WebKit on macOS shows a "Paste" callout for execCommand("paste") and navigator.clipboard reads
// outside a paste event: a menu paste reads text, files and images through the backend.
it.each([
{ name: "text", text: "ls -la", files: [], png: null, target: localTarget, expected: "ls -la" },
{
name: "Finder file",
text: "a b.txt",
files: ["/x/a b.txt"],
png: null,
target: localTarget,
expected: "'/x/a b.txt'",
},
{ name: "screenshot", text: null, files: [], png: "AQI=", target: localTarget, expected: "'/tmp/shot.png'" },
{ name: "remote screenshot", text: null, files: [], png: "AQI=", target: remoteTarget, expected: "'/tmp/shot.png'" },
{ name: "empty clipboard", text: null, files: [], png: null, target: localTarget, expected: null },
{
name: "remote file list",
text: "",
files: ["/x/a b.txt"],
png: null,
target: remoteTarget,
expected: "/x/a b.txt",
},
])("macOS menu paste of $name never asks WebKit", async ({ text, files, png, target, expected }) => {
usePlatform.setState({ os: "macos" });
vi.spyOn(commands, "clipboardText").mockResolvedValue({ status: "ok", data: text });
vi.spyOn(commands, "clipboardFileList").mockResolvedValue({ status: "ok", data: files });
vi.spyOn(commands, "clipboardImage").mockResolvedValue({
status: "ok",
data: png && `data:image/png;base64,${png}`,
});
const store = vi.spyOn(commands, "termStoreImage").mockResolvedValue({ status: "ok", data: "/tmp/shot.png" });
const web = { readText: vi.fn(async () => "web"), read: vi.fn(async () => []) };
Object.defineProperty(navigator, "clipboard", { configurable: true, value: web });
const exec = vi.fn(() => false);
Object.defineProperty(document, "queryCommandSupported", { configurable: true, value: () => true });
Object.defineProperty(document, "execCommand", { configurable: true, value: exec });
const paste = vi.fn();
try {
await pasteTerminalClipboard(paste, () => target());
} finally {
Reflect.deleteProperty(document, "queryCommandSupported");
Reflect.deleteProperty(document, "execCommand");
}
expect(exec).not.toHaveBeenCalled();
expect(web.readText).not.toHaveBeenCalled();
expect(web.read).not.toHaveBeenCalled();
expect(paste.mock.calls).toEqual(expected ? [[expected]] : []);
if (png) expect(store).toHaveBeenCalledWith(42, png, "image/png");
expect(notify).not.toHaveBeenCalled();
});
it("keeps the WebView menu paste for a browser on macOS", async () => {
vi.unstubAllGlobals();
const store = vi.spyOn(commands, "termStoreImage").mockResolvedValue({ status: "ok", data: "/remote/image.png" });
Object.defineProperty(navigator, "clipboard", {
configurable: true,
value: { readText: async () => "", read: async () => [{ types: ["image/png"], getType: async () => image() }] },
});
const paste = vi.fn();
await pasteTerminalClipboard(paste, () => remoteTarget());
expect(store).toHaveBeenCalledWith(42, "AQI=", "image/png");
expect(paste).toHaveBeenCalledWith("'/remote/image.png'");
});
+24 -2
Переглянути файл
@@ -1,6 +1,6 @@
import { pasteClipboardFiles, readClipboardPlainText, readClipboardText } from "@/platform/clipboard";
import { pasteClipboardFiles, readClipboardPlainText, readClipboardPng, readClipboardText } from "@/platform/clipboard";
import { toBase64 } from "@/platform/base64";
import { call, commands, type TerminalId } from "@/platform/ipc";
import { call, commands, isTauri, type TerminalId } from "@/platform/ipc";
import { tx } from "@/platform/i18n";
import { usePlatform } from "@/platform/platformInfo";
import { notifications } from "@/workbench/contributions";
@@ -139,6 +139,28 @@ export async function pasteTerminalClipboard(paste: (text: string) => void, getT
return;
}
}
// WebKit on macOS asks the user to confirm execCommand("paste") and Clipboard.read() from a
// menu with a "Paste" callout; the backend reads files, text and images without asking.
if (target && isTauri() && usePlatform.getState().os === "macos") {
const paths: string[] = await call(commands.clipboardFileList()).catch(() => []);
const text =
paths.length && !target.remote ? pathsText(paths, target) : await readClipboardPlainText().catch(() => "");
if (!target.current()) return;
if (text) {
paste(text);
return;
}
const png = await readClipboardPng();
if (!target.current()) return;
if (png)
await pasteMedia(
new Blob([Uint8Array.from(atob(png), (c) => c.charCodeAt(0))], { type: "image/png" }),
target,
paste,
);
else if (paths.length) paste(paths.join("\n"));
return;
}
// Native paste preserves clipboard blobs where Clipboard.read() is unavailable.
if (target && document.queryCommandSupported?.("paste") && document.execCommand("paste")) return;
const images =
+1
Переглянути файл
@@ -1130,6 +1130,7 @@ export function ChangesTree({ mode, amended }: { mode: "commit" | "local" | "dia
>
<Tree<ChangeNode>
handleRef={treeRef}
horizontalScroll
roots={roots}
getKey={(n) => n.key}
getLabel={nodeText}
+25 -12
Переглянути файл
@@ -438,9 +438,12 @@ function TwoPaneDiff({
inputKey.current = input.key;
// Swap Sides shows the request's sides the other way round; another request starts unswapped.
const [swappedFor, setSwappedFor] = useState<DiffData | null>(null);
// The one-side viewer puts its only editable document into the unified editor.
const indexOnlyLeft = isIndex(input_.left) && input_.right.type === "text" && input_.right.absent;
const swapped = !!indexOnlyLeft || swappedFor === input_;
// The one-side viewer puts its only editable document into the unified editor. A deleted
// file's diff shows the original text as the document itself: the absent side stays on the
// left as the diff's original, as for a staged deletion.
const deletedOneSided =
!(input_.left.type === "text" && input_.left.absent) && input_.right.type === "text" && !!input_.right.absent;
const swapped = deletedOneSided || swappedFor === input_;
const data = useMemo(
() => (swapped ? { ...input_, left: input_.right, right: input_.left } : input_),
[input_, swapped],
@@ -1788,7 +1791,7 @@ function TwoPaneDiff({
return (
<div
ref={rootRef}
className={clsx(styles.root, fit && styles.fit, indexOnlyLeft && styles.indexDeletion)}
className={clsx(styles.root, fit && styles.fit, deletedOneSided && styles.indexDeletion)}
onKeyDown={onKeyDown}
onFocusCapture={() => {
setFocusedDiffNavigator(nav.current);
@@ -1994,7 +1997,7 @@ function TwoPaneDiff({
size="small"
onClick={() => {
void Promise.resolve(indexDoc?.save())
.then(() => executeAction("vcs.showDiffInNewWindow", indexOnlyLeft ? input_ : data))
.then(() => executeAction("vcs.showDiffInNewWindow", deletedOneSided ? input_ : data))
.catch(() => {});
}}
/>
@@ -2049,15 +2052,25 @@ function TwoPaneDiff({
</span>
</div>
) : (
// A deleted file's swapped viewer still reads in the request's order: revision → (deleted).
<div className={labels}>
<span className={styles.label} title={sourceLabels ? `${captionA} → ${captionB}` : undefined}>
<span className={styles.labelText}>{sideLabel(left)}</span>
{sourceLabels && <PaneTitleDetail {...titleA} />}
<span
className={styles.label}
title={
sourceLabels ? (deletedOneSided ? `${captionB} → ${captionA}` : `${captionA} → ${captionB}`) : undefined
}
>
<span className={styles.labelText}>{sideLabel(deletedOneSided ? right : left)}</span>
{sourceLabels && <PaneTitleDetail {...(deletedOneSided ? titleB : titleA)} />}
{unifiedOnLeft && <span className={styles.badge}>{tx("editable")}</span>}
{eolDiffers && eolA && <span className={styles.badge}>{badgeA}</span>} →
<span className={styles.labelText}>{sideLabel(right)}</span>
{sourceLabels && <PaneTitleDetail {...titleB} />}
{eolDiffers && eolB && <span className={styles.badge}>{badgeB}</span>}
{eolDiffers && (deletedOneSided ? eolB : eolA) && (
<span className={styles.badge}>{deletedOneSided ? badgeB : badgeA}</span>
)}{" "}
→<span className={styles.labelText}>{sideLabel(deletedOneSided ? left : right)}</span>
{sourceLabels && <PaneTitleDetail {...(deletedOneSided ? titleA : titleB)} />}
{eolDiffers && (deletedOneSided ? eolA : eolB) && (
<span className={styles.badge}>{deletedOneSided ? badgeA : badgeB}</span>
)}
</span>
</div>
)}
+2 -1
Переглянути файл
@@ -37,7 +37,8 @@ export function blockOf(text: string, [from, to]: readonly [number, number]): st
/** The rows of the list: Local Changes when the block differs from HEAD, then the commits. */
export function historyRows(history: BlockHistory, current: string): HistoryRow[] {
const rows: HistoryRow[] = history.revisions.map((revision) => ({ kind: "revision", revision }));
const head = history.revisions[0]?.after;
// Servers that predate `head` only give the newest row's block, which a merge leaves empty.
const head = history.head ?? history.revisions[0]?.after;
if (history.headLines && head !== undefined && head !== current) rows.unshift({ kind: "local", head, current });
return rows;
}
+48
Переглянути файл
@@ -0,0 +1,48 @@
import { render, screen } from "@testing-library/react";
import { beforeEach, describe, expect, it, vi } from "vitest";
vi.mock("@/platform/ipc", async (importOriginal) => {
const real = await importOriginal<typeof import("@/platform/ipc")>();
return { ...real, call: vi.fn() };
});
vi.mock("../DiffEditor", () => ({ DiffEditor: () => <div /> }));
import { ChangesTree } from "../CommitView";
import { useVcs } from "../store";
import { useProject } from "@/platform/project";
const NAME = "some_long_service_implementation_with_a_very_long_name.ts";
describe("changes tree width (#6080)", () => {
beforeEach(() => {
localStorage.clear();
useProject.setState({
project: { name: "p", root: "/p", trusted: true, isGit: true, settings: {} } as never,
settings: {} as never,
});
useVcs.setState({
root: "/p",
repo: "/p",
roots: ["/p"],
status: [
{
path: `/p/src/features/some_long_module_name/${NAME}`,
relPath: `src/features/some_long_module_name/${NAME}`,
staged: null,
unstaged: "modified" as const,
renamedFrom: null,
},
],
});
});
it.each(["commit", "local"] as const)("scrolls horizontally in %s mode instead of clipping rows", (mode) => {
render(<ChangesTree mode={mode} />);
const tree = screen.getByRole("tree", { name: "Changes" });
// The rows keep their natural width and the tree tracks the widest one for its scroll range.
expect(tree.querySelector("[data-content-width]")).not.toBeNull();
const row = screen.getByText(NAME).closest("[data-row]") as HTMLElement;
expect(row.className).toMatch(/wideRow/);
});
});
+76
Переглянути файл
@@ -0,0 +1,76 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { render, waitFor } from "@testing-library/react";
import type { EditorInput } from "@/workbench/contributions";
const texts: Record<string, string> = { HEAD: "a\nb\nc\n" };
vi.mock("@/platform/ipc", async (importOriginal) => {
const real = await importOriginal<typeof import("@/platform/ipc")>();
return {
...real,
commands: {
...real.commands,
fsProbe: () => Promise.resolve({ status: "ok", data: { size: 0, binary: false, tooLarge: false } }),
vcsFileAt: (_path: string, rev: string) => Promise.resolve({ status: "ok", data: texts[rev] }),
},
};
});
import { DiffEditor } from "../DiffEditor";
const input = {
kind: "diff",
key: "diff:deleted",
data: {
path: "/p/a.ts",
left: { type: "rev", rev: "HEAD" },
right: { type: "text", text: "", label: "(deleted)", absent: true },
},
} as unknown as EditorInput;
/** Plain gutter numbers rendered for document lines (skipping the hidden width-calibration spacer). */
const gutterNumbers = (container: HTMLElement) =>
[...container.querySelectorAll(".cm-lineNumbers .cm-gutterElement")]
.filter((n) => (n as HTMLElement).style.visibility !== "hidden")
.map((n) => n.textContent)
.filter((t) => t && /^\d+$/.test(t));
describe("line numbers of a deleted file's diff", () => {
beforeEach(() => localStorage.clear());
afterEach(() => localStorage.clear());
it("shows the original text as the document itself, numbered like an editor", async () => {
const mounted = render(<DiffEditor input={input} />);
try {
await waitFor(() => expect(mounted.container.querySelectorAll(".cm-editor")).toHaveLength(1));
// "a\nb\nc\n" is four CodeMirror lines, the last one empty, as in the editor itself.
await waitFor(() => expect(gutterNumbers(mounted.container)).toEqual(["1", "2", "3", "4"]));
const lines = [...mounted.container.querySelectorAll(".cm-content > .cm-line")].map((l) => l.textContent);
expect(lines).toEqual(["a", "b", "c", ""]);
// No mirrored widget numbers: the lines are real, so the gutter, selection and context
// menu behave like the editor's.
expect(mounted.container.querySelector(".cm-diffWidgetNumber")).toBeNull();
} finally {
mounted.unmount();
}
});
it("keeps the document's own numbers for an added file", async () => {
const added = {
...input,
data: {
path: "/p/a.ts",
left: { type: "text", text: "", label: "(does not exist)", absent: true },
right: { type: "rev", rev: "HEAD" },
},
} as unknown as EditorInput;
texts.HEAD = "a\nb\nc\n";
const mounted = render(<DiffEditor input={added} />);
try {
await waitFor(() => expect(mounted.container.querySelectorAll(".cm-editor")).toHaveLength(1));
await waitFor(() => expect(gutterNumbers(mounted.container)).toContain("3"));
} finally {
mounted.unmount();
}
});
});
+83 -2
Переглянути файл
@@ -1,8 +1,9 @@
import { describe, expect, it, vi } from "vitest";
import { Chunk, MergeView } from "@codemirror/merge";
import { Text } from "@codemirror/state";
import type { EditorView } from "@codemirror/view";
import { EditorState, Text } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { bandAt, bandPath, transferY, PaddedPanes, UnalignedPanes, type Band } from "../diffScroll";
import { collapsedDiffLines } from "../collapsedDiffLines";
import { readFileSync } from "node:fs";
import { resolve } from "node:path";
@@ -177,6 +178,32 @@ describe("synchronized navigation scrolling", () => {
vi.useRealTimers();
}
});
it("keeps the wheel-scrolled pane in charge when the follower pane adjusts scrollTop on measure", () => {
vi.useFakeTimers();
const frame = vi.spyOn(window, "requestAnimationFrame").mockReturnValue(1);
const p = panes();
try {
p.b.scrollDOM.dispatchEvent(new Event("wheel"));
p.scroll(p.b, 1200);
expect(p.a.scrollDOM.scrollTop).toBe(1200);
// Repeated wheel events must not cancel native momentum with scrollTo(instant).
p.b.scrollDOM.dispatchEvent(new Event("wheel"));
expect(p.b.scrollDOM.scrollTo).not.toHaveBeenCalled();
// Follower shifts from CodeMirror height measurement must not yank the wheel source back.
p.scroll(p.a, 800);
expect(p.b.scrollDOM.scrollTop).toBe(1200);
expect(p.a.scrollDOM.scrollTop).toBe(1200);
// Pointer interaction on the other pane hands control back immediately.
p.a.scrollDOM.dispatchEvent(new Event("pointerdown"));
p.scroll(p.a, 400);
expect(p.b.scrollDOM.scrollTop).toBe(400);
} finally {
p.controller.destroy();
frame.mockRestore();
vi.useRealTimers();
}
});
});
describe("padded pane scrolling (aligned diff)", () => {
@@ -241,6 +268,60 @@ describe("padded pane scrolling (aligned diff)", () => {
vi.useRealTimers();
}
});
it("keeps the wheel-scrolled pane in charge when the follower shifts during layout", () => {
vi.useFakeTimers();
const p = panes();
try {
p.b.scrollDOM.dispatchEvent(new Event("wheel"));
p.scroll(p.b, 900);
expect(p.a.scrollDOM.scrollTop).toBe(900);
p.scroll(p.a, 500);
expect(p.b.scrollDOM.scrollTop).toBe(900);
expect(p.a.scrollDOM.scrollTop).toBe(900);
vi.advanceTimersByTime(150);
p.scroll(p.a, 200);
expect(p.b.scrollDOM.scrollTop).toBe(200);
} finally {
p.controller.destroy();
vi.useRealTimers();
}
});
});
describe("collapsed diff lines", () => {
it("defers button DOM replacement from docViewUpdate into CodeMirror's measure write phase", () => {
const parent = document.createElement("div");
document.body.appendChild(parent);
const view = new EditorView({
state: EditorState.create({ doc: "a\nb\nc", extensions: [collapsedDiffLines()] }),
parent,
});
const measureSpy = vi.spyOn(view, "requestMeasure");
try {
const row = document.createElement("div");
row.className = "cm-collapsedLines";
row.textContent = "10 unchanged lines";
view.contentDOM.appendChild(row);
const plugin = (
view as unknown as { plugins: Array<{ value: { docViewUpdate?: () => void } | null }> }
).plugins.find((p) => typeof p.value?.docViewUpdate === "function");
expect(plugin).toBeDefined();
measureSpy.mockClear();
plugin!.value!.docViewUpdate!();
// Must not mutate DOM synchronously during docViewUpdate (triggers WebKit scrollTop clamping).
expect(row.querySelector("button")).toBeNull();
expect(measureSpy).toHaveBeenCalledTimes(1);
const req = measureSpy.mock.calls[0]![0] as { write?: (v: unknown, view: EditorView) => void };
req.write?.(null, view);
expect(row.querySelector("button")).not.toBeNull();
expect(row.querySelector("button")?.textContent).toBe("10 unchanged lines");
} finally {
measureSpy.mockRestore();
view.destroy();
parent.remove();
}
});
});
describe("divider arrows", () => {
+20
Переглянути файл
@@ -300,6 +300,26 @@ describe("log controls", () => {
expect(rows[0]!.querySelector<HTMLElement>('[class*="colRepository"]')!.style.width).toBe("130px");
});
it("without headers, a row strip on a leading Commit cell resizes the Repository column", async () => {
useVcs.setState({ roots: ["/repo", "/other"] });
const tip = { ...c("tip"), repo: "/repo" };
api.commits = [tip];
// Defaults: headers hidden, Commit first.
useLogOptions.setState({ showRepository: true });
render(<LogView />);
const rows = await within(screen.getByRole("listbox", { name: "Commits" })).findAllByRole("option");
const strip = rows[0]!.querySelector<HTMLElement>('[class*="colSubject"] > [class*="columnResize"]')!;
strip.setPointerCapture = vi.fn();
strip.hasPointerCapture = () => true;
strip.releasePointerCapture = vi.fn();
fireEvent.pointerDown(strip, { button: 0, pointerId: 9, clientX: 100 });
fireEvent.pointerMove(strip, { pointerId: 9, clientX: 130 });
fireEvent.pointerUp(strip, { pointerId: 9, clientX: 130 });
expect(useLogOptions.getState().columnWidths.repository).toBe(130);
// The strip swallows the press, so the row is not selected.
expect(useGitLog.getState().selected).toBeNull();
});
it("exposes a full-height column divider on data rows", async () => {
useLogOptions.setState({ showColumnHeaders: true });
render(<LogView />);
+12
Переглянути файл
@@ -92,6 +92,18 @@ describe("rows", () => {
expect(edited).toHaveLength(3);
expect(historyRows({ headLines: null, revisions: [] }, "new\n")).toEqual([]);
});
it("compares with HEAD's block, not the newest row, when that row is a merge without a diff", () => {
// `git log -L` prints no patch for a merge, so its row has empty sides.
const merge = revision("m", "Merge branch 'side'", "", "");
const merged: BlockHistory = { headLines: [1, 2], head: "TWO\nTHREE\n", revisions: [merge, ...history.revisions] };
expect(historyRows(merged, "TWO\nTHREE\n").map((r) => r.kind)).toEqual(["revision", "revision", "revision"]);
expect(historyRows(merged, "TWO\nTHREE!\n")[0]).toEqual({
kind: "local",
head: "TWO\nTHREE\n",
current: "TWO\nTHREE!\n",
});
});
});
describe("History for Selection tab", () => {
+7 -2
Переглянути файл
@@ -20,8 +20,13 @@ const collapseButtons = ViewPlugin.define((view) => {
row.replaceChildren(button);
}
};
view.requestMeasure({ read: () => null, write: enhance });
return { docViewUpdate: enhance };
// Defer DOM replacement into CodeMirror's measure write phase rather than mutating synchronously
// during docViewUpdate: in WebKit, inserting the inline SVG while updated viewport gaps have not
// flushed layout yet causes scrollTop to clamp backwards and trap wheel scrolling in a loop.
const measure = { key: enhance, read: () => null, write: enhance };
const schedule = () => view.requestMeasure(measure);
schedule();
return { docViewUpdate: schedule };
});
export function collapsedDiffLines(): Extension {
+102 -6
Переглянути файл
@@ -193,17 +193,25 @@ export interface DiffPanes {
* of the content, out of reach until the diff is scrolled to its end.
*/
export class PaddedPanes implements DiffPanes {
readonly extension: Extension = [];
readonly extension: Extension;
private mv: MergeView | null = null;
private sync: boolean;
private scrolling: Side | null = null;
private scrollTimer: ReturnType<typeof setTimeout> | undefined;
private wheelLeader: Side | null = null;
private wheelTimer: ReturnType<typeof setTimeout> | undefined;
/** The scroll position a pane was last moved to by the other one, to tell its echo from the user. */
private readonly moved: Record<Side, number | null> = { a: null, b: null };
private readonly cleanup: (() => void)[] = [];
constructor(sync: boolean) {
this.sync = sync;
this.extension = EditorView.updateListener.of((u) => {
if (u.heightChanged && !u.docChanged && this.mv) {
const side: Side | null = u.view === this.mv.a ? "a" : u.view === this.mv.b ? "b" : null;
if (side && this.moved[side] !== null) this.moved[side] = u.view.scrollDOM.scrollTop;
}
});
}
attach(mv: MergeView) {
@@ -211,8 +219,22 @@ export class PaddedPanes implements DiffPanes {
for (const side of ["a", "b"] as const) {
const el = this.view(side).scrollDOM;
const onScroll = () => this.scrolled(side);
const onWheel = () => {
this.interruptScroll();
this.leadWheel(side);
};
const onPointer = () => {
this.interruptScroll();
this.clearWheel();
};
el.addEventListener("scroll", onScroll, { passive: true });
this.cleanup.push(() => el.removeEventListener("scroll", onScroll));
el.addEventListener("wheel", onWheel, { passive: true });
el.addEventListener("pointerdown", onPointer);
this.cleanup.push(() => {
el.removeEventListener("scroll", onScroll);
el.removeEventListener("wheel", onWheel);
el.removeEventListener("pointerdown", onPointer);
});
}
this.resync();
}
@@ -225,12 +247,14 @@ export class PaddedPanes implements DiffPanes {
setSync(on: boolean) {
if (on === this.sync) return;
this.interruptScroll();
this.clearWheel();
this.sync = on;
this.resync();
}
scrollTo(side: Side, options: ScrollToOptions) {
this.interruptScroll();
this.clearWheel();
this.scrolling = this.sync ? side : null;
this.releaseScroll();
this.view(side).scrollDOM.scrollTo(options);
@@ -241,12 +265,14 @@ export class PaddedPanes implements DiffPanes {
* other pane's delayed reflow follows it instead of being mistaken for a user scroll pulling back.
*/
leadScroll(side: Side) {
this.clearWheel();
this.scrolling = this.sync ? side : null;
this.releaseScroll();
}
destroy() {
clearTimeout(this.scrollTimer);
clearTimeout(this.wheelTimer);
for (const f of this.cleanup) f();
this.mv = null;
}
@@ -262,6 +288,16 @@ export class PaddedPanes implements DiffPanes {
this.releaseScroll();
return;
}
if (this.wheelLeader) {
this.moved[from] = null;
if (from === this.wheelLeader) {
this.leadWheel(from);
if (this.sync) this.follow(from);
} else if (this.sync) {
this.follow(this.wheelLeader);
}
return;
}
const el = this.view(from).scrollDOM;
const moved = this.moved[from];
const echo = moved !== null && Math.abs(el.scrollTop - moved) <= 1;
@@ -269,6 +305,17 @@ export class PaddedPanes implements DiffPanes {
if (!echo && this.sync) this.follow(from);
}
private leadWheel(side: Side) {
this.wheelLeader = this.sync ? side : null;
clearTimeout(this.wheelTimer);
if (this.wheelLeader) this.wheelTimer = setTimeout(() => (this.wheelLeader = null), 150);
}
private clearWheel() {
this.wheelLeader = null;
clearTimeout(this.wheelTimer);
}
private follow(from: Side) {
const to: Side = from === "a" ? "b" : "a";
const el = this.view(to).scrollDOM;
@@ -314,6 +361,8 @@ export class UnalignedPanes implements DiffPanes {
private sync: boolean;
private scrolling: Side | null = null;
private scrollTimer: ReturnType<typeof setTimeout> | undefined;
private wheelLeader: Side | null = null;
private wheelTimer: ReturnType<typeof setTimeout> | undefined;
private frame = -1;
private resize: ResizeObserver | null = null;
private readonly cleanup: (() => void)[] = [];
@@ -326,7 +375,19 @@ export class UnalignedPanes implements DiffPanes {
opts.initialRatio != null && Number.isFinite(opts.initialRatio)
? Math.min(MAX_RATIO, Math.max(MIN_RATIO, opts.initialRatio))
: loadRatio();
this.extension = [gapMarks, changedLineGutters, EditorView.updateListener.of(() => this.schedule())];
this.extension = [
gapMarks,
changedLineGutters,
EditorView.updateListener.of((u) => {
// When CodeMirror's measure adjusts a follower pane's scrollTop after line heights resolve,
// update the expected echo so the layout adjustment is not mistaken for a user scroll.
if (u.heightChanged && !u.docChanged && this.mv) {
const side: Side | null = u.view === this.mv.a ? "a" : u.view === this.mv.b ? "b" : null;
if (side && this.moved[side].top !== null) this.moved[side].top = u.view.scrollDOM.scrollTop;
}
this.schedule();
}),
];
this.divider.className = "cm-diffDivider";
// A lone arrow is centred in the divider; a pair keeps to the two edges.
this.divider.classList.toggle("cm-diffDivider-lone", !!opts.arrows && opts.arrows.toA !== opts.arrows.toB);
@@ -349,13 +410,20 @@ export class UnalignedPanes implements DiffPanes {
for (const side of ["a", "b"] as const) {
const el = this.view(side).scrollDOM;
const onScroll = () => this.scrolled(side);
const onPointer = () => this.interruptScroll();
const onWheel = () => {
this.interruptScroll();
this.leadWheel(side);
};
const onPointer = () => {
this.interruptScroll();
this.clearWheel();
};
el.addEventListener("scroll", onScroll, { passive: true });
el.addEventListener("wheel", onPointer, { passive: true });
el.addEventListener("wheel", onWheel, { passive: true });
el.addEventListener("pointerdown", onPointer);
this.cleanup.push(() => {
el.removeEventListener("scroll", onScroll);
el.removeEventListener("wheel", onPointer);
el.removeEventListener("wheel", onWheel);
el.removeEventListener("pointerdown", onPointer);
});
}
@@ -428,6 +496,7 @@ export class UnalignedPanes implements DiffPanes {
const onWheel = (e: WheelEvent) => {
e.preventDefault();
this.interruptScroll();
this.leadWheel("b");
mv.b.scrollDOM.scrollBy(e.deltaX, e.deltaY);
};
this.divider.addEventListener("wheel", onWheel, { passive: false });
@@ -459,17 +528,30 @@ export class UnalignedPanes implements DiffPanes {
setSync(on: boolean) {
if (on === this.sync) return;
this.interruptScroll();
this.clearWheel();
this.sync = on;
this.resync();
}
scrollTo(side: Side, options: ScrollToOptions) {
this.interruptScroll();
this.clearWheel();
this.scrolling = this.sync ? side : null;
this.releaseScroll();
this.view(side).scrollDOM.scrollTo(options);
}
private leadWheel(side: Side) {
this.wheelLeader = this.sync ? side : null;
clearTimeout(this.wheelTimer);
if (this.wheelLeader) this.wheelTimer = setTimeout(() => (this.wheelLeader = null), 150);
}
private clearWheel() {
this.wheelLeader = null;
clearTimeout(this.wheelTimer);
}
private releaseScroll() {
clearTimeout(this.scrollTimer);
if (this.scrolling) this.scrollTimer = setTimeout(() => (this.scrolling = null), 150);
@@ -487,6 +569,7 @@ export class UnalignedPanes implements DiffPanes {
destroy() {
clearTimeout(this.scrollTimer);
clearTimeout(this.wheelTimer);
if (this.frame >= 0) cancelAnimationFrame(this.frame);
this.resize?.disconnect();
for (const f of this.cleanup) f();
@@ -518,6 +601,19 @@ export class UnalignedPanes implements DiffPanes {
this.schedule();
return;
}
if (this.wheelLeader) {
// Keep the actively wheel-scrolled pane in charge so follower measure adjustments never pull it back.
const moved = this.moved[side];
moved.top = moved.left = null;
if (side === this.wheelLeader) {
this.leadWheel(side);
if (this.sync) this.follow(side);
} else if (this.sync) {
this.follow(this.wheelLeader);
}
this.schedule();
return;
}
const el = this.view(side).scrollDOM;
const moved = this.moved[side];
const echo =
+16 -5
Переглянути файл
@@ -105,8 +105,24 @@ function CommitRowView({
left={opts.refsOnLeft}
/>
);
const repository = opts.showRepository && !!commitRepo(c) && useVcs.getState().roots.length > 1;
// The header's neighbours: an id without a shown column (a hidden one) is skipped.
const visibleIds = columnSequence(opts.columnOrder, columns).filter(
(cid) => cid === SUBJECT_COLUMN.id || columns.some((col) => col.id === cid),
);
const subjectCell = (
<span key={SUBJECT_COLUMN.id} className={styles.colSubject}>
{/* A leading Commit cell's left edge is the only row divider for the Repository column. */}
{repository && visibleIds[0] === SUBJECT_COLUMN.id && (
<RowResizeHandle
target={{
id: SUBJECT_COLUMN.id,
width: 0,
...columnPrev(visibleIds, SUBJECT_COLUMN.id, opts, columns, repository),
leftOnly: true,
}}
/>
)}
{graph && (
<GraphCell
row={graph}
@@ -161,11 +177,6 @@ function CommitRowView({
</Popup>
</span>
);
const repository = opts.showRepository && !!commitRepo(c) && useVcs.getState().roots.length > 1;
// The header's neighbours: an id without a shown column (a hidden one) is skipped.
const visibleIds = columnSequence(opts.columnOrder, columns).filter(
(cid) => cid === SUBJECT_COLUMN.id || columns.some((col) => col.id === cid),
);
return (
<div
id={id}
+25
Переглянути файл
@@ -1,7 +1,9 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { commands } from "./ipc";
import { usePlatform } from "./platformInfo";
import {
pasteClipboardFiles,
readClipboardPlainText,
readClipboardPng,
readClipboardText,
writeClipboardPng,
@@ -44,6 +46,29 @@ describe("clipboard text", () => {
expect(list).toHaveBeenCalledTimes(calls);
});
// WebKit on macOS asks the user to confirm navigator.clipboard reads outside a paste event.
it("treats no native text on macOS as empty, but falls back when the backend refuses", async () => {
usePlatform.setState({ os: "macos" });
const readText = vi.fn(async () => "web");
Object.defineProperty(navigator, "clipboard", { configurable: true, value: { readText } });
const native = vi.spyOn(commands, "clipboardText").mockResolvedValue({ status: "ok", data: null });
expect(await readClipboardPlainText()).toBe("");
expect(readText).not.toHaveBeenCalled();
native.mockRejectedValue(new Error("restricted"));
expect(await readClipboardPlainText()).toBe("web");
});
it("falls back to the WebView where the backend has no text reader", async () => {
usePlatform.setState({ os: "windows" });
Object.defineProperty(navigator, "clipboard", { configurable: true, value: { readText: async () => "web" } });
vi.spyOn(commands, "clipboardText").mockResolvedValue({ status: "ok", data: null });
try {
expect(await readClipboardPlainText()).toBe("web");
} finally {
usePlatform.setState({ os: "macos" });
}
});
it("does not consult files for an empty text-only event or a browser", async () => {
const list = vi.spyOn(commands, "clipboardFileList");
expect(await readClipboardText(transfer("", false))).toBe("");
+4 -1
Переглянути файл
@@ -1,6 +1,7 @@
import { call, commands, isTauri } from "./ipc";
import { ipcPath } from "./paths";
import { toBase64 } from "./base64";
import { usePlatform } from "./platformInfo";
/** Native menu actions and async work can outlive WebKit's user activation. */
export async function writeClipboardText(text: string): Promise<void> {
@@ -28,8 +29,10 @@ export async function writeClipboardPng(png: Promise<Blob>): Promise<void> {
*/
export async function readClipboardPlainText(): Promise<string> {
if (isTauri()) {
const text = await call(commands.clipboardText()).catch(() => null);
const text = await call(commands.clipboardText()).catch(() => undefined);
if (text != null) return text;
// WebKit on macOS makes the user confirm the read with a "Paste" callout; the backend found no text.
if (text === null && usePlatform.getState().os === "macos") return "";
}
return (await navigator.clipboard?.readText()) ?? "";
}
+33
Переглянути файл
@@ -712,3 +712,36 @@ describe(".icls schemes", () => {
}
});
});
describe("annotation colour (#6108)", () => {
const opt = (name: string, value: string) =>
`<option name="${name}"><value><option name="FOREGROUND" value="${value}"/></value></option>`;
const scheme = (parent: string | null, ...options: string[]) =>
parseIcls(
`<scheme name="A"${parent ? ` parent_scheme="${parent}"` : ""}><attributes>${options.join("")}</attributes></scheme>`,
).scheme;
it.each([
["Default", "#808000"],
["Darcula", "#bbb529"],
])("keeps %s's own annotation colour when the file only changes DEFAULT_METADATA", (parent, colour) => {
// IntelliJ shows Java annotations with the parent's ANNOTATION_NAME_ATTRIBUTES, not the file's default.
expect(scheme(parent, opt("DEFAULT_METADATA", "1d8711")).attributes.metadata?.foreground).toBe(colour);
});
it("takes the file's annotation key over its DEFAULT_METADATA", () => {
const s = scheme("Default", opt("DEFAULT_METADATA", "1d8711"), opt("ANNOTATION_NAME_ATTRIBUTES", "9e880d"));
expect(s.attributes.metadata?.foreground).toBe("#9e880d");
});
it("uses DEFAULT_METADATA without a bundled parent", () => {
expect(scheme(null, opt("DEFAULT_METADATA", "1d8711")).attributes.metadata?.foreground).toBe("#1d8711");
});
it("exports the annotation colour under the annotation key, so it survives a re-import", () => {
const imported = scheme("Default", opt("ANNOTATION_NAME_ATTRIBUTES", "9e880d"));
const xml = exportIcls("custom-a", { "custom-a": imported });
expect(xml).toContain('<option name="ANNOTATION_NAME_ATTRIBUTES">');
expect(parseIcls(xml).scheme.attributes.metadata?.foreground).toBe("#9e880d");
});
});
+8
Переглянути файл
@@ -40,6 +40,8 @@ const ATTRIBUTE_NAMES: Record<string, string> = {
DEFAULT_DOC_COMMENT_TAG: "docCommentTag",
DEFAULT_DOC_COMMENT_TAG_VALUE: "docCommentTagValue",
DEFAULT_DOC_MARKUP: "docCommentMarkup",
// Java's annotation key outranks the default it falls back to.
ANNOTATION_NAME_ATTRIBUTES: "metadata",
DEFAULT_METADATA: "metadata",
DEFAULT_OPERATION_SIGN: "operator",
DEFAULT_PARENTHS: "operator",
@@ -297,6 +299,8 @@ for (const id of [
// its fallback's. TypeScript keys win over JavaScript (TS.* falls back to JS.*), then Python, then the
// shared defaults; within a language, the key listed first above. DEFAULT_DOT, _COMMA and _SEMICOLON are
// not mapped: the one punctuation colour here would spread them to every brace and operator.
/** ANNOTATION_NAME_ATTRIBUTES as IntelliJ's bundled Default and Darcula schemes set it. */
const PARENT_ANNOTATIONS: Record<string, string> = { Default: "#808000", Darcula: "#bbb529" };
const KEY_ORDER = new Map(Object.keys(ATTRIBUTE_NAMES).map((name, i) => [name, i]));
const LANGUAGE_PRECEDENCE = ["TS.", "JS.", "PY."];
const precedence = (name: string) => {
@@ -488,6 +492,10 @@ export function parseIcls(
const own = new Set([...entries.keys()].flatMap((name) => (name ? targets(name) : [])));
for (const [id, value] of Object.entries(DARCULA_ATTRIBUTES)) if (!own.has(id)) attributes[id] ??= { ...value };
}
// Both bundled parents set Java's annotation key itself, so a file that leaves it out shows the parent's
// colour there, not its own DEFAULT_METADATA.
if (Object.hasOwn(PARENT_ANNOTATIONS, parentName) && !entries.has("ANNOTATION_NAME_ATTRIBUTES"))
attributes.metadata = { bold: false, italic: false, foreground: PARENT_ANNOTATIONS[parentName]! };
const bg = attributes.text?.background;
const rgb = bg ? [1, 3, 5].map((i) => parseInt(bg.slice(i, i + 2), 16)) : [255, 255, 255];
const dark = rgb[0]! * 0.299 + rgb[1]! * 0.587 + rgb[2]! * 0.114 < 128;
+3 -1
Переглянути файл
@@ -4071,5 +4071,7 @@
"Granted with grant option": "Granted with grant option",
"No privileges are granted on this table.": "No privileges are granted on this table.",
"* With grant option: the grantee may grant the privilege to others.": "* With grant option: the grantee may grant the privilege to others.",
"Separate several prefixes with commas: they are tried in order, then the official source.": "Separate several prefixes with commas: they are tried in order, then the official source."
"Separate several prefixes with commas: they are tried in order, then the official source.": "Separate several prefixes with commas: they are tried in order, then the official source.",
"The backend of another OpenIDEA build, for example the one from before an upgrade, still has this project open, so this build can't open it. Stop that backend and open the project? Its terminals, runs and agent sessions end, and changes it hasn't saved are lost.": "The backend of another OpenIDEA build, for example the one from before an upgrade, still has this project open, so this build can't open it. Stop that backend and open the project? Its terminals, runs and agent sessions end, and changes it hasn't saved are lost.",
"Stop Backend and Open": "Stop Backend and Open"
}
+3
Переглянути файл
@@ -1700,6 +1700,9 @@
"Reload All Gradle Projects": "Recargar todos los proyectos de Gradle",
"Reload All Maven Projects": "Recargar todos los proyectos de Maven",
"Reload Changed Classes": "Recargar clases modificadas",
"Enhanced class redefinition": "Redefinición de clases mejorada",
"When debugging on JetBrains Runtime, Reload Changed Classes can also add or remove methods and fields": "Al depurar en JetBrains Runtime, Recargar clases modificadas también puede añadir o eliminar métodos y campos",
"To add or remove methods and fields, turn on Enhanced class redefinition in the run configuration and debug on JetBrains Runtime.": "Para añadir o eliminar métodos y campos, activa Redefinición de clases mejorada en la configuración de ejecución y depura en JetBrains Runtime.",
"Reload Environments": "Recargar entornos",
"Reload History": "Recargar historial",
"Reload List of Packages": "Recargar lista de paquetes",
+3
Переглянути файл
@@ -1619,6 +1619,9 @@
"Reload All Gradle Projects": "Recharger tous les projets Gradle",
"Reload All Maven Projects": "Recharger tous les projets Maven",
"Reload Changed Classes": "Recharger les classes modifiées",
"Enhanced class redefinition": "Redéfinition de classes étendue",
"When debugging on JetBrains Runtime, Reload Changed Classes can also add or remove methods and fields": "Lors du débogage sur JetBrains Runtime, Recharger les classes modifiées peut aussi ajouter ou supprimer des méthodes et des champs",
"To add or remove methods and fields, turn on Enhanced class redefinition in the run configuration and debug on JetBrains Runtime.": "Pour ajouter ou supprimer des méthodes et des champs, activez Redéfinition de classes étendue dans la configuration d'exécution et déboguez sur JetBrains Runtime.",
"Reload Environments": "Recharger les environnements",
"Reload History": "Recharger l'historique",
"Reload List of Packages": "Recharger la liste des paquets",
+3
Переглянути файл
@@ -1750,6 +1750,9 @@
"Reload All Gradle Projects": "모든 Gradle 프로젝트 다시 로드",
"Reload All Maven Projects": "모든 Maven 프로젝트 다시 로드",
"Reload Changed Classes": "변경된 클래스 다시 로드",
"Enhanced class redefinition": "향상된 클래스 재정의",
"When debugging on JetBrains Runtime, Reload Changed Classes can also add or remove methods and fields": "JetBrains Runtime에서 디버그할 때 변경된 클래스 다시 로드로 메서드와 필드도 추가하거나 제거할 수 있습니다",
"To add or remove methods and fields, turn on Enhanced class redefinition in the run configuration and debug on JetBrains Runtime.": "메서드와 필드를 추가하거나 제거하려면 실행 구성에서 향상된 클래스 재정의를 켜고 JetBrains Runtime에서 디버그하세요.",
"Reload Environments": "환경 다시 로드",
"Reload History": "기록 다시 로드",
"Reload List of Packages": "패키지 목록 다시 로드",
+3
Переглянути файл
@@ -1690,6 +1690,9 @@
"Reload All Gradle Projects": "Przeładuj wszystkie projekty Gradle",
"Reload All Maven Projects": "Przeładuj wszystkie projekty Maven",
"Reload Changed Classes": "Przeładuj zmienione klasy",
"Enhanced class redefinition": "Rozszerzona redefinicja klas",
"When debugging on JetBrains Runtime, Reload Changed Classes can also add or remove methods and fields": "Podczas debugowania w JetBrains Runtime Przeładuj zmienione klasy może też dodawać lub usuwać metody i pola",
"To add or remove methods and fields, turn on Enhanced class redefinition in the run configuration and debug on JetBrains Runtime.": "Aby dodawać lub usuwać metody i pola, włącz Rozszerzoną redefinicję klas w konfiguracji uruchomieniowej i debuguj w JetBrains Runtime.",
"Reload Environments": "Przeładuj środowiska",
"Reload History": "Przeładuj historię",
"Reload List of Packages": "Przeładuj listę pakietów",
+3
Переглянути файл
@@ -1690,6 +1690,9 @@
"Reload All Gradle Projects": "Recarregar todos os projetos Gradle",
"Reload All Maven Projects": "Recarregar todos os projetos Maven",
"Reload Changed Classes": "Recarregar classes alteradas",
"Enhanced class redefinition": "Redefinição de classes aprimorada",
"When debugging on JetBrains Runtime, Reload Changed Classes can also add or remove methods and fields": "Ao depurar no JetBrains Runtime, Recarregar classes alteradas também pode adicionar ou remover métodos e campos",
"To add or remove methods and fields, turn on Enhanced class redefinition in the run configuration and debug on JetBrains Runtime.": "Para adicionar ou remover métodos e campos, ative Redefinição de classes aprimorada na configuração de execução e depure no JetBrains Runtime.",
"Reload Environments": "Recarregar ambientes",
"Reload History": "Recarregar histórico",
"Reload List of Packages": "Recarregar lista de pacotes",
+3
Переглянути файл
@@ -2947,6 +2947,9 @@
"Generate Sources and Update Folders": "Сгенерировать исходный код и обновить каталоги",
"Runs generate-sources, then reloads the Maven projects so generated folders become source folders": "Запускает generate-sources, затем перезагружает проекты Maven, чтобы сгенерированные каталоги стали каталогами исходного кода",
"Reload Changed Classes": "Перезагрузить изменённые классы",
"Enhanced class redefinition": "Расширенное переопределение классов",
"When debugging on JetBrains Runtime, Reload Changed Classes can also add or remove methods and fields": "При отладке на JetBrains Runtime команда «Перезагрузить изменённые классы» также может добавлять и удалять методы и поля",
"To add or remove methods and fields, turn on Enhanced class redefinition in the run configuration and debug on JetBrains Runtime.": "Чтобы добавлять или удалять методы и поля, включите «Расширенное переопределение классов» в конфигурации запуска и отлаживайте на JetBrains Runtime.",
"Reload Environments": "Перезагрузить окружения",
"Reload History": "Перезагрузить историю",
"Reload List of Packages": "Перезагрузить список пакетов",
+3
Переглянути файл
@@ -4449,6 +4449,9 @@
"Reload All Gradle Projects": "Tüm Gradle Projelerini Yeniden Yükle",
"Reload All Maven Projects": "Tüm Maven Projelerini Yeniden Yükle",
"Reload Changed Classes": "Değiştirilen Sınıfları Yeniden Yükle",
"Enhanced class redefinition": "Gelişmiş sınıf yeniden tanımlama",
"When debugging on JetBrains Runtime, Reload Changed Classes can also add or remove methods and fields": "JetBrains Runtime üzerinde hata ayıklarken Değiştirilen Sınıfları Yeniden Yükle, yöntem ve alan da ekleyip kaldırabilir",
"To add or remove methods and fields, turn on Enhanced class redefinition in the run configuration and debug on JetBrains Runtime.": "Yöntem ve alan eklemek veya kaldırmak için çalıştırma yapılandırmasında Gelişmiş sınıf yeniden tanımlamayı açın ve JetBrains Runtime üzerinde hata ayıklayın.",
"Reload Environments": "Ortamları Yeniden Yükle",
"Reload History": "Geçmişi Yeniden Yükle",
"Reload List of Packages": "Paket Listesini Yeniden Yükle",
+3
Переглянути файл
@@ -2523,6 +2523,9 @@
"Generate Sources and Update Folders": "產生原始碼並更新資料夾",
"Runs generate-sources, then reloads the Maven projects so generated folders become source folders": "執行 generate-sources,然後重新載入 Maven 專案,使產生的資料夾成為原始碼資料夾",
"Reload Changed Classes": "重新載入已更改的類別",
"Enhanced class redefinition": "增強類別重新定義",
"When debugging on JetBrains Runtime, Reload Changed Classes can also add or remove methods and fields": "在 JetBrains Runtime 上偵錯時,「重新載入已更改的類別」也可以新增或刪除方法和欄位",
"To add or remove methods and fields, turn on Enhanced class redefinition in the run configuration and debug on JetBrains Runtime.": "如需新增或刪除方法和欄位,請在執行組態中開啟「增強類別重新定義」,並使用 JetBrains Runtime 偵錯。",
"Reload Environments": "重新載入環境",
"Reload History": "重新載入歷史記錄",
"Reload List of Packages": "重新載入軟體包清單",
+6 -1
Переглянути файл
@@ -3016,6 +3016,9 @@
"Generate Sources and Update Folders": "生成源代码并更新文件夹",
"Runs generate-sources, then reloads the Maven projects so generated folders become source folders": "执行 generate-sources,然后重新加载 Maven 项目,使生成的文件夹成为源代码文件夹",
"Reload Changed Classes": "重新加载已更改的类",
"Enhanced class redefinition": "增强类重定义",
"When debugging on JetBrains Runtime, Reload Changed Classes can also add or remove methods and fields": "在 JetBrains Runtime 上调试时,“重新加载已更改的类”还可以添加或删除方法和字段",
"To add or remove methods and fields, turn on Enhanced class redefinition in the run configuration and debug on JetBrains Runtime.": "如需添加或删除方法和字段,请在运行配置中开启“增强类重定义”,并使用 JetBrains Runtime 调试。",
"Reload Environments": "重新加载环境",
"Reload History": "重新加载历史记录",
"Reload List of Packages": "重新加载软件包列表",
@@ -10402,5 +10405,7 @@
"No privileges are granted on this table.": "此表未授予任何权限。",
"* With grant option: the grantee may grant the privilege to others.": "* WITH GRANT OPTION:被授权者可以将该权限再授予他人。",
"Separate several prefixes with commas: they are tried in order, then the official source.": "多个前缀用逗号分隔:按顺序尝试,最后回退到官方源。",
"Recent Find Usages": "最近的查找用法"
"Recent Find Usages": "最近的查找用法",
"The backend of another OpenIDEA build, for example the one from before an upgrade, still has this project open, so this build can't open it. Stop that backend and open the project? Its terminals, runs and agent sessions end, and changes it hasn't saved are lost.": "另一个 OpenIDEA 版本(例如升级前的版本)的后端仍打开着这个项目,当前版本无法打开它。要停止那个后端并打开项目吗?它的终端、运行和智能体会话会结束,未保存的修改会丢失。",
"Stop Backend and Open": "停止后端并打开"
}
+10
Переглянути файл
@@ -57,4 +57,14 @@ describe("the notes' languages", () => {
expect(releaseNotesOf("0.1.40", "zh")).toBe("- older");
expect(recordedNotes("0.1.40")).toEqual({ text: "- older", texts: {} });
});
it("undo restores what an install that did not finish replaced", () => {
recordInstalledUpdate("0.1.40", "- current");
recordInstalledUpdate("0.1.41", "- next")();
expect(releaseNotesOf("0.1.40")).toBe("- current");
expect(releaseNotesOf("0.1.41")).toBeNull();
_resetReleaseNotesForTests();
recordInstalledUpdate("0.1.41", "- next")();
expect(releaseNotesOf("0.1.41")).toBeNull();
});
});
+16 -2
Переглянути файл
@@ -38,22 +38,36 @@ function read(): Stored | null {
}
}
/** Called once an update installed, with the notes its manifest carried. */
/**
* Called before an update installs, with the notes its manifest carried: on
* Windows the installer ends the app inside the install, so nothing after it runs.
* Returns an undo that restores what was stored, for an install that fails or is cancelled.
*/
export function recordInstalledUpdate(
version: string,
notes: string | null,
translations: Record<string, string> | null = null,
): void {
): () => void {
const text = notes?.trim();
const texts = Object.fromEntries(
Object.entries(translations ?? {}).filter(([lang, t]) => lang && lang !== DEFAULT_LOCALE && t.trim()),
);
let previous: string | null = null;
try {
previous = globalThis.localStorage?.getItem(KEY) ?? null;
if (text) globalThis.localStorage?.setItem(KEY, JSON.stringify({ version, text, texts }));
else globalThis.localStorage?.removeItem(KEY);
} catch {
/* storage unavailable: the page reads the manifest instead */
}
return () => {
try {
if (previous === null) globalThis.localStorage?.removeItem(KEY);
else globalThis.localStorage?.setItem(KEY, previous);
} catch {
/* storage unavailable */
}
};
}
/** Notes recorded when this version was installed, for the page to pick the UI's language from. */
+23 -2
Переглянути файл
@@ -237,6 +237,27 @@ async function attachRemote(r: RemoteProject, path: string): Promise<void> {
let connectAttempt = 0;
let backendBusyPrompt: ((target: RemoteTarget) => Promise<boolean>) | null = null;
/** Asks whether to stop another build's backend that still holds the project (#6119). */
export function provideBackendBusyPrompt(value: (target: RemoteTarget) => Promise<boolean>): () => void {
backendBusyPrompt = value;
return () => {
if (backendBusyPrompt === value) backendBusyPrompt = null;
};
}
/** Connects; when another build's backend still holds the project, stops it once the user agrees. */
async function connectOrReplace(target: RemoteTarget, path: string, onProgress: Channel<RemoteProgress>) {
try {
return await call(commands.remoteConnect(target, path, false, onProgress));
} catch (e) {
const busy = e instanceof IpcError && e.data?.type === "remoteBackendBusy";
if (!busy || !backendBusyPrompt || !(await backendBusyPrompt(target))) throw e;
return await call(commands.remoteConnect(target, path, true, onProgress));
}
}
/**
* Opens `path` of `target` (an SSH host or a WSL distribution) in this window. A dev container's
* project folder is the one in the container: `path` is then only a label.
@@ -256,7 +277,7 @@ export async function connectRemote(target: RemoteTarget, path: string) {
location,
});
try {
const r = await call(commands.remoteConnect(target, path, onProgress));
const r = await connectOrReplace(target, path, onProgress);
// Another connect replaced this one, or the user cancelled. Disconnecting here
// would drop the connection that replacement published. Cancel already disconnects.
if (!current()) {
@@ -280,7 +301,7 @@ export async function reconnectRemote(): Promise<void> {
if (!session) return;
useRemote.setState({ reconnecting: true });
try {
const r = await call(commands.remoteConnect(session.target, session.root, new Channel<RemoteProgress>()));
const r = await connectOrReplace(session.target, session.root, new Channel<RemoteProgress>());
useProject.setState({ project: null });
await attachRemote(r, session.root);
} finally {
Loaded 100 of 101 files, more files were not shown because too many files have changed in this diff. Show more