дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-29 22:02:59 +02:00
Порівняти коміти
50
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
7fd1ae9aa7 | ||
|
|
a4ad387085 | ||
|
|
f8a148c06d | ||
|
|
aa1a027162 | ||
|
|
b30716e22c | ||
|
|
7fb21003f3 | ||
|
|
ad8d32d9c7 | ||
|
|
08aef06844 | ||
|
|
3d5ec8a147 | ||
|
|
0f14314156 | ||
|
|
2413cc4b43 | ||
|
|
30291971e1 | ||
|
|
9f3d75976f | ||
|
|
72d9aad715 | ||
|
|
7264e7d66d | ||
|
|
10379a54f7 | ||
|
|
6564b9e6cb | ||
|
|
d437cd46f5 | ||
|
|
925d474274 | ||
|
|
89463afc18 | ||
|
|
c884aa4cc6 | ||
|
|
09108e02e3 | ||
|
|
2b6ca90457 | ||
|
|
3c3681ef2b | ||
|
|
b0d7bfef24 | ||
|
|
527add030a | ||
|
|
81c2fc9ace | ||
|
|
ef1b159544 | ||
|
|
7bfba926c2 | ||
|
|
1042f5fa56 | ||
|
|
fdad01034c | ||
|
|
6dddfde3bc | ||
|
|
0324bc368d | ||
|
|
96c6e65aad | ||
|
|
6eebd895ea | ||
|
|
cfad729dbd | ||
|
|
bd905c6689 | ||
|
|
7138becb3a | ||
|
|
6f7d2ce34d | ||
|
|
719961e34e | ||
|
|
11c432fc23 | ||
|
|
0b8698e47c | ||
|
|
f595a7abf0 | ||
|
|
fe7fa7d505 | ||
|
|
e998e2ca8e | ||
|
|
18424b322f | ||
|
|
daee26e680 | ||
|
|
5886e055b4 | ||
|
|
8d4b360933 | ||
|
|
f6704b53f6 |
No files matched your search
@@ -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).
|
||||
|
||||
@@ -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
|
||||
@@ -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
|
||||
Створено
@@ -6745,6 +6745,7 @@ dependencies = [
|
||||
"objc2-web-kit 0.3.2",
|
||||
"parking_lot",
|
||||
"percent-encoding",
|
||||
"reqwest",
|
||||
"security-framework",
|
||||
"serde",
|
||||
"serde_json",
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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 个文件),
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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>
|
||||
@@ -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>
|
||||
@@ -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>
|
||||
@@ -58,9 +58,10 @@ pub fn set_text(text: &str, owner: usize) -> std::io::Result<()> {
|
||||
imp::set_text(text, owner)
|
||||
}
|
||||
|
||||
/// The clipboard's plain text, None when it holds none. macOS only (main thread);
|
||||
/// Linux reads it asynchronously through GTK in the app, Windows through the WebView.
|
||||
#[cfg(target_os = "macos")]
|
||||
/// The clipboard's plain text. None when macOS holds none, or when Windows cannot
|
||||
/// open the clipboard; empty when Windows holds none. Call on the main thread on
|
||||
/// macOS; Linux reads it asynchronously through GTK in the app.
|
||||
#[cfg(any(windows, target_os = "macos"))]
|
||||
pub fn text() -> Option<String> {
|
||||
imp::text()
|
||||
}
|
||||
@@ -255,6 +256,15 @@ pub fn decode(bytes: &[u8]) -> Vec<PathBuf> {
|
||||
out
|
||||
}
|
||||
|
||||
/// A `CF_UNICODETEXT` block as a string: UTF-16LE up to the first NUL. The block
|
||||
/// 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 (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)
|
||||
}
|
||||
|
||||
/// `BI_RGB` and `BI_BITFIELDS`: uncompressed pixels, the forms screenshots take.
|
||||
#[cfg(any(windows, test))]
|
||||
const BI_RGB: u32 = 0;
|
||||
@@ -310,7 +320,7 @@ fn dib_to_png(dib: &[u8]) -> Option<Vec<u8>> {
|
||||
|
||||
#[cfg(windows)]
|
||||
mod imp {
|
||||
use super::{HEADER, decode, dib_to_png, encode, names_text};
|
||||
use super::{HEADER, decode, dib_to_png, encode, names_text, unicode_text};
|
||||
use std::ffi::c_void;
|
||||
use std::path::PathBuf;
|
||||
use std::ptr;
|
||||
@@ -394,6 +404,19 @@ mod imp {
|
||||
image
|
||||
}
|
||||
|
||||
pub fn text() -> Option<String> {
|
||||
// Empty rather than None: a None falls back to the WebView, which prompts the user.
|
||||
if unsafe { IsClipboardFormatAvailable(CF_UNICODETEXT) } == 0 {
|
||||
return Some(String::new());
|
||||
}
|
||||
if !open() {
|
||||
return None;
|
||||
}
|
||||
let text = read_block(CF_UNICODETEXT).map(|bytes| unicode_text(&bytes));
|
||||
unsafe { CloseClipboard() };
|
||||
text
|
||||
}
|
||||
|
||||
#[link(name = "kernel32")]
|
||||
unsafe extern "system" {
|
||||
fn GlobalAlloc(flags: u32, bytes: usize) -> Handle;
|
||||
@@ -890,6 +913,16 @@ mod tests {
|
||||
assert!(set_png(&header, 0).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unicode_text_stops_at_the_nul() {
|
||||
let mut bytes: Vec<u8> = "héllo\r\n世界".encode_utf16().chain([0, 0x41]).flat_map(u16::to_le_bytes).collect();
|
||||
assert_eq!(unicode_text(&bytes), "héllo\r\n世界");
|
||||
// No terminator, and a stray odd byte, still read the whole text.
|
||||
bytes.truncate(bytes.len() - 4);
|
||||
bytes.push(7);
|
||||
assert_eq!(unicode_text(&bytes), "héllo\r\n世界");
|
||||
}
|
||||
|
||||
fn paths(list: &[&str]) -> Vec<PathBuf> {
|
||||
list.iter().map(PathBuf::from).collect()
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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);
|
||||
@@ -1640,16 +1696,39 @@ impl DebugManager {
|
||||
}
|
||||
|
||||
pub async fn stack_trace(&self, s: DebugSessionId, thread_id: i64) -> IdeResult<Vec<StackFrame>> {
|
||||
const MAX_FRAMES: u64 = 400;
|
||||
let session = self.session(s)?;
|
||||
session.check_thread(thread_id)?;
|
||||
let body = session
|
||||
.conn
|
||||
.request_timeout(
|
||||
let request = |start: u64, levels: u64| {
|
||||
session.conn.request_timeout(
|
||||
"stackTrace",
|
||||
json!({ "threadId": thread_id, "startFrame": 0, "levels": 400 }),
|
||||
json!({ "threadId": thread_id, "startFrame": start, "levels": levels }),
|
||||
REQUEST_TIMEOUT,
|
||||
)
|
||||
.await?;
|
||||
};
|
||||
let frames_of = |mut body: Value| match body.get_mut("stackFrames").map(Value::take) {
|
||||
Some(Value::Array(frames)) => frames,
|
||||
_ => Vec::new(),
|
||||
};
|
||||
let raw = match request(0, MAX_FRAMES).await {
|
||||
Ok(body) => frames_of(body),
|
||||
// java-debug fails the whole request when one frame's source lookup throws (on Windows,
|
||||
// a CGLIB proxy's `<generated>` source against `sourcePaths`): the frames come one at a
|
||||
// time instead, without the ones it cannot describe.
|
||||
// ponytail: one request per frame; page around the failing ones if deep stacks get slow.
|
||||
Err(first @ DapError::Failed { .. }) => {
|
||||
let Ok(top) = request(0, 1).await else { return Err(first.into()) };
|
||||
let total = top.get("totalFrames").and_then(Value::as_u64).unwrap_or(MAX_FRAMES).min(MAX_FRAMES);
|
||||
let mut raw = frames_of(top);
|
||||
for start in 1..total {
|
||||
if let Ok(body) = request(start, 1).await {
|
||||
raw.extend(frames_of(body));
|
||||
}
|
||||
}
|
||||
raw
|
||||
}
|
||||
Err(e) => return Err(e.into()),
|
||||
};
|
||||
let kotlin_lsp = session.kotlin_lsp_quirks().is_some();
|
||||
let frame = |f: &Value| {
|
||||
let mut frame = frame_from(f);
|
||||
@@ -1661,7 +1740,7 @@ impl DebugManager {
|
||||
}
|
||||
frame
|
||||
};
|
||||
Ok(body.get("stackFrames").and_then(Value::as_array).map(|f| f.iter().map(frame).collect()).unwrap_or_default())
|
||||
Ok(raw.iter().map(frame).collect())
|
||||
}
|
||||
|
||||
pub async fn scopes(&self, s: DebugSessionId, frame_id: i64) -> IdeResult<Vec<Scope>> {
|
||||
@@ -1853,7 +1932,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 +1947,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 +1969,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 +1984,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 +1996,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 +2212,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 +2235,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 {
|
||||
|
||||
@@ -1017,6 +1017,13 @@ fn on_reverse_request(mgr: &Arc<DebugManager>, s: &Arc<Session>, seq: i64, comma
|
||||
}
|
||||
}
|
||||
|
||||
/// `text` as a terminal sends it when typed: Enter is CR. A Unix terminal turns CR into the
|
||||
/// newline a line read waits for, but Windows' ConPTY reads LF as Ctrl+J, so a program blocked
|
||||
/// in `input()` never sees its line end (#6041).
|
||||
fn as_typed(text: &str) -> std::borrow::Cow<'_, str> {
|
||||
if text.contains('\n') { text.replace("\r\n", "\r").replace('\n', "\r").into() } else { text.into() }
|
||||
}
|
||||
|
||||
/// A `runInTerminal` program and the pseudo-terminal it runs in.
|
||||
pub(crate) struct ProgramTerminal {
|
||||
writer: Arc<ide_core::input::InputWriter>,
|
||||
@@ -1030,7 +1037,7 @@ pub(crate) struct ProgramTerminal {
|
||||
|
||||
impl ProgramTerminal {
|
||||
pub(crate) fn write(&mut self, text: &str) -> std::io::Result<()> {
|
||||
self.writer.write(text.as_bytes())
|
||||
self.writer.write(as_typed(text).as_bytes())
|
||||
}
|
||||
|
||||
/// The program's process id while it runs.
|
||||
@@ -1386,6 +1393,13 @@ fn parse_jdwp_port(line: &str) -> Option<u16> {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn typed_input_ends_lines_with_enter() {
|
||||
assert_eq!(super::as_typed("42\n"), "42\r");
|
||||
assert_eq!(super::as_typed("a\r\nb\n"), "a\rb\r");
|
||||
assert_eq!(super::as_typed("no newline"), "no newline");
|
||||
}
|
||||
|
||||
use super::{Suspension, kotlin_jvm_args, parse_jdwp_port};
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -126,6 +126,8 @@ struct Script {
|
||||
child_request: Option<Value>,
|
||||
ignore_configuration_done: bool,
|
||||
source_path: Option<String>,
|
||||
/// Fail each `stackTrace` request whose frames include this one (java-debug, one frame's source lookup throwing).
|
||||
failing_frame: Option<u64>,
|
||||
/// Report this process id in the adapter's `process` event (the program being debugged).
|
||||
debuggee_pid: Option<u32>,
|
||||
/// java-debug's spelling of the same event.
|
||||
@@ -206,6 +208,7 @@ impl Default for Script {
|
||||
child_request: None,
|
||||
ignore_configuration_done: false,
|
||||
source_path: None,
|
||||
failing_frame: None,
|
||||
debuggee_pid: None,
|
||||
java_process_id: false,
|
||||
output_after_terminate: false,
|
||||
@@ -520,6 +523,20 @@ async fn fake_adapter<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(stream
|
||||
ok!(msg, json!({"threads": [{"id": 1, "name": "MainThread"}]}));
|
||||
}
|
||||
}
|
||||
"stackTrace" if let Some(bad) = script.failing_frame => {
|
||||
let start = msg["arguments"]["startFrame"].as_u64().unwrap();
|
||||
let end = (start + msg["arguments"]["levels"].as_u64().unwrap()).min(3);
|
||||
if (start..end).contains(&bad) {
|
||||
send!(
|
||||
json!({"type": "response", "request_seq": msg["seq"], "command": "stackTrace", "success": false, "message": "Illegal char <<> at index 21: C:\\p\\com\\x\\<generated>"})
|
||||
);
|
||||
} else {
|
||||
let frames: Vec<Value> = (start..end)
|
||||
.map(|i| json!({"id": 10 + i, "name": format!("f{i}"), "line": 1, "column": 1}))
|
||||
.collect();
|
||||
ok!(msg, json!({"stackFrames": frames, "totalFrames": 3}));
|
||||
}
|
||||
}
|
||||
"stackTrace" => ok!(
|
||||
msg,
|
||||
json!({"stackFrames": [
|
||||
@@ -899,7 +916,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 +998,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 +1022,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 +1054,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 +1906,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 +1915,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 +1931,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 +1978,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 +2018,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 +2032,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 +2266,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 +2293,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 +2327,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!() };
|
||||
@@ -2292,6 +2349,21 @@ async fn kotlin_official_release_ten_no_delay_runs() {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn stack_trace_leaves_out_a_frame_the_adapter_cannot_describe() {
|
||||
let h = harness(Script { failing_frame: Some(1), ..Script::default() });
|
||||
let id = h.start(config()).await.unwrap();
|
||||
let frames = h.manager.stack_trace(id, 1).await.unwrap();
|
||||
assert_eq!(frames.iter().map(|f| f.name.as_str()).collect::<Vec<_>>(), ["f0", "f2"]);
|
||||
h.manager.stop(id).await.unwrap();
|
||||
|
||||
let h = harness(Script { failing_frame: Some(0), ..Script::default() });
|
||||
let id = h.start(config()).await.unwrap();
|
||||
let error = h.manager.stack_trace(id, 1).await.unwrap_err();
|
||||
assert!(error.message.contains("<generated>"), "{error:?}");
|
||||
h.manager.stop(id).await.unwrap();
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[tokio::test]
|
||||
async fn netcoredbg_windows_source_paths_round_trip() {
|
||||
@@ -2299,7 +2371,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 +2395,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 +3490,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"];
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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 =
|
||||
|
||||
@@ -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?;
|
||||
|
||||
@@ -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 }],
|
||||
)
|
||||
|
||||
@@ -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 })
|
||||
}
|
||||
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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() {
|
||||
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
@@ -283,6 +283,47 @@ fn minimal_edits(text: &str, edits: Vec<TextEdit>) -> Vec<TextEdit> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The edits on the lines of `range`. Some servers (Intelephense, #6055) answer a range request
|
||||
/// with edits across the whole file; Reformat Code with a selection changes only the selected
|
||||
/// lines. An edit that reaches past them and keeps its line count is split into one per line.
|
||||
fn within_lines(text: &str, edits: Vec<TextEdit>, range: Range) -> Vec<TextEdit> {
|
||||
let from = Pos::new(range.start.line, 0);
|
||||
// A selection ending at a line start leaves that line out.
|
||||
let to = if range.end.col == 0 && range.end.line > range.start.line {
|
||||
range.end
|
||||
} else {
|
||||
Pos::new(range.end.line + 1, 0)
|
||||
};
|
||||
let doc = ide_text::Document::new(text);
|
||||
edits
|
||||
.into_iter()
|
||||
.flat_map(|e| if e.range.start >= from && e.range.end <= to { vec![e] } else { per_line(&doc, e) })
|
||||
.filter(|e| e.range.start >= from && e.range.end <= to)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// `edit` as one edit per line when it replaces as many lines as it inserts, else nothing.
|
||||
fn per_line(doc: &ide_text::Document, edit: TextEdit) -> Vec<TextEdit> {
|
||||
let Range { start, end } = edit.range;
|
||||
let lines: Vec<&str> = edit.new_text.split('\n').collect();
|
||||
if lines.len() as u32 != end.line - start.line + 1 {
|
||||
return Vec::new();
|
||||
}
|
||||
let width = |line: u32| doc.line(line).map_or(0, |l| l.encode_utf16().count() as u32);
|
||||
lines
|
||||
.into_iter()
|
||||
.zip(start.line..=end.line)
|
||||
.map(|(new_text, line)| TextEdit {
|
||||
range: Range::new(
|
||||
Pos::new(line, if line == start.line { start.col } else { 0 }),
|
||||
Pos::new(line, if line == end.line { end.col } else { width(line) }),
|
||||
),
|
||||
new_text: new_text.to_owned(),
|
||||
})
|
||||
.filter(|e| doc.slice(doc.pos_to_offset(e.range.start), doc.pos_to_offset(e.range.end)) != e.new_text)
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub async fn format(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
@@ -514,9 +555,15 @@ async fn provider_edits(
|
||||
None => project.lsp.format_text(&snap.path, &snap.language, &snap.text, options).await?,
|
||||
};
|
||||
let text = snap.text;
|
||||
return tokio::task::spawn_blocking(move || Some(minimal_edits(&text, edits)))
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()));
|
||||
return tokio::task::spawn_blocking(move || {
|
||||
let edits = minimal_edits(&text, edits);
|
||||
Some(match range {
|
||||
Some(range) => within_lines(&text, edits, range),
|
||||
None => edits,
|
||||
})
|
||||
})
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()));
|
||||
};
|
||||
let tool_settings = settings.languages.formatter(selected);
|
||||
// Black takes over from the language server in its projects, so Format on save runs it too.
|
||||
@@ -1050,6 +1097,26 @@ mod tests {
|
||||
|
||||
const ALIGN: PhpAlignment = PhpAlignment { key_value_pairs: true, assignments: true };
|
||||
|
||||
#[test]
|
||||
fn range_formatting_changes_only_the_selected_lines() {
|
||||
// Intelephense answers a range request for lines 2-3 with edits across the file (#6055).
|
||||
let text = "<?php\nf(\"a\");\n$x = 1;\n$y = 2;\nf(\"b\");\n";
|
||||
let formatted = "<?php\nf('a');\n$x = 1;\n$y = 2;\nf('b');\n";
|
||||
let whole = vec![TextEdit { range: Range::new(Pos::new(0, 0), Pos::new(5, 0)), new_text: formatted.into() }];
|
||||
let edits = minimal_edits(text, whole);
|
||||
let selected = Range::new(Pos::new(2, 0), Pos::new(3, 8));
|
||||
assert_eq!(
|
||||
after(text, &within_lines(text, edits.clone(), selected)),
|
||||
"<?php\nf(\"a\");\n$x = 1;\n$y = 2;\nf(\"b\");\n"
|
||||
);
|
||||
// Selected up to the start of line 4: line 4 stays as it is.
|
||||
let to_line_start = Range::new(Pos::new(2, 3), Pos::new(3, 0));
|
||||
assert_eq!(
|
||||
after(text, &within_lines(text, edits, to_line_start)),
|
||||
"<?php\nf(\"a\");\n$x = 1;\n$y = 2;\nf(\"b\");\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_whole_file_edit_becomes_one_edit_per_changed_region() {
|
||||
let text = "a\n b\nc\nd\n e\n";
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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)),
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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() {
|
||||
|
||||
@@ -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"));
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -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() {
|
||||
|
||||
@@ -48,9 +48,13 @@ const QUERY_TIMEOUT: Duration = Duration::from_secs(10);
|
||||
/// `cargo metadata` / `go list` load the whole dependency graph.
|
||||
const GRAPH_TIMEOUT: Duration = Duration::from_secs(60);
|
||||
|
||||
/// Prints the interpreter's library folders as JSON: `[stdlib, platstdlib, purelib, platlib]`.
|
||||
const PYTHON_PATHS: &str = "import json,sysconfig;p=sysconfig.get_paths();\
|
||||
print(json.dumps([p.get(k) for k in ('stdlib','platstdlib','purelib','platlib')]))";
|
||||
/// Prints the interpreter's library folders as two JSON lines: `[stdlib, platstdlib, purelib,
|
||||
/// platlib]`, then `sys.path`. On Debian and Ubuntu the system interpreter's `purelib` is the
|
||||
/// usually empty `/usr/local/lib/python3.X/dist-packages`; the packages apt installs, and the
|
||||
/// user's site-packages, are only on `sys.path` (#6042).
|
||||
const PYTHON_PATHS: &str = "import json,sys,sysconfig;p=sysconfig.get_paths();\
|
||||
print(json.dumps([p.get(k) for k in ('stdlib','platstdlib','purelib','platlib')]));\
|
||||
print(json.dumps([x for x in sys.path if isinstance(x,str) and x]))";
|
||||
|
||||
const JAVA_MANIFESTS: &[&str] =
|
||||
&["pom.xml", "build.gradle", "build.gradle.kts", "settings.gradle", "settings.gradle.kts"];
|
||||
@@ -397,7 +401,7 @@ fn python_groups(root: &Path, project: &Path, s: &Settings, cancel: &Cancellatio
|
||||
let user = outside_folders(crate::apply::interpreter_user_paths(&python, s), &folders);
|
||||
let key = std::iter::once(&python).chain(&user).map(|p| p.display().to_string()).collect::<Vec<_>>().join("\n");
|
||||
cached_cancellable(root, "python", key, &files, cancel, || {
|
||||
let mut group = python_libraries(&python, Some(root));
|
||||
let mut group = python_libraries(&python, Some(root), &folders);
|
||||
if let Some(group) = &mut group {
|
||||
group.roots.extend(library_roots(user));
|
||||
}
|
||||
@@ -411,13 +415,24 @@ fn outside_folders(paths: Vec<PathBuf>, folders: &[PathBuf]) -> Vec<PathBuf> {
|
||||
paths.into_iter().filter(|p| !folders.iter().any(|f| p.starts_with(f) || f.starts_with(p))).collect()
|
||||
}
|
||||
|
||||
/// Standard library and site-packages folders of a Python interpreter.
|
||||
pub fn python_libraries(python: &Path, root: Option<&Path>) -> Option<LibraryGroup> {
|
||||
// In a neutral directory: the working directory comes first on `sys.path` for `-c`.
|
||||
/// Standard library and site-packages folders of a Python interpreter, then the other folders on
|
||||
/// its `sys.path` (other site dirs, `lib-dynload`, `.pth` entries) outside the project's `folders`.
|
||||
pub fn python_libraries(python: &Path, root: Option<&Path>, folders: &[PathBuf]) -> Option<LibraryGroup> {
|
||||
// In a neutral directory and without the IDE's own `PYTHONPATH`: the working directory comes
|
||||
// first on `sys.path` for `-c`, and neither belongs to the interpreter.
|
||||
let dir = crate::python::neutral_dir();
|
||||
let out = query_in(python, &["-c", PYTHON_PATHS], dir.as_ref().map(|d| d.path()), &[], QUERY_TIMEOUT)?;
|
||||
let out =
|
||||
query_in(python, &["-c", PYTHON_PATHS], dir.as_ref().map(|d| d.path()), &[("PYTHONPATH", "")], QUERY_TIMEOUT)?;
|
||||
let name = crate::discover::python_sdk(python, "system", root).map(|s| s.name).unwrap_or_else(|| "Python".into());
|
||||
group(name, "python", library_roots(parse_python_paths(&out)))
|
||||
group(name, "python", library_roots(python_library_paths(&out, folders)))
|
||||
}
|
||||
|
||||
/// The paths [`PYTHON_PATHS`] printed: the `sysconfig` folders, then the `sys.path` ones outside
|
||||
/// `folders` (an editable install's `.pth` puts the project's own sources there).
|
||||
pub(crate) fn python_library_paths(out: &str, folders: &[PathBuf]) -> Vec<PathBuf> {
|
||||
let mut lists = out.lines().filter(|l| l.trim_start().starts_with('[')).rev().take(2).map(parse_python_paths);
|
||||
let (sys_path, sysconfig) = (lists.next().unwrap_or_default(), lists.next().unwrap_or_default());
|
||||
sysconfig.into_iter().chain(outside_folders(sys_path, folders)).collect()
|
||||
}
|
||||
|
||||
/// `sys.path` of `python` started on its own; `None` when it cannot run or was cancelled.
|
||||
|
||||
@@ -2126,6 +2126,31 @@ fn python_library_paths_are_parsed_and_deduplicated() {
|
||||
assert!(crate::libraries::parse_python_paths("not json").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn python_libraries_include_the_other_folders_on_sys_path() {
|
||||
// Ubuntu's /usr/bin/python3: `purelib` is the empty /usr/local dist-packages; apt's packages
|
||||
// and the user's site-packages are only on `sys.path` (#6042).
|
||||
let project = std::path::PathBuf::from("/home/u/app");
|
||||
let sysconfig =
|
||||
r#"["/usr/lib/python3.12", "/usr/lib/python3.12", "/usr/local/lib/python3.12/dist-packages", null]"#;
|
||||
let sys_path = r#"["/usr/lib/python312.zip", "/usr/lib/python3.12", "/usr/lib/python3.12/lib-dynload", "/home/u/.local/lib/python3.12/site-packages", "/home/u/app/src", "/usr/lib/python3/dist-packages"]"#;
|
||||
let paths = crate::libraries::python_library_paths(&format!("{sysconfig}\n{sys_path}\n"), &[project]);
|
||||
let paths: Vec<_> = paths.iter().map(|p| p.to_string_lossy().into_owned()).collect();
|
||||
assert_eq!(
|
||||
paths,
|
||||
[
|
||||
"/usr/lib/python3.12",
|
||||
"/usr/lib/python3.12",
|
||||
"/usr/local/lib/python3.12/dist-packages",
|
||||
"/usr/lib/python312.zip",
|
||||
"/usr/lib/python3.12",
|
||||
"/usr/lib/python3.12/lib-dynload",
|
||||
"/home/u/.local/lib/python3.12/site-packages",
|
||||
"/usr/lib/python3/dist-packages",
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_libraries_without_an_interpreter() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -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, ¤t), 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
|
||||
|
||||
@@ -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>,
|
||||
}
|
||||
|
||||
|
||||
@@ -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));
|
||||
|
||||
@@ -919,6 +919,20 @@ impl Documents {
|
||||
/// on disk after this buffer was edited, which only an explicit save may overwrite.
|
||||
pub fn autosave(&self, doc: DocId) -> IdeResult<bool> {
|
||||
self.with_doc(doc, |st| {
|
||||
// The watcher event for an external write may not have arrived yet: check the stamp now.
|
||||
if st.dirty
|
||||
&& !st.disk_conflict
|
||||
&& st.uri.is_none()
|
||||
&& let Ok(meta) = std::fs::metadata(&st.path)
|
||||
&& (ide_vfs::mtime_ms(&meta) != st.disk_mtime || meta.len() != st.disk_len)
|
||||
{
|
||||
st.disk_mtime = ide_vfs::mtime_ms(&meta);
|
||||
st.disk_len = meta.len();
|
||||
st.disk_conflict = true;
|
||||
// The text read before no longer matches the file: undoing back to it is not clean.
|
||||
st.clean_text = None;
|
||||
self.sink.emit(IdeEvent::DocDiskConflict { doc, path: st.path.to_string_lossy().into_owned() });
|
||||
}
|
||||
if st.dirty && st.disk_conflict {
|
||||
return Ok(false);
|
||||
}
|
||||
|
||||
@@ -330,6 +330,26 @@ fn save_to_a_path_replaced_by_a_directory_preserves_the_dirty_buffer() {
|
||||
assert_eq!(fs::read_dir(&f.root).unwrap().count(), 1, "save left artifacts beside the replacement directory");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn autosave_checks_the_disk_before_the_watcher_reports_a_change() {
|
||||
let f = fixture();
|
||||
let path = f.root.join("notes.txt");
|
||||
fs::write(&path, "alpha\nbeta\n").unwrap();
|
||||
let info = f.docs.open(&path).unwrap();
|
||||
f.docs.edit(info.id, 0, change(0, 5, "edited")).unwrap();
|
||||
std::thread::sleep(std::time::Duration::from_millis(20));
|
||||
// An external write (git checkout, another editor) whose watcher event has not arrived yet.
|
||||
fs::write(&path, "alpha\nbeta external\n").unwrap();
|
||||
|
||||
assert!(!f.docs.autosave(info.id).unwrap());
|
||||
assert_eq!(fs::read_to_string(&path).unwrap(), "alpha\nbeta external\n");
|
||||
assert!(f.docs.snapshot(info.id).unwrap().dirty);
|
||||
assert!(
|
||||
f.events.lock().iter().any(|e| matches!(e, IdeEvent::DocDiskConflict { doc, .. } if *doc == info.id)),
|
||||
"the refused autosave must surface the conflict"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn autosave_leaves_a_file_changed_on_disk_after_an_edit() {
|
||||
let f = fixture();
|
||||
@@ -1197,7 +1217,7 @@ fn untitled_buffers_are_editable_and_saved_to_a_chosen_path() {
|
||||
assert_eq!(f.docs.by_path(&target), Some(info.id));
|
||||
assert_eq!(f.docs.by_path(Path::new("untitled:Untitled-1")), None);
|
||||
f.docs.edit(info.id, version, change(0, 0, "// hi\n")).unwrap();
|
||||
f.docs.save(info.id).unwrap();
|
||||
assert!(f.docs.autosave(info.id).unwrap(), "Save As records the disk state autosave checks");
|
||||
assert!(!f.docs.is_dirty(info.id).unwrap());
|
||||
assert_eq!(fs::read_to_string(&target).unwrap(), "// hi\nfn main() {}\n");
|
||||
|
||||
|
||||
@@ -75,7 +75,7 @@ Going to files, classes and symbols by name is covered in [Search and navigation
|
||||
| **Highlight Usages in File** | `⇧⌘F7` | `Ctrl+Shift+F7` |
|
||||
| **Next Highlighted Usage** / **Previous** | `⌃⌥↓` / `⌃⌥↑` | `Ctrl+Alt+Down` / `Ctrl+Alt+Up` |
|
||||
|
||||
**Find Usages** lists the results in the **Find Usages** tool window, grouped by file, with a preview. **Show Usages** shows them in a popup at the caret. The occurrences of the symbol under the caret are highlighted in the editor as you move.
|
||||
**Find Usages** lists the results in the **Find Usages** tool window, grouped by file, with a preview. **Show Usages** shows them in a popup at the caret. **Recent Find Usages** (from Find Action) lists the last ten searches, including those whose tab was closed, and runs the chosen one again. The occurrences of the symbol under the caret are highlighted in the editor as you move.
|
||||
|
||||
Above declarations, a **N usages** hint and the last author of the code (from Git blame) are shown, with the date of that last change. Turn them off under **Code Vision** in **Settings › Editor › Inlay Hints**.
|
||||
|
||||
|
||||
@@ -24,6 +24,8 @@ The editor follows IntelliJ IDEA's behaviour and default keymap. Shortcuts below
|
||||
- **Add Selection for Next Occurrence** selects the word at the caret first, then adds the next match on every press. When nothing more is found, a hint appears; press again to continue from the top of the file.
|
||||
- Drag with `⌥` / `Alt` held (or with the middle mouse button on macOS and Windows) to make a rectangular selection without switching modes.
|
||||
- **Extend Selection** grows the selection to the enclosing word, expression, statement and block, using the syntax tree.
|
||||
- **Swap Selection Boundaries** moves the caret of each selection to its other end and keeps the text selected, so `⇧` / `Shift` with the arrow keys then extends or shrink it from that side. It has no default shortcut.
|
||||
- **Select Line at Caret** selects the whole line at each caret together with its line break; a selection grows to the whole lines it touches. It has no default shortcut.
|
||||
|
||||
## Editing lines and code
|
||||
|
||||
@@ -51,6 +53,8 @@ The editor follows IntelliJ IDEA's behaviour and default keymap. Shortcuts below
|
||||
|
||||
**Move Caret to Page Top** / **Bottom** put the caret on the first / last line the editor shows in full, in the same column, without scrolling; with `⇧` / `Shift` added they select up to it.
|
||||
|
||||
**Move Caret Forward a Paragraph** / **Backward a Paragraph** jump each caret over a run of non-blank lines to the blank line after or before it (a line of only spaces or tabs counts as blank), or to the end or start of the file; their **with Selection** variants select up to there. They have no default shortcut.
|
||||
|
||||
**Edit › Sort Lines** and **Edit › Reverse Lines** reorder the selected lines (the whole file without a selection); they have no default shortcut. Sort Lines orders by character code, so uppercase letters come before lowercase ones.
|
||||
|
||||
**Cut up to Line End** cuts from each caret to the end of its line, together with the line break when only whitespace is left (or the caret is already at the line end), so pressing it again on the same caret cuts the next line too; those repeated cuts collect into one clipboard entry. **Delete to Line Start** and **Delete to Line End** delete the same way without copying (to the line start, or the line break before the caret at the line start), or delete the selection. They have no default shortcut except in the Eclipse keymaps (`⇧⌘⌦` / `Ctrl+Shift+Delete` for Delete to Line End).
|
||||
@@ -146,8 +150,10 @@ With tabs placed left or right, the tab column is as wide as its longest name, u
|
||||
| **Scroll to Center** | `⌃L` | `Ctrl+M` |
|
||||
| **Scroll Up** | — | `Ctrl+Up` |
|
||||
| **Scroll Down** | — | `Ctrl+Down` |
|
||||
| **Scroll to Top** | — | — |
|
||||
| **Scroll to Bottom** | — | — |
|
||||
|
||||
**Scroll Up** and **Scroll Down** move the view by one line and leave the caret where it is, even when it scrolls out of sight.
|
||||
**Scroll Up** and **Scroll Down** move the view by one line and leave the caret where it is, even when it scrolls out of sight. **Scroll to Top** and **Scroll to Bottom** show the start and the end of the file; the caret stays where it is too. They have no default shortcut: run them from Find Action or assign one in **Settings › Keymap**.
|
||||
|
||||
- **View › Active Editor › Soft-Wrap** wraps long lines in the current editor. To wrap some file types by default, use **Settings › Editor › General**, section **Soft Wraps**.
|
||||
- **View › Reset Font Size** undoes font zoom in the active editor or focused surface (**View › Reset Font Size in All Editors** resets every open editor). Changing the font size with `⌘` / `Ctrl` + mouse wheel (scoped to **Active editor** by default, or **All editors**) can be turned on in **Settings › Editor › General**, section **Mouse Control**.
|
||||
|
||||
@@ -160,7 +160,7 @@ A **Compound** configuration starts several configurations at once. Run it to st
|
||||
|
||||
Each launch opens a tab in the **Run** tool window (bottom). The toolbar has **Rerun**, **Debug**, **Rerun Failed Tests** (for test runs), **Update Application**, **Find…**, **Scroll to End**, **Soft-Wrap**, **Clear All** and **Edit Configurations…**.
|
||||
|
||||
- File paths and stack trace frames in the output are links.
|
||||
- File paths and stack trace frames in the output are links. **Up the Stack Trace** / **Down the Stack Trace** in the toolbar (or **Previous / Next Occurrence**, `⌥⌘↑` / `⌥⌘↓`, `Ctrl+Alt+↑` / `Ctrl+Alt+↓` on Windows and Linux) select the previous / next one and open it; links in collapsed folds are skipped. In a test run these keys go through the failed tests instead.
|
||||
- Repeated lines can be folded; configure the patterns in **Settings › Build, Execution, Deployment › Console**, along with the buffer size and the console encoding. **Fold Lines Like This** in the console's context menu opens that page with the selected text (or the clicked line) added as a pattern.
|
||||
- Log lines can take the colour of their level (`ERROR`, `WARN`, `INFO`, `DEBUG`, `TRACE`); colours the program prints itself are kept. Turn it on and pick the colours in **Settings › Build, Execution, Deployment › Console**.
|
||||
- For test runs the tab shows a test tree next to the output. See [Testing](/en/guide/testing).
|
||||
|
||||
@@ -248,6 +248,7 @@ Turn on **Combine stashes and shelves in one tab** in the Git settings to show b
|
||||
|
||||
- **Annotate with Git Blame** shows author and date per line in the gutter (also from the gutter's context menu). Click an entry to open the commit in the log. **Show inline blame for the current line** in the Git settings shows the author at the end of the caret line; a click on it opens the commit unless **Open the commit when the inline blame is clicked** is off.
|
||||
- **Options › Names** in the gutter's context menu shows authors as **Initials**, **Last Name** (the default), **First Name** or **Full Name** in every annotated editor.
|
||||
- **Annotate Revision** in an annotated line's menu opens the file as it was at that commit, annotated, next to the working copy. A file renamed since then is read under its name at that commit.
|
||||
- **Annotate Previous Revision** in an annotated line's menu opens the file as it was before that commit, annotated, next to the commit's version.
|
||||
- **Annotate at Revision…** picks any revision the file has and shows it annotated next to the working copy.
|
||||
- **Show History** opens the file's history in a tab of the Git tool window.
|
||||
|
||||
@@ -152,7 +152,9 @@ double click and Enter with `event.table_activate()` (API 1.3, absolute 0-based
|
||||
Bodies, fields and events added by later APIs travel as `Other { kind, data }`: an IDE that
|
||||
doesn't know a body says it needs updating, and leaves out a field type it doesn't know.
|
||||
Item right-click menus use `viewItem.context` (see
|
||||
[Commands and actions](/en/plugins/guides/commands#menus)).
|
||||
[Commands and actions](/en/plugins/guides/commands#menus)). A command that menu offers for the selected item,
|
||||
run from its shortcut (or Find Action) while the view has the keyboard focus, gets that
|
||||
item's key as its argument, as from the menu; none when nothing is selected.
|
||||
|
||||
## Custom editors
|
||||
|
||||
|
||||
@@ -75,7 +75,7 @@ description: "代码补全、导航、查找用法、文档、层次结构与文
|
||||
| **高亮文件中的用法** | `⇧⌘F7` | `Ctrl+Shift+F7` |
|
||||
| **下一个高亮的用法** / **上一个** | `⌃⌥↓` / `⌃⌥↑` | `Ctrl+Alt+Down` / `Ctrl+Alt+Up` |
|
||||
|
||||
**查找用法** 把结果按文件分组列在 **查找用法** 工具窗口中,并带预览。**显示用法** 在光标处用弹窗显示。移动光标时,编辑器会自动高亮光标下符号的所有出现位置。
|
||||
**查找用法** 把结果按文件分组列在 **查找用法** 工具窗口中,并带预览。**显示用法** 在光标处用弹窗显示。**最近的查找用法**(通过查找操作执行)列出最近十次搜索,包括标签页已关闭的,选中一项即重新运行。移动光标时,编辑器会自动高亮光标下符号的所有出现位置。
|
||||
|
||||
声明上方会显示用法数量(如 `3 usages`)和这段代码最后的作者(来自 Git blame),并标注最近一次修改的日期。可以在 **设置 › 编辑器 › 嵌入提示** 的 **Code Vision** 一节中关闭。
|
||||
|
||||
|
||||
@@ -24,6 +24,8 @@ description: "多光标与选区、行编辑、剪贴板历史、代码折叠、
|
||||
- **添加下一个匹配项到选区** 第一次按下时选中光标处的单词,之后每按一次加入下一个匹配。找不到更多时会给出提示,再按一次就从文件开头继续找。
|
||||
- 按住 `⌥` / `Alt` 拖动鼠标(macOS 和 Windows 上也可以用鼠标中键拖动)可以直接做矩形选区,不用切换模式。
|
||||
- **扩展选区** 依据语法树逐级扩大到所在的单词、表达式、语句和代码块。
|
||||
- **交换选区边界** 把每个选区的光标移到选区的另一端并保持选中,之后用 `⇧` / `Shift`+方向键即可从这一端扩大或缩小选区。它默认没有快捷键。
|
||||
- **选择光标所在行** 选中每个光标所在的整行及其换行符;有选区时扩大到选区涉及的所有整行。它默认没有快捷键。
|
||||
|
||||
## 编辑行与代码
|
||||
|
||||
@@ -51,6 +53,8 @@ description: "多光标与选区、行编辑、剪贴板历史、代码折叠、
|
||||
|
||||
**将光标移至页面顶部** / **底部** 把光标放到编辑器完整显示的第一行 / 最后一行,保持所在列,不滚动视图;再加上 `⇧` / `Shift` 则选择到该处。
|
||||
|
||||
**将光标移至下一段落** / **上一段落** 让每个光标越过一段连续的非空行,跳到其后或其前的空行(只含空格或制表符的行也算空行),没有空行时跳到文件末尾或开头;对应的 **并选择** 版本选择到该处。它们默认没有快捷键。
|
||||
|
||||
**剪切到行尾** 从每个光标剪切到所在行的行尾;光标后只剩空白(或光标已在行尾)时连同换行符一起剪切,所以在同一光标处再按一次会剪切下一行,这些连续的剪切合并为剪贴板中的一条内容。**删除到行首** 和 **删除到行尾** 以同样方式删除但不复制(删除到行首时,若光标在行首则删除前面的换行符),有选区时删除选区。除 Eclipse 键位映射(删除到行尾为 `⇧⌘⌦` / `Ctrl+Shift+Delete`)外,它们默认没有快捷键。
|
||||
|
||||
**贪婪退格** 一次删除每个光标前的所有空格、制表符和换行符,直到前一个非空白字符;光标前是其他字符或有选区时,它与 `⌫` / `Backspace` 相同。它默认没有快捷键。
|
||||
@@ -146,8 +150,10 @@ description: "多光标与选区、行编辑、剪贴板历史、代码折叠、
|
||||
| **滚动到中央** | `⌃L` | `Ctrl+M` |
|
||||
| **向上滚动** | — | `Ctrl+Up` |
|
||||
| **向下滚动** | — | `Ctrl+Down` |
|
||||
| **滚动到顶部** | — | — |
|
||||
| **滚动到底部** | — | — |
|
||||
|
||||
**向上滚动** 和 **向下滚动** 把视图移动一行,光标保持原位,即使它因此移出可见区域。
|
||||
**向上滚动** 和 **向下滚动** 把视图移动一行,光标保持原位,即使它因此移出可见区域。**滚动到顶部** 和 **滚动到底部** 显示文件的开头和结尾;光标同样保持原位。它们默认没有快捷键:在查找操作中运行,或在 **设置 › 按键映射** 中指定。
|
||||
|
||||
- **视图 › 活动编辑器 › 软换行** 让当前编辑器的长行自动折行。想让某些文件类型默认软换行,在 **设置 › 编辑器 › 常规** 的 **软换行** 一节中设置。
|
||||
- **视图 › 重置字体大小** 撤销当前编辑器或焦点区域的字体缩放(**视图 › 重置所有编辑器中的字体大小** 会重置所有打开的编辑器)。用 `⌘` / `Ctrl` + 鼠标滚轮调整字号的功能默认关闭,可在 **设置 › 编辑器 › 常规** 的 **鼠标控制** 一节中打开,并可选择作用于 **当前编辑器**(默认)或 **所有编辑器**。
|
||||
|
||||
@@ -156,7 +156,7 @@ Maven 模块在 **自动** 和 **构建(Make)** 时由 jdtls(ECJ)构建
|
||||
|
||||
每次启动都会在底部的 **运行** 工具窗口里开一个标签页。工具栏有 **重新运行**、**调试**、**重新运行失败的测试**(测试运行时)、**更新应用**、**查找…**、**滚动到末尾**、**软换行**、**全部清除** 和 **编辑配置…**。
|
||||
|
||||
- 输出里的文件路径和堆栈帧都可以点击跳转。
|
||||
- 输出里的文件路径和堆栈帧都可以点击跳转。工具栏的 **沿堆栈跟踪向上** / **沿堆栈跟踪向下**(或 **上一个 / 下一个匹配项**,`⌥⌘↑` / `⌥⌘↓`,Windows 和 Linux 上为 `Ctrl+Alt+↑` / `Ctrl+Alt+↓`)选中上一个 / 下一个链接并打开它;折叠起来的行里的链接会跳过。测试运行时这两个快捷键改为在失败的测试之间跳转。
|
||||
- 重复的行可以折叠。折叠规则、缓冲区大小和控制台编码在 **设置 › 构建、执行、部署 › 控制台** 中配置。控制台右键菜单中的 **折叠与此类似的行** 会打开该页面,并把选中的文本(或右键所在的行)添加为折叠规则。
|
||||
- 日志行可按级别着色(`ERROR`、`WARN`、`INFO`、`DEBUG`、`TRACE`);程序自行输出的颜色保持不变。默认关闭,可在 **设置 › 构建、执行、部署 › 控制台** 开启并修改颜色。
|
||||
- 测试运行时,标签页会在输出旁显示测试树,参见[测试](/zh/guide/testing)。
|
||||
|
||||
@@ -246,6 +246,7 @@ Git 工具窗口的 **日志** 标签页显示提交图。
|
||||
|
||||
- **使用 Git Blame 注解** 在边栏中逐行显示作者和日期(也可以从边栏右键菜单打开)。点击某条记录会在日志中打开对应提交。在 Git 设置中打开 **为当前行显示内联 Git Blame**,会在光标所在行末尾显示作者;点击它会打开对应提交,关闭 **点击内联 Git Blame 时打开提交** 后则不会。
|
||||
- 边栏右键菜单的 **选项 › 姓名** 可让所有已注解的编辑器以 **首字母缩写**、**姓**(默认)、**名** 或 **全名**显示作者。
|
||||
- 注解行的右键菜单中,**注解此修订版** 会打开该提交时的文件(已注解),与工作区文件并排显示。此后重命名过的文件按它在该提交中的名称读取。
|
||||
- 注解行的右键菜单中,**标注上一版本** 会打开该提交之前版本的文件(已注解),与这个提交的版本并排显示。
|
||||
- **标注指定版本…** 可选择文件的任意版本,把该版本(已注解)与工作区文件并排显示。
|
||||
- **显示历史记录** 在 Git 工具窗口的标签页中打开文件历史。
|
||||
|
||||
@@ -136,7 +136,7 @@ register_plugin!(TodoFinder, views);
|
||||
双击和回车用 `event.table_activate()`(API 1.3,从 0 开始的绝对行号)。
|
||||
|
||||
后续 API 新增的主体、字段和事件以 `Other { kind, data }` 传递:IDE 不认识某种主体时会提示需要更新,
|
||||
不认识的字段类型则直接省略。条目右键菜单使用 `viewItem.context`(见 [命令与动作](/zh/plugins/guides/commands) 中的“菜单”一节)。
|
||||
不认识的字段类型则直接省略。条目右键菜单使用 `viewItem.context`(见 [命令与动作](/zh/plugins/guides/commands) 中的“菜单”一节)。视图有键盘焦点时,用快捷键(或查找动作)运行选中条目的右键菜单里有的命令,命令参数是该条目的 key,与从菜单运行相同;未选中条目时没有参数。
|
||||
|
||||
## 自定义编辑器
|
||||
|
||||
|
||||
@@ -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(),
|
||||
],
|
||||
});
|
||||
@@ -0,0 +1,9 @@
|
||||
<!doctype html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
</head>
|
||||
<body>
|
||||
<script type="module" src="./cppNamespaceStyle.fixture.ts"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -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)");
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -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/ })
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
|
||||
|
||||
test("shows why the frames did not load and retries them", async ({ workbench: page }) => {
|
||||
await page.setViewportSize({ width: 940, height: 740 });
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(async () => {
|
||||
const stateModule = "/src/features/debugger/state.ts";
|
||||
const workbenchModule = "/src/workbench/contributions.ts";
|
||||
const { adoptSession, handleDebugEvent } = await import(/* @vite-ignore */ stateModule);
|
||||
const { toolWindowService } = await import(/* @vite-ignore */ workbenchModule);
|
||||
const handlers = window.__ipc.handlers;
|
||||
let failures = 1;
|
||||
handlers.debug_stack_trace = () => {
|
||||
if (failures-- > 0)
|
||||
throw { kind: "protocol", message: "debug adapter did not answer `stackTrace` in time", detail: null };
|
||||
return [{ id: 7, name: "OrderController.place(Order)", path: null, line: 41, column: 0, presentationHint: null }];
|
||||
};
|
||||
handlers.debug_threads = () => [{ id: 9, name: "http-nio-8080-exec-9" }];
|
||||
handlers.debug_scopes = () => [];
|
||||
adoptSession(98, { name: "Orders", adapter: "java-debug", status: "running" });
|
||||
toolWindowService().show("debug", true);
|
||||
handleDebugEvent(98, {
|
||||
kind: "stopped",
|
||||
threadId: 9,
|
||||
allThreadsStopped: false,
|
||||
reason: "breakpoint",
|
||||
description: null,
|
||||
});
|
||||
});
|
||||
|
||||
const frames = page.getByRole("region", { name: "Debug", exact: true }).getByRole("listbox", { name: "Frames" });
|
||||
const error = frames.getByRole("alert");
|
||||
await expect(error).toContainText("Could not load the frames: debug adapter did not answer `stackTrace` in time");
|
||||
await page.screenshot({ path: test.info().outputPath("frames-error.png") });
|
||||
await error.getByRole("button", { name: "Retry" }).click();
|
||||
await expect(frames.getByText("OrderController.place(Order)", { exact: true })).toBeVisible();
|
||||
await expect(error).toBeHidden();
|
||||
expect(await ipcCalls(page, "debug_stack_trace")).toEqual([
|
||||
{ session: 98, threadId: 9 },
|
||||
{ session: 98, threadId: 9 },
|
||||
]);
|
||||
});
|
||||
@@ -303,7 +303,11 @@ public final class BuildModel extends AbstractMavenLifecycleParticipant {
|
||||
json.append("}}");
|
||||
}
|
||||
|
||||
/** The classpaths of the resolved graph, in Maven's order: compile, runtime, test scopes. */
|
||||
/**
|
||||
* The classpaths of the resolved graph, in Maven's order: compile, runtime, test scopes. A
|
||||
* {@code system} jar is on the runtime classpath too: it is an explicit file the launched JVM
|
||||
* must load (IDEA imports the scope as Compile), while {@code provided} is the container's.
|
||||
*/
|
||||
private static void classpaths(DependencyNode root, List<String> compile, List<String> runtime, List<String> test) {
|
||||
List<DependencyNode> nodes = new ArrayList<>();
|
||||
collect(root, nodes, new HashSet<>());
|
||||
@@ -314,7 +318,7 @@ public final class BuildModel extends AbstractMavenLifecycleParticipant {
|
||||
String scope = node.getDependency().getScope();
|
||||
String path = file.getAbsolutePath();
|
||||
if (!"test".equals(scope) && !"runtime".equals(scope)) compile.add(path);
|
||||
if (!"test".equals(scope) && !"provided".equals(scope) && !"system".equals(scope)) runtime.add(path);
|
||||
if (!"test".equals(scope) && !"provided".equals(scope)) runtime.add(path);
|
||||
test.add(path);
|
||||
}
|
||||
}
|
||||
|
||||
Бінарний файл не відображається.
@@ -170,7 +170,11 @@ its first `:`, so `pod` for `pod:default/nginx`; the whole key when it has no
|
||||
`:`). Only the menu's `when` sees them, not the command's own `when`; a command
|
||||
whose `when` is false shows greyed out. Other menus refuse `view`, a web view
|
||||
has no item menu, and no menu opens when no declaration matches the item.
|
||||
The menu is new in API 1.2, so a plugin using it declares
|
||||
A command run without an argument (its shortcut, Find Action) while one of the
|
||||
plugin's views has the keyboard focus gets the selected item's key too, when
|
||||
that item's `viewItem.context` menu offers the command: a shortcut acts on the
|
||||
selected item like the menu entry. With nothing selected, the focus elsewhere or
|
||||
the command not in the item's menu, it gets none. The menu is new in API 1.2, so a plugin using it declares
|
||||
`engines.openidea = "^1.2"`. For example:
|
||||
|
||||
```toml
|
||||
|
||||
@@ -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/);
|
||||
});
|
||||
});
|
||||
@@ -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);
|
||||
});
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -48,7 +48,7 @@ pub async fn clipboard_write_image(app: AppHandle, window: WebviewWindow, png: S
|
||||
|
||||
/// The clipboard's plain text, read natively as [`clipboard_write_text`] writes it: a Paste
|
||||
/// from a menu has no paste event, and WebKitGTK gives `navigator.clipboard.readText()` no
|
||||
/// text there (#3041). None on Windows, where the WebView's clipboard is used.
|
||||
/// text there (#3041); WebView2 asks the user before letting the page read it.
|
||||
#[desktop_command(trust = trusted)]
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
@@ -67,15 +67,10 @@ pub async fn clipboard_text(app: AppHandle) -> IdeResult<Option<String>> {
|
||||
.map_err(|error| IdeError::internal(format!("Cannot dispatch clipboard access to the main thread: {error}")))?;
|
||||
Ok(rx.await.ok().flatten())
|
||||
}
|
||||
#[cfg(target_os = "macos")]
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
{
|
||||
with_clipboard(app, || Ok(ide_clipboard::text())).await
|
||||
}
|
||||
#[cfg(not(any(target_os = "macos", target_os = "linux")))]
|
||||
{
|
||||
let _ = app;
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
|
||||
/// Absolute paths on the clipboard, empty when it holds no file list.
|
||||
|
||||
@@ -463,7 +463,23 @@ pub fn menu_model(app: AppHandle, state: State<'_, AppState>, menu_state: State<
|
||||
}
|
||||
let home = dirs::home_dir();
|
||||
let config = menu_state.config.lock().clone();
|
||||
menu::model(&spec, &menu::recent_items(&state.recent.list(), home.as_deref()), &config)
|
||||
let remote = menu_state.remote_recent.lock().clone();
|
||||
menu::model(&spec, &menu::recent_items(&state.recent.list(), &remote, home.as_deref()), &config)
|
||||
}
|
||||
|
||||
/// The Remote Development projects of the frontend's recent list, for Open Recent.
|
||||
#[desktop_command(trust = always)]
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn menu_set_remote_recent(
|
||||
app: AppHandle,
|
||||
menu_state: State<'_, MenuState>,
|
||||
state: State<'_, AppState>,
|
||||
projects: Vec<menu::RemoteRecent>,
|
||||
) {
|
||||
if menu::store_remote_recent(&menu_state, projects) {
|
||||
menu::install(&app, &menu_state, &state.recent.list());
|
||||
}
|
||||
}
|
||||
|
||||
/// Action ids the focused window cannot run now: their native menu items are
|
||||
@@ -597,7 +613,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 +648,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 +723,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 +777,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 +801,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 +818,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 +936,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 +974,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");
|
||||
@@ -962,6 +1012,7 @@ ide_command::desktop_domain!(
|
||||
menu_model,
|
||||
menu_refresh,
|
||||
menu_set_disabled,
|
||||
menu_set_remote_recent,
|
||||
window_begin_prompt,
|
||||
window_close_context,
|
||||
window_complete_launch,
|
||||
|
||||
@@ -1117,6 +1117,31 @@ pub struct MenuState {
|
||||
/// Visible menu last installed. Accelerators of actions that are not on the menu
|
||||
/// are not part of this, so they must not redraw the macOS menu bar.
|
||||
rendered: Mutex<Option<Vec<RenderedMenu>>>,
|
||||
/// The Remote Development projects of the frontend's recent list.
|
||||
pub remote_recent: Mutex<Vec<RemoteRecent>>,
|
||||
}
|
||||
|
||||
/// A recent Remote Development project (SSH, WSL, Dev Container), kept by the frontend: Open
|
||||
/// Recent lists it among the local projects, as Manage Projects does.
|
||||
#[derive(Debug, Clone, PartialEq, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct RemoteRecent {
|
||||
/// `ssh://host/path`, `wsl://Ubuntu/path`…: what `file.openRecentProject` gets back.
|
||||
pub location: String,
|
||||
pub name: String,
|
||||
/// Where it lives, as shown after the name (`me@host:/srv/app`).
|
||||
pub detail: String,
|
||||
pub opened_at_ms: f64,
|
||||
}
|
||||
|
||||
/// Stores the remote recent list; `false` when it is unchanged.
|
||||
pub fn store_remote_recent(state: &MenuState, next: Vec<RemoteRecent>) -> bool {
|
||||
let mut current = state.remote_recent.lock();
|
||||
if *current == next {
|
||||
return false;
|
||||
}
|
||||
*current = next;
|
||||
true
|
||||
}
|
||||
|
||||
/// Stores `next` when it differs from the config last used to build the menu.
|
||||
@@ -1193,18 +1218,28 @@ pub struct RecentItem {
|
||||
pub label: String,
|
||||
}
|
||||
|
||||
pub fn recent_items(recent: &[ide_workspace::RecentProject], home: Option<&Path>) -> Vec<RecentItem> {
|
||||
recent
|
||||
.iter()
|
||||
.take(MAX_RECENT)
|
||||
.map(|p| {
|
||||
let shown = match home.and_then(|h| p.path.strip_prefix(h).ok()) {
|
||||
Some(rest) => format!("~/{}", rest.display()),
|
||||
None => p.path.display().to_string(),
|
||||
};
|
||||
RecentItem { path: p.path.to_string_lossy().into_owned(), label: format!("{} — {shown}", p.name) }
|
||||
})
|
||||
.collect()
|
||||
/// The local and remote recent projects, most recently opened first.
|
||||
pub fn recent_items(
|
||||
recent: &[ide_workspace::RecentProject],
|
||||
remote: &[RemoteRecent],
|
||||
home: Option<&Path>,
|
||||
) -> Vec<RecentItem> {
|
||||
let local = recent.iter().map(|p| {
|
||||
let shown = match home.and_then(|h| p.path.strip_prefix(h).ok()) {
|
||||
Some(rest) => format!("~/{}", rest.display()),
|
||||
None => p.path.display().to_string(),
|
||||
};
|
||||
let item =
|
||||
RecentItem { path: p.path.to_string_lossy().into_owned(), label: format!("{} — {shown}", p.name) };
|
||||
(p.opened_at_ms, item)
|
||||
});
|
||||
let remote = remote.iter().map(|r| {
|
||||
(r.opened_at_ms, RecentItem { path: r.location.clone(), label: format!("{} — {}", r.name, r.detail) })
|
||||
});
|
||||
let mut items: Vec<(f64, RecentItem)> = local.chain(remote).collect();
|
||||
// Stable: the local list's own order holds among equal times.
|
||||
items.sort_by(|a, b| b.0.total_cmp(&a.0));
|
||||
items.into_iter().take(MAX_RECENT).map(|(_, item)| item).collect()
|
||||
}
|
||||
|
||||
/// One top-level menu, as it will actually be drawn.
|
||||
@@ -1746,7 +1781,7 @@ pub fn install<R: Runtime>(app: &AppHandle<R>, menu_state: &MenuState, recent: &
|
||||
return;
|
||||
}
|
||||
let home = dirs::home_dir();
|
||||
let items = recent_items(recent, home.as_deref());
|
||||
let items = recent_items(recent, &menu_state.remote_recent.lock(), home.as_deref());
|
||||
let config = menu_state.config.lock().clone();
|
||||
let disabled = menu_state.disabled.lock().clone();
|
||||
let rendered = render_bar(&prepared_spec(app, Os::current()), &config, &items);
|
||||
@@ -2233,11 +2268,39 @@ mod tests {
|
||||
branch: None,
|
||||
missing: false,
|
||||
}];
|
||||
let items = recent_items(&recent, Some(Path::new("/home/me")));
|
||||
let items = recent_items(&recent, &[], Some(Path::new("/home/me")));
|
||||
assert_eq!(items[0].label, "openidea — ~/code/openidea");
|
||||
assert_eq!(items[0].path, "/home/me/code/openidea");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remote_projects_join_the_recent_list_by_when_they_were_opened() {
|
||||
let local = |path: &str, at: f64| ide_workspace::RecentProject {
|
||||
path: path.into(),
|
||||
name: path.rsplit('/').next().unwrap().into(),
|
||||
opened_at_ms: at,
|
||||
branch: None,
|
||||
missing: false,
|
||||
};
|
||||
let recent = vec![local("/home/me/new", 30.0), local("/home/me/old", 10.0)];
|
||||
let remote = [RemoteRecent {
|
||||
location: "wsl://Ubuntu/home/me/api".into(),
|
||||
name: "api".into(),
|
||||
detail: "Ubuntu:/home/me/api".into(),
|
||||
opened_at_ms: 20.0,
|
||||
}];
|
||||
let items = recent_items(&recent, &remote, Some(Path::new("/home/me")));
|
||||
let paths: Vec<&str> = items.iter().map(|i| i.path.as_str()).collect();
|
||||
assert_eq!(paths, ["/home/me/new", "wsl://Ubuntu/home/me/api", "/home/me/old"]);
|
||||
assert_eq!(items[1].label, "api — Ubuntu:/home/me/api");
|
||||
|
||||
let many: Vec<_> = (0..20).map(|i| local(&format!("/p/{i}"), f64::from(i))).collect();
|
||||
let items = recent_items(&many, &remote, None);
|
||||
assert_eq!(items.len(), MAX_RECENT);
|
||||
assert_eq!([items[0].path.as_str(), items[1].path.as_str()], ["wsl://Ubuntu/home/me/api", "/p/19"]);
|
||||
assert_eq!(items[MAX_RECENT - 1].path, format!("/p/{}", 20 - MAX_RECENT + 1), "the remote one takes a slot");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn model_drops_native_roles_and_fills_recent() {
|
||||
let spec = vec![sub(
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -471,6 +471,13 @@ fn unversioned_server_binary(data: &std::path::Path, os: &str, arch: &str) -> Op
|
||||
Some(data.join("server").join(format!("{os}-{arch}")).join("openidea-server")).filter(|p| p.is_file())
|
||||
}
|
||||
|
||||
/// Whether the server binary at `path` names `version` anywhere: every build embeds its own
|
||||
/// version (`--version`), so a binary without it is certainly another version. The binary is
|
||||
/// for the remote platform, so it can't be asked here.
|
||||
fn mentions_version(path: &std::path::Path, version: &str) -> bool {
|
||||
std::fs::read(path).is_ok_and(|bytes| bytes.windows(version.len()).any(|w| w == version.as_bytes()))
|
||||
}
|
||||
|
||||
/// The release build of the server for `os`/`arch`, downloaded once into the data dir.
|
||||
async fn download_server(
|
||||
state: &AppState,
|
||||
@@ -541,6 +548,15 @@ pub(crate) async fn local_server(
|
||||
return Ok(LocalServer::Installed(bin.clone()));
|
||||
}
|
||||
match unversioned_server_binary(&state.local_data_dir, os, arch) {
|
||||
// A server of another version fails the handshake with a bare EOF (#5742).
|
||||
Some(local) if !mentions_version(&local, version) => {
|
||||
return Err(IdeError::unavailable(format!(
|
||||
"no openidea-server {version} for {os}-{arch} ({}), and {} is another version. Delete it, \
|
||||
or replace it with openidea-server-{os}-{arch}.gz from the {version} release, unpacked",
|
||||
e.message,
|
||||
local.display()
|
||||
)));
|
||||
}
|
||||
Some(local) => {
|
||||
tracing::warn!(
|
||||
"no openidea-server {version} for {os}-{arch} ({}); using {}, which may be another version",
|
||||
@@ -657,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| {
|
||||
@@ -688,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}")))?;
|
||||
@@ -707,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)
|
||||
@@ -724,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
|
||||
@@ -1398,6 +1421,16 @@ async fn invoke_reply(peer: &Peer, call: Invoke, entries_timeout: std::time::Dur
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_hand_placed_server_of_another_version_is_recognised() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let bin = dir.path().join("openidea-server");
|
||||
std::fs::write(&bin, b"\x7fELF...openidea-server 0.1.43 (protocol 2)...").unwrap();
|
||||
assert!(mentions_version(&bin, "0.1.43"));
|
||||
assert!(!mentions_version(&bin, "0.1.51"));
|
||||
assert!(!mentions_version(&dir.path().join("missing"), "0.1.51"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remote_locations_round_trip_like_the_frontend() {
|
||||
let cases = [
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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(¤t).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);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
@@ -428,6 +429,7 @@ menu_configure always desktop bin
|
||||
menu_model always desktop bindings sync
|
||||
menu_refresh always desktop bindings sync
|
||||
menu_set_disabled always desktop bindings sync
|
||||
menu_set_remote_recent always desktop bindings sync
|
||||
nav_index_definitions always project_host bindings async
|
||||
nav_inheritance always project_host bindings async
|
||||
nav_python_stubs always project_host bindings async
|
||||
|
||||
+27
-3
@@ -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. */
|
||||
@@ -305,7 +307,7 @@ export const commands = {
|
||||
/**
|
||||
* The clipboard's plain text, read natively as [`clipboard_write_text`] writes it: a Paste
|
||||
* from a menu has no paste event, and WebKitGTK gives `navigator.clipboard.readText()` no
|
||||
* text there (#3041). None on Windows, where the WebView's clipboard is used.
|
||||
* text there (#3041); WebView2 asks the user before letting the page read it.
|
||||
*/
|
||||
clipboardText: () => typedError<string | null, IdeError>(__TAURI_INVOKE("clipboard_text")),
|
||||
/** Copies image pixels to this computer's clipboard, including from remote project windows. */
|
||||
@@ -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 })),
|
||||
@@ -1157,6 +1162,8 @@ export const commands = {
|
||||
* disabled in place (no rebuild).
|
||||
*/
|
||||
menuSetDisabled: (ids: string[]) => __TAURI_INVOKE<void>("menu_set_disabled", { ids }),
|
||||
/** The Remote Development projects of the frontend's recent list, for Open Recent. */
|
||||
menuSetRemoteRecent: (projects: RemoteRecent[]) => __TAURI_INVOKE<void>("menu_set_remote_recent", { projects }),
|
||||
/**
|
||||
* Index definitions named `name` within the roots `from` may navigate into (its own root
|
||||
* plus its configured dependencies).
|
||||
@@ -1512,7 +1519,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 +3787,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 +6857,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. */
|
||||
@@ -12157,6 +12168,19 @@ export type RemoteProject_Serialize = {
|
||||
project: ProjectInfo_Serialize,
|
||||
};
|
||||
|
||||
/**
|
||||
* A recent Remote Development project (SSH, WSL, Dev Container), kept by the frontend: Open
|
||||
* Recent lists it among the local projects, as Manage Projects does.
|
||||
*/
|
||||
export type RemoteRecent = {
|
||||
/** `ssh://host/path`, `wsl://Ubuntu/path`…: what `file.openRecentProject` gets back. */
|
||||
location: string,
|
||||
name: string,
|
||||
/** Where it lives, as shown after the name (`me@host:/srv/app`). */
|
||||
detail: string,
|
||||
openedAtMs: number | null,
|
||||
};
|
||||
|
||||
export type RemoteSession = RemoteSession_Serialize | RemoteSession_Deserialize;
|
||||
|
||||
export type RemoteSession_Deserialize = {
|
||||
|
||||
@@ -24,8 +24,10 @@ import {
|
||||
moveStatementUp,
|
||||
nextOccurrence,
|
||||
selectAllOccurrences,
|
||||
selectLineAtCaret,
|
||||
startNewLine,
|
||||
startNewLineBefore,
|
||||
swapSelectionBoundaries,
|
||||
toggleCase,
|
||||
unselectOccurrence,
|
||||
} from "./cm/editing";
|
||||
@@ -73,13 +75,19 @@ import {
|
||||
cursorMatchBrace,
|
||||
cursorPageBottom,
|
||||
cursorPageTop,
|
||||
cursorParagraphBackward,
|
||||
cursorParagraphForward,
|
||||
scrollDown,
|
||||
scrollToBottom,
|
||||
scrollToCenter,
|
||||
scrollToTop,
|
||||
scrollUp,
|
||||
selectCodeBlockEnd,
|
||||
selectCodeBlockStart,
|
||||
selectPageBottom,
|
||||
selectPageTop,
|
||||
selectParagraphBackward,
|
||||
selectParagraphForward,
|
||||
splitLine,
|
||||
} from "./cm/caretCommands";
|
||||
import { isOverwrite, toggleOverwrite } from "./cm/overwrite";
|
||||
@@ -1020,6 +1028,8 @@ export function registerEditorActions(): () => void {
|
||||
caret("editor.scrollToCenter", "Scroll to Center", (v) => scrollToCenter(v), { category: "Editor Actions" }),
|
||||
caret("editor.scrollUp", "Scroll Up", (v) => scrollUp(v), { category: "Editor Actions" }),
|
||||
caret("editor.scrollDown", "Scroll Down", (v) => scrollDown(v), { category: "Editor Actions" }),
|
||||
caret("editor.scrollToTop", "Scroll to Top", (v) => scrollToTop(v), { category: "Editor Actions" }),
|
||||
caret("editor.scrollToBottom", "Scroll to Bottom", (v) => scrollToBottom(v), { category: "Editor Actions" }),
|
||||
caret("editor.moveToPageTop", "Move Caret to Page Top", (v) => cursorPageTop(v), { category: "Editor Actions" }),
|
||||
caret("editor.moveToPageBottom", "Move Caret to Page Bottom", (v) => cursorPageBottom(v), {
|
||||
category: "Editor Actions",
|
||||
@@ -1053,6 +1063,24 @@ export function registerEditorActions(): () => void {
|
||||
category: "Editor Actions",
|
||||
},
|
||||
),
|
||||
caret("editor.paragraphForward", "Move Caret Forward a Paragraph", (v) => cursorParagraphForward(v), {
|
||||
category: "Editor Actions",
|
||||
}),
|
||||
caret("editor.paragraphBackward", "Move Caret Backward a Paragraph", (v) => cursorParagraphBackward(v), {
|
||||
category: "Editor Actions",
|
||||
}),
|
||||
caret(
|
||||
"editor.paragraphForwardWithSelection",
|
||||
"Move Caret Forward a Paragraph with Selection",
|
||||
(v) => selectParagraphForward(v),
|
||||
{ category: "Editor Actions" },
|
||||
),
|
||||
caret(
|
||||
"editor.paragraphBackwardWithSelection",
|
||||
"Move Caret Backward a Paragraph with Selection",
|
||||
(v) => selectParagraphBackward(v),
|
||||
{ category: "Editor Actions" },
|
||||
),
|
||||
text("editor.contextInfo", "Context Info", (v) => showContextInfo(v), {
|
||||
category: "View",
|
||||
keywords: ["enclosing method", "enclosing class", "where am I"],
|
||||
@@ -1117,6 +1145,11 @@ export function registerEditorActions(): () => void {
|
||||
caret("code.addCaretsToLineEnds", "Add Carets to Ends of Selected Lines", (v) => addCaretsToLineEnds(v), {
|
||||
category: "Edit",
|
||||
}),
|
||||
caret("editor.swapSelectionBoundaries", "Swap Selection Boundaries", (v) => swapSelectionBoundaries(v), {
|
||||
category: "Editor Actions",
|
||||
keywords: ["anchor", "exchange point and mark"],
|
||||
}),
|
||||
caret("editor.selectLine", "Select Line at Caret", (v) => selectLineAtCaret(v), { category: "Editor Actions" }),
|
||||
occurrence("code.unselectOccurrence", "Unselect Occurrence", unselectOccurrence),
|
||||
text("code.pasteFromHistory", "Paste from History…", (v) => pasteFromHistory(v), {
|
||||
category: "Edit",
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { afterEach, beforeAll, describe, expect, it } from "vitest";
|
||||
import { EditorSelection, EditorState } from "@codemirror/state";
|
||||
import { EditorSelection, EditorState, StateEffect } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { indentService, type LanguageSupport } from "@codemirror/language";
|
||||
import { languages } from "@codemirror/language-data";
|
||||
@@ -9,10 +9,17 @@ import {
|
||||
codeBlockStart,
|
||||
cursorPageBottom,
|
||||
cursorPageTop,
|
||||
cursorParagraphBackward,
|
||||
cursorParagraphForward,
|
||||
nextParagraphBoundary,
|
||||
previousParagraphBoundary,
|
||||
scrollDown,
|
||||
scrollToBottom,
|
||||
scrollToTop,
|
||||
scrollUp,
|
||||
selectPageBottom,
|
||||
selectPageTop,
|
||||
selectParagraphForward,
|
||||
splitLine,
|
||||
} from "./caretCommands";
|
||||
import { editorBaseKeymap } from "./baseKeymap";
|
||||
@@ -104,6 +111,63 @@ describe("Scroll Up / Scroll Down", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("Scroll to Top / Scroll to Bottom", () => {
|
||||
/** jsdom has no layout: record where each command asks the view to scroll. */
|
||||
function scrolls(text: string) {
|
||||
const targets: { from: number; to: number; y: unknown }[] = [];
|
||||
const view = make(text);
|
||||
view.dispatch({
|
||||
effects: StateEffect.appendConfig.of(
|
||||
EditorView.scrollHandler.of(
|
||||
(_, range, options) => (targets.push({ from: range.from, to: range.to, y: options.y }), true),
|
||||
),
|
||||
),
|
||||
});
|
||||
return { view, targets };
|
||||
}
|
||||
/** The view scrolls in its next measure, on an animation frame. */
|
||||
const frame = () => new Promise((resolve) => requestAnimationFrame(resolve));
|
||||
|
||||
it("scrolls to the very top, keeping the horizontal position", async () => {
|
||||
const view = make("a\nb|\nc\nd");
|
||||
let top = 120;
|
||||
Object.defineProperty(view.scrollDOM, "scrollTop", {
|
||||
configurable: true,
|
||||
get: () => top,
|
||||
set: (v: number) => (top = v),
|
||||
});
|
||||
view.scrollDOM.scrollLeft = 40;
|
||||
expect(scrollToTop(view)).toBe(true);
|
||||
await frame();
|
||||
expect(top).toBe(0);
|
||||
expect(view.scrollDOM.scrollLeft).toBe(40);
|
||||
});
|
||||
|
||||
it("brings the end of the file toward the middle", async () => {
|
||||
const { view, targets } = scrolls("a\nb|\nc\nd");
|
||||
expect(scrollToBottom(view)).toBe(true);
|
||||
await frame();
|
||||
expect(targets).toEqual([{ from: 7, to: 7, y: "center" }]);
|
||||
});
|
||||
|
||||
it("leaves the carets, the selection and the document as they are", () => {
|
||||
const { view } = scrolls("|a\nb\nc");
|
||||
view.dispatch({ selection: EditorSelection.create([EditorSelection.range(0, 3), EditorSelection.cursor(5)], 1) });
|
||||
const before = view.state.selection;
|
||||
scrollToBottom(view);
|
||||
scrollToTop(view);
|
||||
expect(view.state.selection.eq(before)).toBe(true);
|
||||
expect(view.state.doc.toString()).toBe("a\nb\nc");
|
||||
});
|
||||
|
||||
it("works in an empty file", async () => {
|
||||
const { view, targets } = scrolls("|");
|
||||
scrollToBottom(view);
|
||||
await frame();
|
||||
expect(targets).toEqual([{ from: 0, to: 0, y: "center" }]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Move Caret to Page Top / Bottom", () => {
|
||||
/** jsdom has no layout: show the document from `top` for `height` pixels (in line heights). */
|
||||
function page(view: EditorView, top: number, height: number) {
|
||||
@@ -227,6 +291,75 @@ describe("code block navigation", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("paragraph navigation", () => {
|
||||
// Lines: "a1", "a2", "", "b1", "b2", " ", "c1", "c2".
|
||||
const text = "a1\na2\n\nb1\nb2\n \nc1\nc2";
|
||||
const state = EditorState.create({ doc: text });
|
||||
const empty = text.indexOf("\n\n") + 1;
|
||||
const spaces = text.indexOf(" ");
|
||||
const c1 = text.indexOf("c1");
|
||||
const at = (s: string) => text.indexOf(s);
|
||||
|
||||
it("goes forward to the next blank line, whitespace-only included, or the end of the text", () => {
|
||||
expect(nextParagraphBoundary(state, 0)).toBe(empty);
|
||||
expect(nextParagraphBoundary(state, at("a2") + 1)).toBe(empty);
|
||||
expect(nextParagraphBoundary(state, at("b1") + 1)).toBe(spaces);
|
||||
// From a blank line: past it and the paragraph after it.
|
||||
expect(nextParagraphBoundary(state, empty)).toBe(spaces);
|
||||
expect(nextParagraphBoundary(state, spaces + 1)).toBe(text.length);
|
||||
expect(nextParagraphBoundary(state, at("c2"))).toBe(text.length);
|
||||
});
|
||||
|
||||
it("goes backward to the empty line before the paragraph, or the line after a whitespace-only one", () => {
|
||||
expect(previousParagraphBoundary(state, at("c2") + 1)).toBe(c1);
|
||||
expect(previousParagraphBoundary(state, at("b2") + 2)).toBe(empty);
|
||||
expect(previousParagraphBoundary(state, at("a2") + 1)).toBe(0);
|
||||
expect(previousParagraphBoundary(state, 0)).toBe(0);
|
||||
});
|
||||
|
||||
it("goes backward past the paragraph above from a line start or a blank line", () => {
|
||||
expect(previousParagraphBoundary(state, c1)).toBe(empty);
|
||||
expect(previousParagraphBoundary(state, spaces + 2)).toBe(empty);
|
||||
expect(previousParagraphBoundary(state, at("b1"))).toBe(0);
|
||||
expect(previousParagraphBoundary(state, empty)).toBe(0);
|
||||
});
|
||||
|
||||
it("does not stall on a whitespace-only line when pressed repeatedly", () => {
|
||||
const stops: number[] = [];
|
||||
let pos = text.length;
|
||||
while (pos > 0) stops.push((pos = previousParagraphBoundary(state, pos)));
|
||||
expect(stops).toEqual([c1, empty, 0]);
|
||||
stops.length = 0;
|
||||
while (pos < text.length) stops.push((pos = nextParagraphBoundary(state, pos)));
|
||||
expect(stops).toEqual([empty, spaces, text.length]);
|
||||
});
|
||||
|
||||
it("treats a document with no blank line as one paragraph", () => {
|
||||
const one = EditorState.create({ doc: "x\ny" });
|
||||
expect(nextParagraphBoundary(one, 0)).toBe(3);
|
||||
expect(previousParagraphBoundary(one, 3)).toBe(0);
|
||||
const blank = EditorState.create({ doc: "" });
|
||||
expect(nextParagraphBoundary(blank, 0)).toBe(0);
|
||||
expect(previousParagraphBoundary(blank, 0)).toBe(0);
|
||||
});
|
||||
|
||||
it("moves every caret, merging carets that land together", () => {
|
||||
const view = make("a|1\na|2\n\nb|1\nb2");
|
||||
expect(cursorParagraphForward(view)).toBe(true);
|
||||
expect(show(view)).toBe("a1\na2\n|\nb1\nb2|");
|
||||
expect(cursorParagraphBackward(view)).toBe(true);
|
||||
expect(show(view)).toBe("|a1\na2\n|\nb1\nb2");
|
||||
});
|
||||
|
||||
it("with Selection extends each selection from its anchor", () => {
|
||||
const view = make("a1\na|2\n\nb1");
|
||||
selectParagraphForward(view);
|
||||
expect(view.state.selection.main).toMatchObject({ anchor: 4, head: 6 });
|
||||
selectParagraphForward(view);
|
||||
expect(view.state.selection.main).toMatchObject({ anchor: 4, head: 9 });
|
||||
});
|
||||
});
|
||||
|
||||
describe("editor base keymap", () => {
|
||||
it("drops CodeMirror defaults that IDEA uses for other actions", () => {
|
||||
const runs = editorBaseKeymap.map((b) => b.run);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
/** IDEA caret commands that CodeMirror has no equivalent for: Split Line, Scroll to Center / Up / Down, Page Top / Bottom, code block and brace navigation. */
|
||||
/** IDEA caret commands that CodeMirror has no equivalent for: Split Line, Scroll to Center / Up / Down / Top / Bottom, Page Top / Bottom, code block, brace and paragraph navigation. */
|
||||
import { countColumn, EditorSelection, findColumn, type EditorState, type Transaction } from "@codemirror/state";
|
||||
import { EditorView, type Command } from "@codemirror/view";
|
||||
import { insertNewlineAndIndent } from "@codemirror/commands";
|
||||
@@ -36,6 +36,16 @@ const scrollByLine =
|
||||
export const scrollUp = scrollByLine(-1);
|
||||
export const scrollDown = scrollByLine(1);
|
||||
|
||||
/** Scroll to Top / Scroll to Bottom (as IDEA): show the start of the file at the top, or bring its end toward the middle, without moving the caret. */
|
||||
export const scrollToTop: Command = (view) => {
|
||||
view.scrollDOM.scrollTop = 0;
|
||||
return true;
|
||||
};
|
||||
export const scrollToBottom: Command = (view) => {
|
||||
view.dispatch({ effects: EditorView.scrollIntoView(view.state.doc.length, { y: "center" }) });
|
||||
return true;
|
||||
};
|
||||
|
||||
/**
|
||||
* The line Move Caret to Page Top / Bottom goes to (as IDEA): the first / last line
|
||||
* the scroller shows whole; a partly hidden edge line only when there is no other.
|
||||
@@ -152,6 +162,63 @@ export const cursorCodeBlockEnd = moveToBlock(codeBlockEnd);
|
||||
export const selectCodeBlockStart = moveToBlock(codeBlockStart, true);
|
||||
export const selectCodeBlockEnd = moveToBlock(codeBlockEnd, true);
|
||||
|
||||
/** A line with nothing but whitespace, which separates paragraphs. */
|
||||
const isBlankLine = (text: string) => !/\S/.test(text);
|
||||
|
||||
/**
|
||||
* Where Move Caret Forward a Paragraph goes from `pos` (as IDEA, after Emacs
|
||||
* `forward-paragraph`): past any blank lines at the caret, then to the start of
|
||||
* the next blank line, or the end of the text.
|
||||
*/
|
||||
export function nextParagraphBoundary(state: EditorState, pos: number): number {
|
||||
const { doc } = state;
|
||||
let line = doc.lineAt(pos).number;
|
||||
if (isBlankLine(doc.line(line).text)) while (++line <= doc.lines && isBlankLine(doc.line(line).text));
|
||||
while (++line <= doc.lines) {
|
||||
if (isBlankLine(doc.line(line).text)) return doc.line(line).from;
|
||||
}
|
||||
return doc.length;
|
||||
}
|
||||
|
||||
/**
|
||||
* Where Move Caret Backward a Paragraph goes from `pos`: back over the
|
||||
* paragraph (from a blank line or a line start, past the blank lines above
|
||||
* first) to the empty line before it, or the start of the line after a
|
||||
* whitespace-only one; the start of the text when there is none.
|
||||
*/
|
||||
export function previousParagraphBoundary(state: EditorState, pos: number): number {
|
||||
const { doc } = state;
|
||||
const at = doc.lineAt(pos);
|
||||
let line = at.number;
|
||||
if (pos === at.from || isBlankLine(at.text)) while (--line >= 1 && isBlankLine(doc.line(line).text));
|
||||
while (--line >= 1 && !isBlankLine(doc.line(line).text));
|
||||
if (line < 1) return 0;
|
||||
const target = doc.line(line);
|
||||
return target.length === 0 ? target.from : doc.line(line + 1).from;
|
||||
}
|
||||
|
||||
/** Move Caret Forward / Backward a Paragraph (with Selection), for every caret. */
|
||||
function moveByParagraph(find: (state: EditorState, pos: number) => number, extend = false): Command {
|
||||
return (view) => {
|
||||
const { state } = view;
|
||||
const ranges = state.selection.ranges.map((r) => {
|
||||
const head = find(state, r.head);
|
||||
return extend ? EditorSelection.range(r.anchor, head) : EditorSelection.cursor(head);
|
||||
});
|
||||
view.dispatch({
|
||||
selection: EditorSelection.create(ranges, state.selection.mainIndex),
|
||||
scrollIntoView: true,
|
||||
userEvent: extend ? "select" : "select.navigate",
|
||||
});
|
||||
return true;
|
||||
};
|
||||
}
|
||||
|
||||
export const cursorParagraphForward = moveByParagraph(nextParagraphBoundary);
|
||||
export const cursorParagraphBackward = moveByParagraph(previousParagraphBoundary);
|
||||
export const selectParagraphForward = moveByParagraph(nextParagraphBoundary, true);
|
||||
export const selectParagraphBackward = moveByParagraph(previousParagraphBoundary, true);
|
||||
|
||||
/**
|
||||
* The inside of the `{…}` block around `pos` (between the braces) for Collapse Block;
|
||||
* after a `}` the block it closes. `null` outside any block.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { EditorSelection, EditorState, type Extension } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { history, insertNewlineAndIndent, redo, undo } from "@codemirror/commands";
|
||||
import { history, insertNewlineAndIndent, redo, selectCharLeft, undo } from "@codemirror/commands";
|
||||
import { indentOnInput, indentService, indentUnit, ensureSyntaxTree } from "@codemirror/language";
|
||||
import {
|
||||
addCaretsToLineEnds,
|
||||
@@ -11,8 +11,10 @@ import {
|
||||
deleteLine,
|
||||
duplicateEntireLines,
|
||||
joinLines,
|
||||
selectLineAtCaret,
|
||||
startNewLine,
|
||||
startNewLineBefore,
|
||||
swapSelectionBoundaries,
|
||||
toggleCase,
|
||||
unselectOccurrence,
|
||||
} from "./editing";
|
||||
@@ -254,6 +256,65 @@ describe("cycle case", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("select line at caret", () => {
|
||||
it("selects the caret's line with its line break, the head after it", () => {
|
||||
const v = make("a|b\ncd");
|
||||
expect(selectLineAtCaret(v)).toBe(true);
|
||||
expect(show(v)).toBe("[ab\n]cd");
|
||||
expect(v.state.selection.main).toMatchObject({ anchor: 0, head: 3 });
|
||||
selectLineAtCaret(v);
|
||||
expect(show(v)).toBe("[ab\n]cd");
|
||||
});
|
||||
|
||||
it("selects up to the end of the document on the last line", () => {
|
||||
const v = make("ab\nc|d");
|
||||
selectLineAtCaret(v);
|
||||
expect(show(v)).toBe("ab\n[cd]");
|
||||
});
|
||||
|
||||
it("grows a selection to the whole lines it touches, keeping its direction", () => {
|
||||
const v = make("x\na[b\nc]d\ne");
|
||||
selectLineAtCaret(v);
|
||||
expect(show(v)).toBe("x\n[ab\ncd\n]e");
|
||||
expect(v.state.selection.main).toMatchObject({ anchor: 2, head: 8 });
|
||||
|
||||
const back = make("x\nab\ncd\ne");
|
||||
back.dispatch({ selection: { anchor: 6, head: 3 } });
|
||||
selectLineAtCaret(back);
|
||||
expect(back.state.selection.main).toMatchObject({ anchor: 8, head: 2 });
|
||||
});
|
||||
|
||||
it("leaves out the line where a selection ends at its start", () => {
|
||||
const v = make("[ab\n]cd\nef");
|
||||
selectLineAtCaret(v);
|
||||
expect(show(v)).toBe("[ab\n]cd\nef");
|
||||
const partial = make("a[b\n]cd");
|
||||
selectLineAtCaret(partial);
|
||||
expect(show(partial)).toBe("[ab\n]cd");
|
||||
});
|
||||
|
||||
it("selects each caret's line, once per line", () => {
|
||||
const v = make("a|b\ncd\ne|f");
|
||||
selectLineAtCaret(v);
|
||||
expect(show(v)).toBe("[ab\n]cd\n[ef]");
|
||||
expect(v.state.selection.ranges).toHaveLength(2);
|
||||
|
||||
const one = make("a|b|c\nd");
|
||||
selectLineAtCaret(one);
|
||||
expect(show(one)).toBe("[abc\n]d");
|
||||
expect(one.state.selection.ranges).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("selects in a read-only editor and on an empty line", () => {
|
||||
const v = make("ab\n|\ncd", EditorState.readOnly.of(true));
|
||||
expect(selectLineAtCaret(v)).toBe(true);
|
||||
expect(show(v)).toBe("ab\n[\n]cd");
|
||||
const empty = make("|");
|
||||
expect(selectLineAtCaret(empty)).toBe(true);
|
||||
expect(show(empty)).toBe("|");
|
||||
});
|
||||
});
|
||||
|
||||
describe("multiple carets", () => {
|
||||
it("adds carets at the ends of the selected lines", () => {
|
||||
const v = make("[ab\ncd\nef]\ngh");
|
||||
@@ -281,6 +342,48 @@ describe("multiple carets", () => {
|
||||
expect(unselectOccurrence(v)).toBe(false);
|
||||
});
|
||||
|
||||
it("swaps the caret to the other end of each selection", () => {
|
||||
const v = make("[ab] c|d [ef]");
|
||||
const before = v.state.selection;
|
||||
expect(swapSelectionBoundaries(v)).toBe(true);
|
||||
const after = v.state.selection;
|
||||
expect(after.ranges.map((r) => [r.anchor, r.head])).toEqual([
|
||||
[2, 0],
|
||||
[4, 4],
|
||||
[8, 6],
|
||||
]);
|
||||
expect(after.mainIndex).toBe(before.mainIndex);
|
||||
expect(show(v)).toBe("[ab] c|d [ef]");
|
||||
swapSelectionBoundaries(v);
|
||||
expect(v.state.selection.eq(before)).toBe(true);
|
||||
});
|
||||
|
||||
it("lets the selection grow from its start after the swap", () => {
|
||||
const v = make("a [bc]d");
|
||||
swapSelectionBoundaries(v);
|
||||
selectCharLeft(v);
|
||||
expect(show(v)).toBe("a[ bc]d");
|
||||
});
|
||||
|
||||
it("swaps a selection that spans lines", () => {
|
||||
const v = make("a[b\nc]d");
|
||||
swapSelectionBoundaries(v);
|
||||
expect(v.state.selection.main.head).toBe(1);
|
||||
expect(v.state.selection.main.anchor).toBe(4);
|
||||
});
|
||||
|
||||
it("does nothing without a selection", () => {
|
||||
const v = make("a|b c|d");
|
||||
expect(swapSelectionBoundaries(v)).toBe(false);
|
||||
expect(show(v)).toBe("a|b c|d");
|
||||
});
|
||||
|
||||
it("swaps in a read-only editor", () => {
|
||||
const v = make("[ab]c", EditorState.readOnly.of(true));
|
||||
expect(swapSelectionBoundaries(v)).toBe(true);
|
||||
expect(v.state.selection.main.head).toBe(0);
|
||||
});
|
||||
|
||||
it("⌥⇧click toggles a caret", () => {
|
||||
const start = EditorSelection.create([EditorSelection.cursor(1), EditorSelection.cursor(5)]);
|
||||
expect(toggleCaret(start, 3, 3).ranges.map((r) => r.head)).toEqual([1, 3, 5]);
|
||||
|
||||
@@ -1124,6 +1124,41 @@ export const addCaretsToLineEnds: Command = (view) => {
|
||||
return true;
|
||||
};
|
||||
|
||||
/** Swap Selection Boundaries: moves each selection's caret to its other end, keeping the selection. */
|
||||
export const swapSelectionBoundaries: Command = (view) => {
|
||||
const { selection } = view.state;
|
||||
if (selection.ranges.every((r) => r.empty)) return false;
|
||||
view.dispatch({
|
||||
selection: EditorSelection.create(
|
||||
selection.ranges.map((r) => EditorSelection.range(r.head, r.anchor)),
|
||||
selection.mainIndex,
|
||||
),
|
||||
scrollIntoView: true,
|
||||
userEvent: "select",
|
||||
});
|
||||
return true;
|
||||
};
|
||||
|
||||
/**
|
||||
* IDEA's Select Line at Caret: each caret or selection grows to the whole lines it touches,
|
||||
* with the line break after them; a folded region's lines go together with the line it is shown on.
|
||||
*/
|
||||
export const selectLineAtCaret: Command = (view) => {
|
||||
const { state } = view;
|
||||
const ranges = state.selection.ranges.map((r) => {
|
||||
const end = r.to > r.from && state.doc.lineAt(r.to).from === r.to ? r.to - 1 : r.to;
|
||||
const span = visualLineSpan(state, r.from, end);
|
||||
const to = Math.min(span.to + 1, state.doc.length);
|
||||
return r.head < r.anchor ? EditorSelection.range(to, span.from) : EditorSelection.range(span.from, to);
|
||||
});
|
||||
view.dispatch({
|
||||
selection: EditorSelection.create(ranges, state.selection.mainIndex),
|
||||
scrollIntoView: true,
|
||||
userEvent: "select",
|
||||
});
|
||||
return true;
|
||||
};
|
||||
|
||||
/** ⌃⇧G: Unselect Occurrence — drops the most recently added selection; a single one collapses to its caret. */
|
||||
export const unselectOccurrence: Command = (view) => {
|
||||
const { state } = view;
|
||||
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
nextOccurrence,
|
||||
occurrenceSearch,
|
||||
selectAllOccurrences,
|
||||
selectLineAtCaret,
|
||||
unselectOccurrence,
|
||||
} from "./editing";
|
||||
import { caretExtension, pasteReindentFilter } from "./prefs";
|
||||
@@ -203,6 +204,12 @@ describe("folded lines", () => {
|
||||
expect(back.state.selection.main).toMatchObject({ anchor: 17, head: 15 });
|
||||
});
|
||||
|
||||
it("Select Line at Caret on a folded region's line selects the whole folded block", () => {
|
||||
const v = folded();
|
||||
selectLineAtCaret(v);
|
||||
expect(v.state.selection.main).toMatchObject({ anchor: 2, head: 15 });
|
||||
});
|
||||
|
||||
it("⌘⌫ on a folded region's line deletes the whole folded block", () => {
|
||||
const v = folded();
|
||||
deleteLine(v);
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
// @vitest-environment jsdom
|
||||
import { afterEach, expect, it } from "vitest";
|
||||
import { EditorState, type Extension } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import type { EditorDocContext } from "@/editor/api";
|
||||
import { breakpointGutter } from "@/features/debugger/editor/breakpointGutter";
|
||||
import { indexedMarkers } from "@/features/plugins/indexedMarkers";
|
||||
import { inlineBlame } from "@/features/vcs/inlineBlame";
|
||||
import { iconAreaExtension } from "./iconArea";
|
||||
|
||||
const ctx: EditorDocContext = { doc: 1, path: "/p/A.java", language: "java", uiMode: null, readOnly: false };
|
||||
const views: EditorView[] = [];
|
||||
afterEach(() => views.splice(0).forEach((v) => v.destroy()));
|
||||
|
||||
function cssRules(): number {
|
||||
let n = 0;
|
||||
for (const sheet of [...document.styleSheets, ...(document.adoptedStyleSheets ?? [])]) n += sheet.cssRules.length;
|
||||
return n;
|
||||
}
|
||||
|
||||
function mount(extensions: Extension): void {
|
||||
const parent = document.createElement("div");
|
||||
document.body.append(parent);
|
||||
views.push(new EditorView({ state: EditorState.create({ doc: "a\nb", extensions }), parent }));
|
||||
}
|
||||
|
||||
// A theme built inside an extension factory mounts new CSS rules for every editor that calls it.
|
||||
// The rules are never removed, and each insertion makes the browser restyle the whole document.
|
||||
it.each([
|
||||
["breakpointGutter", () => breakpointGutter(ctx)],
|
||||
["inlineBlame", () => inlineBlame(ctx)],
|
||||
["indexedMarkers", () => [iconAreaExtension, indexedMarkers(ctx.path)]],
|
||||
])("%s mounts its theme once, however many editors use it", (_name, extensions) => {
|
||||
mount(extensions());
|
||||
const after = cssRules();
|
||||
mount(extensions());
|
||||
mount(extensions());
|
||||
expect(cssRules()).toBe(after);
|
||||
});
|
||||
@@ -24,7 +24,7 @@ import {
|
||||
type DocumentAttachmentOptions,
|
||||
type TextEditorHandle,
|
||||
} from "@/editor/api";
|
||||
import { useDocMeta, type DocAttachmentTarget, type DocumentManager } from "./document";
|
||||
import { restoresVcsText, useDocMeta, type DocAttachmentTarget, type DocumentManager } from "./document";
|
||||
import { saveOnBlur } from "../saveOnBlur";
|
||||
import { editorHistoryKeymap } from "../cm/baseKeymap";
|
||||
|
||||
@@ -205,7 +205,7 @@ export async function attachDocument(
|
||||
if (released || model.closed || target.forwarding) return;
|
||||
for (const tr of u.transactions)
|
||||
if (tr.docChanged && !isExternalChange(tr) && !tr.annotation(transientChange))
|
||||
model.onLocal(tr.changes, target);
|
||||
model.onLocal(tr.changes, target, restoresVcsText(tr));
|
||||
}),
|
||||
],
|
||||
save: (options) => model.save(options?.exact ? "exact" : "explicit"),
|
||||
@@ -223,7 +223,7 @@ export async function attachDocument(
|
||||
const edit = ChangeSet.of(changes, model.sync.localText.length);
|
||||
if (edit.empty) return;
|
||||
target.applyExternal(edit, [Transaction.userEvent.of(userEvent)]);
|
||||
model.onLocal(edit, target);
|
||||
model.onLocal(edit, target, restoresVcsText(userEvent));
|
||||
}
|
||||
},
|
||||
release: () => {
|
||||
|
||||
@@ -520,6 +520,32 @@ describe("DocumentManager + slots", () => {
|
||||
},
|
||||
);
|
||||
|
||||
it("save cleanup keeps what a rollback put back", async () => {
|
||||
const { backend, manager } = setup({ "/p/Posts.php": "<?php\n}\n", "/p/a.txt": "x\n" });
|
||||
try {
|
||||
const php = new EditorSlot(await manager.acquire("/p/Posts.php"), "t1", host);
|
||||
// Reverting an added line break at the end: saving doesn't add it back.
|
||||
php.dispatchLocal({ changes: { from: 7, to: 8 }, userEvent: "revert" });
|
||||
await php.model.save("auto");
|
||||
expect(backend.files.get("/p/Posts.php")).toBe("<?php\n}");
|
||||
await php.model.save("explicit");
|
||||
expect(backend.files.get("/p/Posts.php")).toBe("<?php\n}");
|
||||
// The user's own edit at the end ensures it again.
|
||||
php.dispatchLocal({ changes: { from: 7, insert: " " }, userEvent: "input.type" });
|
||||
await php.model.save("auto");
|
||||
expect(backend.files.get("/p/Posts.php")).toBe("<?php\n}\n");
|
||||
|
||||
// Trailing spaces a rollback restored aren't stripped as an edited line's.
|
||||
const txt = new EditorSlot(await manager.acquire("/p/a.txt"), "t2", host);
|
||||
txt.dispatchLocal({ changes: { from: 0, to: 1, insert: "y" }, userEvent: "input.type" });
|
||||
txt.dispatchLocal({ changes: { from: 0, to: 1, insert: "x " }, userEvent: "input.rollback" });
|
||||
await txt.model.save("auto");
|
||||
expect(backend.files.get("/p/a.txt")).toBe("x \n");
|
||||
} finally {
|
||||
manager.stop();
|
||||
}
|
||||
});
|
||||
|
||||
it("checks dirty state when each queued save starts", async () => {
|
||||
const { backend, manager } = setup({ "/p/query.sql": "SELECT 1" });
|
||||
const model = await manager.acquire("/p/query.sql");
|
||||
|
||||
@@ -195,12 +195,34 @@ export class ModifiedRanges {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* `changes` put back text from the VCS version (a rollback): what they inserted is not an edit
|
||||
* of the user's, so save cleanup leaves it alone; ranges recorded there before are dropped.
|
||||
*/
|
||||
restore(changes: ChangeSet) {
|
||||
if (this.all) return;
|
||||
this.map(changes);
|
||||
const restored: Array<[number, number]> = [];
|
||||
changes.iterChangedRanges((_fa, _ta, fromB, toB) => restored.push([fromB, toB]), true);
|
||||
this.ranges = this.ranges.filter(([a, b]) => !restored.some(([from, to]) => from <= a && b <= to));
|
||||
}
|
||||
|
||||
clear() {
|
||||
this.ranges = [];
|
||||
this.all = false;
|
||||
}
|
||||
}
|
||||
|
||||
/** User events of edits that put back text from the VCS version: a diff's revert arrow, a gutter rollback. */
|
||||
const RESTORE_EVENTS = ["revert", "input.rollback"];
|
||||
|
||||
/** Whether `tr` (or an edit with user event `event`) puts back text from the VCS version. */
|
||||
export function restoresVcsText(tr: Transaction | string): boolean {
|
||||
return typeof tr === "string"
|
||||
? RESTORE_EVENTS.some((e) => tr === e || tr.startsWith(`${e}.`))
|
||||
: RESTORE_EVENTS.some((e) => tr.isUserEvent(e));
|
||||
}
|
||||
|
||||
/** 0-based start lines of functions / methods in an outline (method separators). */
|
||||
export function methodLines(items: readonly OutlineItem[]): number[] {
|
||||
const out: number[] = [];
|
||||
@@ -227,12 +249,14 @@ export function saveCleanupChanges(
|
||||
protectLines: Set<number>;
|
||||
allLines?: boolean;
|
||||
trailingBlankLines?: boolean;
|
||||
/** The end of the text was restored from the VCS version: its blank lines and line break stay. */
|
||||
keepEnd?: boolean;
|
||||
},
|
||||
): Array<{ from: number; to: number; insert?: string }> {
|
||||
const changes: Array<{ from: number; to: number; insert?: string }> = [];
|
||||
const doc = state.doc;
|
||||
let blankFrom = doc.length;
|
||||
if (opts.trailingBlankLines) {
|
||||
if (opts.trailingBlankLines && !opts.keepEnd) {
|
||||
// Keep exactly one line break after the last non-blank line.
|
||||
const m = /\n[ \t\n]*$/.exec(doc.sliceString(Math.max(0, doc.length - 10_000)));
|
||||
if (m && m[0].indexOf("\n", 1) >= 0) blankFrom = doc.length - m[0].length + 1;
|
||||
@@ -255,7 +279,7 @@ export function saveCleanupChanges(
|
||||
}
|
||||
}
|
||||
if (blankFrom < doc.length) changes.push({ from: blankFrom, to: doc.length });
|
||||
else if (opts.finalNewline && doc.length > 0 && doc.sliceString(doc.length - 1) !== "\n")
|
||||
else if (opts.finalNewline && !opts.keepEnd && doc.length > 0 && doc.sliceString(doc.length - 1) !== "\n")
|
||||
changes.push({ from: doc.length, to: doc.length, insert: "\n" });
|
||||
return changes;
|
||||
}
|
||||
@@ -270,6 +294,8 @@ export class DocModel {
|
||||
/** Views outside the tab system sharing this document (e.g. the editable side of a diff). */
|
||||
readonly attachments = new Set<DocAttachmentTarget>();
|
||||
readonly modified = new ModifiedRanges();
|
||||
/** The end of the text was last changed by a rollback to the VCS version (see [`restoresVcsText`]). */
|
||||
private endRestored = false;
|
||||
info: LanguageInfo | undefined;
|
||||
/** Effective `.editorconfig` properties at open time. */
|
||||
editorconfig: EditorConfigProps | null = null;
|
||||
@@ -448,9 +474,16 @@ export class DocModel {
|
||||
return this.slots.values().next().value ?? null;
|
||||
}
|
||||
|
||||
onLocal(changes: ChangeSet, origin: EditorSlot | DocAttachmentTarget) {
|
||||
/** `restored`: the changes put back text from the VCS version ([`restoresVcsText`]). */
|
||||
onLocal(changes: ChangeSet, origin: EditorSlot | DocAttachmentTarget, restored = false) {
|
||||
this.sync.local(changes);
|
||||
this.modified.add(changes);
|
||||
if (restored) this.modified.restore(changes);
|
||||
else this.modified.add(changes);
|
||||
let end = false;
|
||||
changes.iterChangedRanges((_fromA, toA) => {
|
||||
if (toA === changes.length) end = true;
|
||||
});
|
||||
if (end) this.endRestored = restored;
|
||||
this.changeCounter++;
|
||||
for (const s of this.slots)
|
||||
if (s !== origin) s.applyExternal(changes, [mirroredChange.of(true), Transaction.addToHistory.of(false)]);
|
||||
@@ -760,6 +793,7 @@ export class DocModel {
|
||||
protectLines: g.keepTrailingOnCaretLine ? protectLines : new Set(),
|
||||
allLines: g.stripTrailingScope === "all",
|
||||
trailingBlankLines: g.removeTrailingBlankLines,
|
||||
keepEnd: this.endRestored,
|
||||
});
|
||||
if (changes.length) slot.dispatchLocal({ changes, userEvent: "input.save" });
|
||||
}
|
||||
|
||||
@@ -36,7 +36,7 @@ import { baseExtensions, compartments, contributionExtensions } from "../cm/setu
|
||||
import { markdownImageFolds } from "../cm/folding";
|
||||
import { gutterMenuItems, inGutterMenuArea } from "../gutterMenu";
|
||||
import { offerMakeWritable } from "../fileAttributes";
|
||||
import type { DocModel } from "./document";
|
||||
import { restoresVcsText, type DocModel } from "./document";
|
||||
import type { WorkspaceHistoryTarget } from "./workspaceHistory";
|
||||
import { isNavigation } from "./navHistory";
|
||||
|
||||
@@ -326,7 +326,7 @@ export class EditorSlot {
|
||||
navigatedFrom = { line: line.number - 1, col: head - line.from };
|
||||
}
|
||||
if (tr.docChanged && !isExternalChange(tr) && !tr.annotation(transientChange)) {
|
||||
this.model.onLocal(tr.changes, this);
|
||||
this.model.onLocal(tr.changes, this, restoresVcsText(tr));
|
||||
if (
|
||||
tr.isUserEvent("input") ||
|
||||
tr.isUserEvent("delete") ||
|
||||
@@ -351,7 +351,7 @@ export class EditorSlot {
|
||||
}
|
||||
const tr = "startState" in spec ? spec : this.stored.update(spec);
|
||||
this.stored = tr.state;
|
||||
if (tr.docChanged) this.model.onLocal(tr.changes, this);
|
||||
if (tr.docChanged) this.model.onLocal(tr.changes, this, restoresVcsText(tr));
|
||||
if (rewritesIndents(tr)) this.model.redetectIndent();
|
||||
}
|
||||
|
||||
|
||||
@@ -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"]);
|
||||
});
|
||||
});
|
||||
@@ -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);
|
||||
},
|
||||
});
|
||||
@@ -33,6 +33,7 @@ import "./php";
|
||||
import "./go";
|
||||
import "./java";
|
||||
import "./javascript";
|
||||
import "./cpp";
|
||||
|
||||
const semanticBackoff = featureBackoff();
|
||||
|
||||
|
||||
@@ -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([
|
||||
|
||||
@@ -12,6 +12,7 @@ const windowGroupJoin = vi.fn();
|
||||
const windowTakeLaunch = vi.fn();
|
||||
const windowCompleteLaunch = vi.fn();
|
||||
const wslResolve = vi.fn();
|
||||
const windowOpenRemote = vi.fn();
|
||||
const cancelClose = vi.fn();
|
||||
const notify = vi.fn();
|
||||
const listen = vi.fn();
|
||||
@@ -51,6 +52,7 @@ vi.mock("@/platform/ipc", async (orig) => {
|
||||
windowTakeLaunch: () => windowTakeLaunch(),
|
||||
windowCompleteLaunch: () => windowCompleteLaunch(),
|
||||
wslResolve: (p: string) => wslResolve(p),
|
||||
windowOpenRemote: (...a: unknown[]) => windowOpenRemote(...a),
|
||||
lightEditOpen: (p: string) => lightEditOpen(p),
|
||||
fsReadDir: (p: string) => fsReadDir(p),
|
||||
},
|
||||
@@ -266,6 +268,14 @@ describe("a recent project opened with a modifier key", () => {
|
||||
await action.run({ arg: "/p/b" } as never);
|
||||
expect(windowOpenProject).toHaveBeenLastCalledWith("/p/b", false, []);
|
||||
});
|
||||
|
||||
it("opens a Remote Development project from Open Recent on its host (#6124)", async () => {
|
||||
windowOpenRemote.mockResolvedValue(ok({ kind: "focused" }));
|
||||
const action = windowActions().find((a) => a.id === "file.openRecentProject")!;
|
||||
await action.run({ arg: "wsl://Ubuntu/home/me/api" } as never);
|
||||
expect(windowOpenRemote).toHaveBeenCalledWith({ kind: "wsl", distro: "Ubuntu" }, "/home/me/api", false);
|
||||
expect(windowOpenProject).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("loose files (LightEdit)", () => {
|
||||
|
||||
@@ -20,6 +20,7 @@ import {
|
||||
useKeymap,
|
||||
} from "@/platform/keymap";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { syncRemoteRecentMenu } from "@/platform/remote";
|
||||
import { useContributions, useMenuSlotItems, useStandaloneEditor } from "@/workbench/contributions";
|
||||
import { useDistractionFree } from "@/workbench/distractionFree";
|
||||
import { javaFileNameOf, menuLabelParams } from "@/workbench/menuLabels";
|
||||
@@ -258,6 +259,7 @@ export function installMenuBridge(): () => void {
|
||||
.catch(() => {});
|
||||
|
||||
push();
|
||||
syncRemoteRecentMenu();
|
||||
const onFocus = () => {
|
||||
push();
|
||||
pushEnablement(true);
|
||||
|
||||
@@ -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({
|
||||
|
||||
@@ -22,10 +22,10 @@ import {
|
||||
} from "@/platform/project";
|
||||
import { confirmProjectTrust } from "@/platform/projectTrust";
|
||||
import { ask } from "@/workbench/messages";
|
||||
import { connectRemote, isRemoteWindow } from "@/platform/remote";
|
||||
import { connectRemote, isRemoteWindow, parseRemoteLocation } from "@/platform/remote";
|
||||
import { holdSplash } from "@/platform/splash";
|
||||
import { editorService, maybeEditorService, notifications } from "@/workbench/contributions";
|
||||
import { chooseProjectWindow, type ProjectWindowOverride } from "@/workbench/projectWindow";
|
||||
import { chooseProjectWindow, openRemoteProject, type ProjectWindowOverride } from "@/workbench/projectWindow";
|
||||
import { openTabColorPicker } from "@/workbench/TabColorPicker";
|
||||
import { cycleWindowTab, useWindowGroup } from "@/platform/windowGroups";
|
||||
import { editorSwitching } from "@/editor/api";
|
||||
@@ -606,7 +606,15 @@ export function windowActions(): Action[] {
|
||||
hidden: true,
|
||||
run: async (c) => {
|
||||
const recent = recentProjectArg(c.arg);
|
||||
if (recent) await openProjectWithPolicy(recent.path, [], recent.window);
|
||||
if (!recent) return;
|
||||
// Open Recent lists Remote Development projects by their location (`ssh://host/path`).
|
||||
const remote = parseRemoteLocation(recent.path);
|
||||
if (!remote) return openProjectWithPolicy(recent.path, [], recent.window);
|
||||
try {
|
||||
await openRemoteProject(remote.target, remote.path, undefined, recent.window);
|
||||
} catch (e) {
|
||||
openFailed(remote.path, e);
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
|
||||
@@ -324,6 +324,28 @@ it("attaches a module directory without a build file outside the project, after
|
||||
expect(mocks.link).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("doesn't offer to attach a folder where another root can't be attached (a remote window)", async () => {
|
||||
const attached = vi.fn();
|
||||
const off = registerAction({
|
||||
id: "project.attachFolder",
|
||||
title: "Attach",
|
||||
when: "projectLocal",
|
||||
run: ({ arg }) => attached(arg),
|
||||
});
|
||||
setContext("projectLocal", false);
|
||||
mocks.open.mockResolvedValue("/code/B");
|
||||
mocks.readDir.mockResolvedValue([fileEntry("/code/B", "Main.java")]);
|
||||
await act(async () => {
|
||||
await executeAction("maven.importExternal");
|
||||
});
|
||||
off();
|
||||
expect(mocks.confirm).not.toHaveBeenCalled();
|
||||
expect(attached).not.toHaveBeenCalled();
|
||||
expect(mocks.notify).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ level: "warning", title: "Module was not imported", key: "module-import-no-attach" }),
|
||||
);
|
||||
});
|
||||
|
||||
it("says a module directory without a build file inside the project is already part of it", async () => {
|
||||
mocks.open.mockResolvedValue("/p/lib");
|
||||
mocks.readDir.mockResolvedValue([]);
|
||||
|
||||
@@ -9,7 +9,7 @@ import { confirm } from "@/workbench/messages";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { create } from "zustand";
|
||||
import { Channel } from "@tauri-apps/api/core";
|
||||
import { executeAction } from "@/platform/actions";
|
||||
import { executeAction, getAction, isActionEnabled } from "@/platform/actions";
|
||||
import { choosePath, choosePaths } from "@/platform/choosePath";
|
||||
import {
|
||||
call,
|
||||
@@ -535,6 +535,18 @@ export async function importModuleFromExistingSources() {
|
||||
});
|
||||
return;
|
||||
}
|
||||
const attach = getAction("project.attachFolder");
|
||||
if (!attach || !isActionEnabled(attach)) {
|
||||
// Another root can't be attached here (a remote window): say so instead of offering it.
|
||||
notifications().notify({
|
||||
group: "tools",
|
||||
level: "warning",
|
||||
title: tx`Module was not imported`,
|
||||
body: tx`${name} has no pom.xml or Gradle build file, and a folder outside the project can't be attached as another root in this window. Move it into the project folder, or add a pom.xml or Gradle build file to it.`,
|
||||
key: "module-import-no-attach",
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (
|
||||
await confirm({
|
||||
title: tx`Import Module from Existing Sources`,
|
||||
|
||||
@@ -13,12 +13,23 @@ import {
|
||||
registerToolWindow,
|
||||
} from "@/workbench/contributions";
|
||||
import { getContext } from "@/platform/context";
|
||||
import { formatMessage, tx } from "@/platform/i18n";
|
||||
import { basename } from "@/platform/project";
|
||||
import { showContextMenu } from "@/ui/Menu";
|
||||
import { clearProblems, installProblemsEvents, problemsReport, useProblems } from "./problemsStore";
|
||||
import { installProblemDecorations } from "./decorations";
|
||||
import { ProblemsTabs, ProblemsView, useProblemsHeaderMenu } from "./ProblemsView";
|
||||
import { UsagesTabs, UsagesView, useUsagesHeaderMenu } from "./UsagesView";
|
||||
import { UsagesPopup } from "./UsagesPopup";
|
||||
import { findUsages, rerunActiveUsages, resetUsages, showUsageResults, showUsagesPopup } from "./usages";
|
||||
import {
|
||||
findUsages,
|
||||
recentUsageSearches,
|
||||
rerunActiveUsages,
|
||||
rerunRecentUsages,
|
||||
resetUsages,
|
||||
showUsageResults,
|
||||
showUsagesPopup,
|
||||
} from "./usages";
|
||||
import { HierarchyTabs, HierarchyView } from "./HierarchyView";
|
||||
import { resetHierarchy, showHierarchy } from "./hierarchy";
|
||||
import { installServerEvents, linterCovers } from "./servers";
|
||||
@@ -28,6 +39,17 @@ import { installWorkspaceEditUndo } from "./workspaceUndo";
|
||||
|
||||
const EDITOR_WHEN = "textEditorActive && (editorFocus || !toolWindowFocus)";
|
||||
|
||||
/** Recent Find Usages: IDEA's list of the last searches; the chosen one runs again in the tool window. */
|
||||
function showRecentUsages() {
|
||||
const items = recentUsageSearches().map((search) => ({
|
||||
label: search.symbol ? formatMessage(tx("Usages of '{symbol}'"), { symbol: search.symbol }) : tx("Usages"),
|
||||
verbatim: true,
|
||||
shortcut: `${basename(search.path)}:${search.line + 1}`,
|
||||
run: () => void rerunRecentUsages(search),
|
||||
}));
|
||||
showContextMenu("center", items, { title: "Recent Find Usages" });
|
||||
}
|
||||
|
||||
function useErrorBadge(): number | null {
|
||||
return useProblems((s) => s.counts.error || null);
|
||||
}
|
||||
@@ -127,6 +149,14 @@ export function activate(): () => void {
|
||||
when: EDITOR_WHEN,
|
||||
run: () => showUsagesPopup(),
|
||||
},
|
||||
{
|
||||
id: "find.recentUsages",
|
||||
title: "Recent Find Usages",
|
||||
category: "Find",
|
||||
when: "projectOpen",
|
||||
enabled: () => recentUsageSearches().length > 0,
|
||||
run: showRecentUsages,
|
||||
},
|
||||
{
|
||||
// ⌘R in the Find Usages tool window, as in IDEA.
|
||||
id: "usages.rerun",
|
||||
|
||||
@@ -0,0 +1,200 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const show = vi.fn();
|
||||
const hide = vi.fn();
|
||||
vi.mock("@/workbench/contributions", async (orig) => ({
|
||||
...(await orig<typeof import("@/workbench/contributions")>()),
|
||||
toolWindowService: () => ({ show, hide }),
|
||||
}));
|
||||
const lspReferences = vi.fn(async (..._args: unknown[]) => ({ status: "ok", data: null }));
|
||||
vi.mock("@/platform/ipc", async (orig) => {
|
||||
const actual = await orig<typeof import("@/platform/ipc")>();
|
||||
return { ...actual, commands: { ...actual.commands, lspReferences } };
|
||||
});
|
||||
/** The caret Find Usages starts from (`null`: no editor). */
|
||||
let caret: { doc: number; path: string; line: number; col: number; word: string | null } | null = null;
|
||||
/** Documents `withDocument` opened and closed, by path; a missing path fails to open. */
|
||||
const opened: string[] = [];
|
||||
const closed: number[] = [];
|
||||
const reportError = vi.fn();
|
||||
vi.mock("./ipc", async (orig) => ({
|
||||
...(await orig<typeof import("./ipc")>()),
|
||||
caretContext: () => (caret ? { ...caret, view: null } : null),
|
||||
lspRequest: async (request: () => unknown) => {
|
||||
request();
|
||||
return { locations: [], incomplete: null };
|
||||
},
|
||||
readManyFileLines: async () => new Map(),
|
||||
withDocument: async (path: string, fn: (doc: number) => Promise<unknown>) => {
|
||||
if (path.includes("missing")) throw new Error(`Cannot open ${path}`);
|
||||
opened.push(path);
|
||||
const doc = 100 + opened.length;
|
||||
try {
|
||||
return await fn(doc);
|
||||
} finally {
|
||||
closed.push(doc);
|
||||
}
|
||||
},
|
||||
reportError,
|
||||
}));
|
||||
|
||||
vi.mock("@tauri-apps/api/core", async (orig) => ({
|
||||
...(await orig<object>()),
|
||||
Channel: class {
|
||||
onmessage = () => {};
|
||||
},
|
||||
}));
|
||||
|
||||
const { executeAction, getAction } = await import("@/platform/actions");
|
||||
const { setContext } = await import("@/platform/context");
|
||||
const { useContextMenuStore } = await import("@/ui/Menu");
|
||||
const { activate } = await import("./index");
|
||||
const { activeUsageSearch, closeUsageTab, findUsages, recentUsageSearches, resetUsages, useUsages } =
|
||||
await import("./usages");
|
||||
|
||||
const at = (path: string, line: number, col: number, word: string | null, doc = 1) => {
|
||||
caret = { doc, path, line, col, word };
|
||||
};
|
||||
/** The (doc, line, col) of the last references request. */
|
||||
const lastRequest = () => {
|
||||
const [, doc, pos, , , libraries] = lspReferences.mock.lastCall!;
|
||||
return { doc, pos, libraries };
|
||||
};
|
||||
|
||||
describe("Recent Find Usages", () => {
|
||||
beforeEach(() => {
|
||||
resetUsages();
|
||||
lspReferences.mockClear();
|
||||
opened.length = 0;
|
||||
closed.length = 0;
|
||||
reportError.mockClear();
|
||||
useContextMenuStore.setState({ menu: null });
|
||||
});
|
||||
|
||||
it("remembers searches newest first, once per position, up to ten", async () => {
|
||||
at("/p/a.rs", 1, 4, "foo");
|
||||
await findUsages();
|
||||
at("/p/b.rs", 2, 0, "bar");
|
||||
await findUsages();
|
||||
at("/p/a.rs", 1, 4, "foo");
|
||||
await findUsages();
|
||||
expect(recentUsageSearches().map((r) => r.symbol)).toEqual(["foo", "bar"]);
|
||||
|
||||
// Same name elsewhere is another search.
|
||||
at("/p/c.rs", 7, 2, "foo");
|
||||
await findUsages();
|
||||
expect(recentUsageSearches().map((r) => r.path)).toEqual(["/p/c.rs", "/p/a.rs", "/p/b.rs"]);
|
||||
|
||||
for (let line = 10; line < 20; line++) {
|
||||
at("/p/d.rs", line, 0, `s${line}`);
|
||||
// oxlint-disable-next-line no-await-in-loop -- searches run one after another, like the user's
|
||||
await findUsages();
|
||||
}
|
||||
expect(recentUsageSearches()).toHaveLength(10);
|
||||
expect(recentUsageSearches()[0]!.symbol).toBe("s19");
|
||||
expect(recentUsageSearches().at(-1)!.symbol).toBe("s10");
|
||||
});
|
||||
|
||||
it("keeps a search after its tab is closed and forgets it on a project switch", async () => {
|
||||
at("/p/a.rs", 1, 4, "foo");
|
||||
await findUsages();
|
||||
closeUsageTab(activeUsageSearch(useUsages.getState())!.id);
|
||||
expect(useUsages.getState().tabs).toHaveLength(0);
|
||||
expect(recentUsageSearches().map((r) => r.symbol)).toEqual(["foo"]);
|
||||
resetUsages();
|
||||
expect(recentUsageSearches()).toEqual([]);
|
||||
});
|
||||
|
||||
it("does not remember a search that never started", async () => {
|
||||
caret = null;
|
||||
await findUsages();
|
||||
expect(recentUsageSearches()).toEqual([]);
|
||||
});
|
||||
|
||||
describe("action", () => {
|
||||
let dispose: () => void;
|
||||
beforeEach(() => {
|
||||
setContext("projectOpen", true);
|
||||
dispose = activate();
|
||||
return () => dispose();
|
||||
});
|
||||
|
||||
it("is disabled until something was searched", async () => {
|
||||
const action = getAction("find.recentUsages")!;
|
||||
expect(action.title).toBe("Recent Find Usages");
|
||||
expect(action.enabled?.({ arg: undefined } as never)).toBe(false);
|
||||
expect(await executeAction("find.recentUsages")).toBe(false);
|
||||
expect(useContextMenuStore.getState().menu).toBeNull();
|
||||
});
|
||||
|
||||
it("lists the searches and runs the chosen one again, in the file's current document", async () => {
|
||||
at("/p/a.rs", 1, 4, "foo", 7);
|
||||
await findUsages();
|
||||
at("/p/b.rs", 2, 0, "bar", 8);
|
||||
await findUsages();
|
||||
closeUsageTab(activeUsageSearch(useUsages.getState())!.id);
|
||||
|
||||
expect(await executeAction("find.recentUsages")).toBe(true);
|
||||
const menu = useContextMenuStore.getState().menu!;
|
||||
expect(menu.title).toBe("Recent Find Usages");
|
||||
const items = menu.items.filter((i) => i.kind !== "header") as {
|
||||
label: string;
|
||||
shortcut?: string;
|
||||
run(): void;
|
||||
}[];
|
||||
expect(items.map((i) => [i.label, i.shortcut])).toEqual([
|
||||
["Usages of 'bar'", "b.rs:3"],
|
||||
["Usages of 'foo'", "a.rs:2"],
|
||||
]);
|
||||
|
||||
// The editor that searched `foo` may be gone: it asks in a document opened for it.
|
||||
lspReferences.mockClear();
|
||||
items[1]!.run();
|
||||
await vi.waitFor(() => expect(activeUsageSearch(useUsages.getState())?.loading).toBe(false));
|
||||
expect(opened).toEqual(["/p/a.rs"]);
|
||||
expect(lastRequest()).toEqual({ doc: 101, pos: { line: 1, col: 4 }, libraries: false });
|
||||
expect(activeUsageSearch(useUsages.getState())!.symbol).toBe("foo");
|
||||
expect(show).toHaveBeenCalledWith("usages");
|
||||
// Run again, it is the newest.
|
||||
expect(recentUsageSearches().map((r) => r.symbol)).toEqual(["foo", "bar"]);
|
||||
// That document closed with the search: the tab's Rerun opens it again.
|
||||
expect(closed).toEqual([101]);
|
||||
activeUsageSearch(useUsages.getState())!.rerun!();
|
||||
await vi.waitFor(() => expect(closed).toEqual([101, 102]));
|
||||
expect(lastRequest()).toEqual({ doc: 102, pos: { line: 1, col: 4 }, libraries: false });
|
||||
});
|
||||
|
||||
it("keeps the scope a search was widened to", async () => {
|
||||
at("/p/a.rs", 1, 4, "foo");
|
||||
await findUsages();
|
||||
activeUsageSearch(useUsages.getState())!.searchLibraries!();
|
||||
await vi.waitFor(() => expect(lastRequest().libraries).toBe(true));
|
||||
await vi.waitFor(() => expect(activeUsageSearch(useUsages.getState())!.loading).toBe(false));
|
||||
expect(recentUsageSearches()).toHaveLength(1);
|
||||
|
||||
await executeAction("find.recentUsages");
|
||||
const item = useContextMenuStore.getState().menu!.items.find((i) => i.kind !== "header") as { run(): void };
|
||||
lspReferences.mockClear();
|
||||
item.run();
|
||||
await vi.waitFor(() => expect(lspReferences).toHaveBeenCalled());
|
||||
expect(lastRequest().libraries).toBe(true);
|
||||
});
|
||||
|
||||
it("reports a file that can no longer be opened", async () => {
|
||||
at("/p/missing.rs", 0, 0, "gone");
|
||||
await findUsages();
|
||||
await executeAction("find.recentUsages");
|
||||
const item = useContextMenuStore.getState().menu!.items.find((i) => i.kind !== "header") as { run(): void };
|
||||
lspReferences.mockClear();
|
||||
item.run();
|
||||
await vi.waitFor(() => expect(reportError).toHaveBeenCalledOnce());
|
||||
expect(String(reportError.mock.lastCall![0])).toContain("Cannot open /p/missing.rs");
|
||||
expect(lspReferences).not.toHaveBeenCalled();
|
||||
expect(activeUsageSearch(useUsages.getState())).toMatchObject({
|
||||
symbol: "gone",
|
||||
loading: false,
|
||||
error: "Cannot open /p/missing.rs",
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -2,6 +2,7 @@
|
||||
import { create } from "zustand";
|
||||
import { Channel } from "@tauri-apps/api/core";
|
||||
import type { ClassifiedReference, ReferenceAccess, ReferenceKind, Location, References, RequestId } from "@/bindings";
|
||||
import { editorsFor } from "@/editor/api";
|
||||
import { clearLineTokens } from "@/editor/lineTokens";
|
||||
import { showPendingHint } from "@/editor/lsp/hint";
|
||||
import { incompleteNote } from "@/editor/lsp/lsp";
|
||||
@@ -18,6 +19,7 @@ import {
|
||||
openLocation,
|
||||
readManyFileLines,
|
||||
reportError,
|
||||
withDocument,
|
||||
type CaretContext,
|
||||
} from "./ipc";
|
||||
import { syntaxUsages } from "./syntaxUsages";
|
||||
@@ -299,6 +301,7 @@ export function resetUsages() {
|
||||
if (popupRequest !== null) void commands.cancelRequest(popupRequest).catch(() => {});
|
||||
popupRequest = null;
|
||||
useUsages.setState({ tabs: [], active: null });
|
||||
recentSearches = [];
|
||||
useUsagesPopup.setState({ open: false, symbol: null, groups: [], note: null, loading: false, scope: null });
|
||||
popupTarget = null;
|
||||
}
|
||||
@@ -309,8 +312,56 @@ export async function findUsages() {
|
||||
hint("Open a file to find usages");
|
||||
return;
|
||||
}
|
||||
await searchUsages(c, (fetch) => fetch(c), false, false);
|
||||
}
|
||||
|
||||
/** A past Find Usages search, run again by Recent Find Usages. */
|
||||
export interface RecentUsageSearch {
|
||||
path: string;
|
||||
line: number;
|
||||
col: number;
|
||||
symbol: string | null;
|
||||
libraries: boolean;
|
||||
widenable: boolean;
|
||||
}
|
||||
|
||||
const MAX_RECENT = 10;
|
||||
let recentSearches: RecentUsageSearch[] = [];
|
||||
|
||||
/** Recent Find Usages: the last searches, newest first, one per caret position. */
|
||||
export const recentUsageSearches = (): readonly RecentUsageSearch[] => recentSearches;
|
||||
|
||||
/** Runs `search` again in a new tab, in its file's document whether or not an editor still has it open. */
|
||||
export async function rerunRecentUsages(search: RecentUsageSearch) {
|
||||
const { path, line, col, symbol, libraries, widenable } = search;
|
||||
await searchUsages(
|
||||
{ path, line, col, word: symbol },
|
||||
(fetch) =>
|
||||
withDocument(path, (doc) =>
|
||||
fetch({ doc, path, line, col, word: symbol, view: editorsFor(path)[0]?.view ?? null }),
|
||||
),
|
||||
libraries,
|
||||
widenable,
|
||||
);
|
||||
}
|
||||
|
||||
/** Runs `fetch` with the caret of a search: the editor's, or one in a document opened for each run. */
|
||||
type InDocument = <T>(fetch: (c: CaretContext) => Promise<T>) => Promise<T>;
|
||||
|
||||
/** Searches the usages at `c` into the tool window. */
|
||||
async function searchUsages(
|
||||
c: Pick<CaretContext, "path" | "line" | "col" | "word">,
|
||||
inDocument: InDocument,
|
||||
libraries: boolean,
|
||||
widenable: boolean,
|
||||
) {
|
||||
const here = (r: RecentUsageSearch) => r.path === c.path && r.line === c.line && r.col === c.col;
|
||||
// `widenable`: an earlier run of this search skipped the libraries.
|
||||
const run = async (prev: number | null, libraries: boolean, widenable: boolean) => {
|
||||
recentSearches = [
|
||||
{ path: c.path, line: c.line, col: c.col, symbol: c.word, libraries, widenable },
|
||||
...recentSearches.filter((r) => !here(r)),
|
||||
].slice(0, MAX_RECENT);
|
||||
const id = ++searchSeq;
|
||||
const base = {
|
||||
id,
|
||||
@@ -325,13 +376,16 @@ export async function findUsages() {
|
||||
const request = nextRequestId();
|
||||
inflight.set(id, request);
|
||||
try {
|
||||
const { groups, note, librariesSkipped } = await fetchUsages(
|
||||
c,
|
||||
request,
|
||||
(found) => {
|
||||
if (inflight.get(id) === request) replaceUsageTab(id, { ...loading, groups: found.groups, note: found.note });
|
||||
},
|
||||
libraries,
|
||||
const { groups, note, librariesSkipped } = await inDocument((caret) =>
|
||||
fetchUsages(
|
||||
caret,
|
||||
request,
|
||||
(found) => {
|
||||
if (inflight.get(id) === request)
|
||||
replaceUsageTab(id, { ...loading, groups: found.groups, note: found.note });
|
||||
},
|
||||
libraries,
|
||||
),
|
||||
);
|
||||
const scope = searchedScope(libraries, librariesSkipped, widenable);
|
||||
replaceUsageTab(id, { ...base, loading: false, groups, error: null, note, scope });
|
||||
@@ -345,7 +399,7 @@ export async function findUsages() {
|
||||
if (inflight.get(id) === request) inflight.delete(id);
|
||||
}
|
||||
};
|
||||
await run(null, false, false);
|
||||
await run(null, libraries, widenable);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
Loaded 100 of 190 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Заблокувати користувача