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

..
Автор SHA1 Повідомлення Дата
l0ng-ai 887b2f52dd fix(vim): keep shadowed leader built-ins across rc reloads
Unmapping a built-in shrank codemirror-vim's default keymap, which mapclear
and noremap split from user mappings by count, so a built-in shadowed by one
rc (e.g. comma after a comma leader) was dropped for good once a later rc
stopped using it. Swap the built-in for a stand-in in the default keymap
once and switch its keys on later reloads instead.
2026-11-09 20:59:03 +08:00
l0ng-ai 53f837b704 test(e2e): reach the end of the diff with Meta+End
Meta+ArrowDown now jumps to source in the diff viewer, so the scattered
edits test never left the first difference.
2026-11-09 20:53:05 +08:00
l0ng-ai 7c80b68787 fix(vim): only shadow leader keys, not operators a mapping starts with (#2360) 2026-11-09 20:50:59 +08:00
Shohruh Ismoilov 44d871caee fix(deps): bundle patched SQLite for RUSTSEC-2026-0459 (#2351)
Update libsqlite3-sys to 0.39.1 (SQLite 3.54.1), which needs SQLx at its unreleased rev 10462fa: SQLx 0.9.0 on crates.io caps libsqlite3-sys below 0.38. The rev also brings the 48 other commits on SQLx's main since 0.9.0. Cargo deny allows this one Git source and requires revision pins.
2026-11-09 20:30:07 +08:00
arookieofc 89f96edc07 fix(vim): let mapleader shadow built-in keys like <Space> and , (#2337) (#2355)
* fix(vim): let mapleader shadow built-in keys like <Space> and , (#2337)

codemirror-vim prefers a full match over a partial one, so a user mapping
that starts with <Space> or , never fires: the built-in <Space>->l and
,->repeatLastCharacterSearch commands run first and clear the key buffer.

While an rc mapping begins with a key a built-in uses, unmap the built-in;
restore it on the next applyRcCommands pass so mapclear()'s user/default
boundary stays honest (Vim.unmap does not update defaultKeymapLength).

* fix(vim): pass the context arg Vim.unmap's typings require (#2337)
2026-11-09 20:27:38 +08:00
l0ng-ai fd79a5c55e fix(editor): keep the page from scrolling with the editor (#2356)
CodeMirror's tooltip container in `body` carries the editor's theme classes,
so the themes' `height: 100%` gave it a full window of height. Scrolling to a
position the editor had already reached then moved the page itself, leaving
the title bar cut off and an empty band at the bottom.

Set the height on `.cm-editor` only, and clip the body so nothing outside
`#root` can make the page scrollable.
2026-11-09 20:22:12 +08:00
arookieofc bb8c9fa0b4 fix(vcs): remember the diff window's size between openings (#2328) (#2353)
The modal-commit diff dialog always reopened at its default 1100x720.
Pass the persisted size as the dialog's initialSize and save it when a
resize ends, like the Find in Files popup already does.
2026-11-09 20:14:28 +08:00
ntbang0901таNguyenBang 039ec09122 feat(vcs): pick each repository's remote and target branch in the multi-repository Push dialog (#2342)
Co-authored-by: NguyenBang <[email protected]>
2026-11-09 20:10:09 +08:00
ntbang0901таNguyenBang d02aae2280 feat(keymap): bind ⌘↓ to Jump to Source in the diff viewer on macOS (#2341)
IDEA's Diff.OpenInEditor copies EditSource's shortcuts, which the Mac OS X 10.5+ keymap binds to F4 and ⌘↓. The IntelliJ (macOS) preset only had F4 for diff.jumpToSource, which macOS often takes for itself. The binding is scoped by diffEditorFocus, so ⌘↓ still moves to the document end in other editors.

Closes #2292

Co-authored-by: NguyenBang <[email protected]>
2026-11-09 20:08:01 +08:00
NealimeKennaтаNealimeKenna e44a3af310 fix(agents): attach pasted clipboard images on Linux (#2336)
WebKitGTK hands the composer an empty clipboardData when the clipboard
holds only an image, as after a GNOME screenshot, and refuses
navigator.clipboard.read(). Ctrl+V then attached nothing. A paste that
carries no data now reads the image through the GTK clipboard with the
new clipboard_image command.

Co-authored-by: NealimeKenna <[email protected]>
2026-11-09 19:59:30 +08:00
l0ng-ai ff2eb95b01 fix(lsp): respect Dart's own filesystem watcher (#2350) 2026-11-09 19:58:10 +08:00
l0ng-ai b2b881e075 fix(debug): wait for Windows debuggee trees to exit (#2349) 2026-11-09 19:58:00 +08:00
l0ng-ai 90d32f7883 fix(lsp): wait through planned server restarts (#2348) 2026-11-09 19:57:51 +08:00
arookieofc f72e3a9a8a fix(fonts): prefer installed JetBrains Mono/Inter over bundled variable webfonts (#2311)
* fix(fonts): prefer installed JetBrains Mono/Inter over bundled variable webfonts

When the user has JetBrains Mono or Inter installed, the system outline
fonts carry TrueType hinting bytecode that the bundled fontsource variable
webfonts lack, so the installed face renders crisper at editor sizes and
matches IntelliJ IDEA. Keep the variable faces as fallbacks so machines
without a system install keep rendering (#26).

Fixes #2305

* test(e2e): expect installed Inter before bundled Inter Variable (#2305)

* test(e2e): match computed-style serialization in the Inter font assertion (#2305)

* chore: trigger CI (no runs created for 950cb4b4)
2026-11-09 19:43:48 +08:00
l0ng-ai 1ae8572021 fix(project): keep attachments in the current project (#2320)
Attach adds a trusted folder to the current project without reopening it or moving its root. Attachments live in the primary project's private .openidea/workspace.json, and detaching the last one restores a plain project.

ProjectInfo.name stays the primary project's name; displayName supplies window titles, project tabs and Recent Projects. Attach is no longer a remembered opening policy, and File > Attach Project is available when the policy is not Ask. Attached folders must be trusted, and Restricted Mode names any attached folder that blocks trust. Explicit workspaces keep their behaviour and still cannot be created in or inside a linked project.
2026-11-09 19:23:05 +08:00
l0ng-ai 023c3f36c2 feat(app): check for updates while the IDE stays open (#2329)
* feat(app): check for updates periodically

* test(app): cover update commands in Restricted Mode
2026-11-09 19:13:47 +08:00
l0ng-ai 88a1e4161e Update README.md 2026-11-09 18:44:37 +08:00
l0ng-ai 0b1f723b9a fix(build): link missing tool and JDK errors to recovery (#2335) 2026-11-09 18:15:24 +08:00
l0ng-ai e2f22de824 fix(tools): install with the selected project SDK (#2334) 2026-11-09 18:13:57 +08:00
arookieofc 24d3173a55 fix(editor): parent CodeMirror tooltips to the body so panels can't cover them (#2310) (#2327) 2026-11-09 18:12:18 +08:00
l0ng-ai 799391b301 fix(debugger): report obsolete methods as a completed hot swap (#2330) 2026-11-09 18:07:12 +08:00
130 змінених файлів з 3535 додано та 503 видалено

No files matched your search

Створено
+28 -20
Переглянути файл
@@ -1522,7 +1522,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d045de693cb712d0b22c6a64be5b953f67b3ce00ab5ad3dd5d8b441886ab8e1a"
dependencies = [
"quote",
"syn 3.0.9",
"syn 2.0.119",
]
[[package]]
@@ -5582,9 +5582,9 @@ dependencies = [
[[package]]
name = "libsqlite3-sys"
version = "0.37.0"
version = "0.39.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b1f111c8c41e7c61a49cd34e44c7619462967221a6443b0ec299e0ac30cfb9b1"
checksum = "14a5f01b87b92705d07b433c06f96cbc764637d81a0bffb5734ce17cf0f9a2b3"
dependencies = [
"cc",
"pkg-config",
@@ -6364,6 +6364,15 @@ dependencies = [
"objc2-foundation 0.2.2",
]
[[package]]
name = "objc2-system-configuration"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7216bd11cbda54ccabcab84d523dc93b858ec75ecfb3a7d89513fa22464da396"
dependencies = [
"objc2-core-foundation",
]
[[package]]
name = "objc2-ui-kit"
version = "0.2.2"
@@ -8630,8 +8639,7 @@ checksum = "3a0219bd7d979d58245a4f41f695e1ac9f8befdffadd7f61f1bae9e39abc6620"
[[package]]
name = "sqlx"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "378620ccc25c62c89d8be1c819e76a88d59bdcc3304733330788948e619bfd71"
source = "git+https://github.com/transact-rs/sqlx?rev=10462fa4414c6c7f1ed1d39bb31678e3b726878c#10462fa4414c6c7f1ed1d39bb31678e3b726878c"
dependencies = [
"sqlx-core",
"sqlx-macros",
@@ -8643,8 +8651,7 @@ dependencies = [
[[package]]
name = "sqlx-core"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "05b44e85bf579a8eeb4ceaa77a3a523baf2bf0e9bac7e40f405d537b5d2d5ccb"
source = "git+https://github.com/transact-rs/sqlx?rev=10462fa4414c6c7f1ed1d39bb31678e3b726878c#10462fa4414c6c7f1ed1d39bb31678e3b726878c"
dependencies = [
"base64 0.22.1",
"bytes",
@@ -8666,7 +8673,7 @@ dependencies = [
"rustls",
"serde",
"serde_json",
"sha2 0.10.9",
"sha2 0.11.1",
"smallvec",
"thiserror 2.0.21",
"tokio",
@@ -8679,8 +8686,7 @@ dependencies = [
[[package]]
name = "sqlx-macros"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bd2b84f2bc39a5705ef27ec785a11c934a41bbd4a24941e257927cddc26b60bf"
source = "git+https://github.com/transact-rs/sqlx?rev=10462fa4414c6c7f1ed1d39bb31678e3b726878c#10462fa4414c6c7f1ed1d39bb31678e3b726878c"
dependencies = [
"proc-macro2",
"quote",
@@ -8692,8 +8698,7 @@ dependencies = [
[[package]]
name = "sqlx-macros-core"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fb8d96de5fdc85a5c4ec813432b523ec637e80ba98f046555f75f7908ddac7c3"
source = "git+https://github.com/transact-rs/sqlx?rev=10462fa4414c6c7f1ed1d39bb31678e3b726878c#10462fa4414c6c7f1ed1d39bb31678e3b726878c"
dependencies = [
"cfg-if",
"dotenvy",
@@ -8704,7 +8709,7 @@ dependencies = [
"quote",
"serde",
"serde_json",
"sha2 0.10.9",
"sha2 0.11.1",
"sqlx-core",
"sqlx-mysql",
"sqlx-postgres",
@@ -8717,8 +8722,7 @@ dependencies = [
[[package]]
name = "sqlx-mysql"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "90b8020fe17c5f2c245bfa2505d7ef59c5604839527c740266ad2214acebea27"
source = "git+https://github.com/transact-rs/sqlx?rev=10462fa4414c6c7f1ed1d39bb31678e3b726878c#10462fa4414c6c7f1ed1d39bb31678e3b726878c"
dependencies = [
"bitflags 2.13.2",
"byteorder",
@@ -8743,8 +8747,7 @@ dependencies = [
[[package]]
name = "sqlx-postgres"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "87a2bdd6e83f6b3ea525ca9fee568030508b58355a43d0b2c1674d5f79dcd65e"
source = "git+https://github.com/transact-rs/sqlx?rev=10462fa4414c6c7f1ed1d39bb31678e3b726878c#10462fa4414c6c7f1ed1d39bb31678e3b726878c"
dependencies = [
"atoi",
"base64 0.22.1",
@@ -8778,8 +8781,7 @@ dependencies = [
[[package]]
name = "sqlx-sqlite"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "488e99c397a62007e4229aec669a179816339afc6d2620ca6fa420dbee2e982c"
source = "git+https://github.com/transact-rs/sqlx?rev=10462fa4414c6c7f1ed1d39bb31678e3b726878c#10462fa4414c6c7f1ed1d39bb31678e3b726878c"
dependencies = [
"atoi",
"flume",
@@ -9544,7 +9546,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
dependencies = [
"fastrand",
"getrandom 0.4.3",
"getrandom 0.3.4",
"once_cell",
"rustix",
"windows-sys 0.61.2",
@@ -11310,6 +11312,12 @@ name = "whoami"
version = "2.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "626c4bac6755d76ffc12cb01b2eac751db1996b9e0041de9aa02c8c211ddc82c"
dependencies = [
"libc",
"libredox",
"objc2-system-configuration",
"web-sys",
]
[[package]]
name = "win_uds"
+2 -1
Переглянути файл
@@ -103,7 +103,8 @@ portable-pty = "0.9"
reqwest = { version = "0.13", default-features = false, features = ["rustls-no-provider", "http2", "charset", "socks", "gzip", "deflate", "brotli"] }
rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12", "logging"] }
rustls-platform-verifier = "0.7"
sqlx = { version = "0.9", default-features = false, features = ["runtime-tokio", "tls-rustls-ring-webpki", "sqlite", "postgres", "mysql"] }
# Until SQLx releases its libsqlite3-sys 0.39 update (RUSTSEC-2026-0459).
sqlx = { version = "0.9", git = "https://github.com/transact-rs/sqlx", rev = "10462fa4414c6c7f1ed1d39bb31678e3b726878c", default-features = false, features = ["runtime-tokio", "tls-rustls-ring-webpki", "sqlite", "postgres", "mysql"] }
tiberius = { version = "0.13", default-features = false, features = ["tds73", "rustls", "sql-browser-tokio"] }
oracle = { version = "0.6", default-features = false }
bb8 = "0.9"
+1 -1
Переглянути файл
@@ -69,7 +69,7 @@ the [official plugins](plugins/official). The plugin API is still a preview.
### Contributors
<a href="https://github.com/l0ng-ai/openidea/graphs/contributors">
<img src="https://contrib.rocks/image?repo=l0ng-ai/openidea&max=100" alt="OpenIDEA contributors">
<img src="https://contrib.rocks/image?repo=l0ng-ai/openidea&max=500" alt="OpenIDEA contributors">
</a>
## License
+6
Переглянути файл
@@ -148,6 +148,12 @@ pub enum IdeEvent {
SettingsChanged {
key: String,
},
UpdateStatusChanged {
status: crate::updates::UpdateStatus,
},
UpdateAvailable {
update: crate::updates::UpdateInfo,
},
/// The project's source / test / resource / excluded roots changed (build files
/// changed or folders were marked); the UI re-reads them with `project_roots`.
ProjectRootsChanged {
+1
Переглянути файл
@@ -27,6 +27,7 @@ pub mod settings;
pub mod task;
pub mod text;
pub mod tool_path;
pub mod updates;
pub mod version_managers;
pub mod workflow_settings;
pub mod wsl;
+45 -3
Переглянути файл
@@ -104,6 +104,9 @@ fn signal_group(child: &Child, signal: libc::c_int) {
#[cfg(windows)]
const TREE_EXIT_WAIT: Duration = Duration::from_secs(5);
#[cfg(windows)]
pub use windows_tree::ProcessTree;
/// `taskkill /T /F` from `pid`, then waits (up to [`TREE_EXIT_WAIT`]) until what the child
/// started is gone: termination is asynchronous, and until a process is gone the files it
/// holds open can't be opened or deleted. The child itself is left to its owner to reap.
@@ -136,13 +139,48 @@ mod windows_tree {
CreateToolhelp32Snapshot, PROCESSENTRY32W, Process32FirstW, Process32NextW, TH32CS_SNAPPROCESS,
};
use windows_sys::Win32::System::Threading::{
GetProcessTimes, OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION, PROCESS_SYNCHRONIZE, WaitForSingleObject,
GetProcessTimes, OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION, PROCESS_SYNCHRONIZE, PROCESS_TERMINATE,
TerminateProcess, WaitForSingleObject,
};
/// Owned handles to a program and its current descendants, retained even if its launcher exits.
pub struct ProcessTree {
processes: Vec<OwnedHandle>,
}
impl ProcessTree {
pub fn capture(pid: u32) -> Self {
let Some(root) = open_with(pid, PROCESS_TERMINATE) else { return Self { processes: Vec::new() } };
let children = descendants_with(pid, PROCESS_TERMINATE);
Self { processes: std::iter::once(root).chain(children).collect() }
}
pub fn is_running(&self) -> bool {
self.processes.iter().any(|process| {
// SAFETY: an owned process handle opened with SYNCHRONIZE access.
unsafe {
WaitForSingleObject(process.as_raw_handle(), 0) == windows_sys::Win32::Foundation::WAIT_TIMEOUT
}
})
}
/// Requests termination children first; poll `is_running` until termination completes.
pub fn terminate(&self) {
for process in self.processes.iter().rev() {
// SAFETY: an owned process handle opened with TERMINATE access, never a reused pid.
unsafe { TerminateProcess(process.as_raw_handle(), 1) };
}
}
}
/// Every process `root` started, directly or not, opened so it can be waited for. A
/// parent's id is reused once it is gone, so a process counts only if it started after
/// its parent.
pub(super) fn descendants(root: u32) -> Vec<OwnedHandle> {
descendants_with(root, 0)
}
fn descendants_with(root: u32, access: u32) -> Vec<OwnedHandle> {
let Some(root_started) = open(root).as_ref().and_then(started) else { return Vec::new() };
let processes = processes();
let mut seen = HashSet::from([root]);
@@ -153,7 +191,7 @@ mod windows_tree {
if ppid != parent || !seen.insert(pid) {
continue;
}
let Some(handle) = open(pid) else { continue };
let Some(handle) = open_with(pid, access) else { continue };
if let Some(at) = started(&handle).filter(|&at| at >= parent_started) {
parents.push((pid, at));
found.push(handle);
@@ -193,8 +231,12 @@ mod windows_tree {
}
fn open(pid: u32) -> Option<OwnedHandle> {
open_with(pid, 0)
}
fn open_with(pid: u32, access: u32) -> Option<OwnedHandle> {
// SAFETY: plain call; a non-null result is a process handle owned by the caller.
let handle = unsafe { OpenProcess(PROCESS_SYNCHRONIZE | PROCESS_QUERY_LIMITED_INFORMATION, 0, pid) };
let handle = unsafe { OpenProcess(PROCESS_SYNCHRONIZE | PROCESS_QUERY_LIMITED_INFORMATION | access, 0, pid) };
// SAFETY: as above.
(!handle.is_null()).then(|| unsafe { OwnedHandle::from_raw_handle(handle) })
}
+2
Переглянути файл
@@ -292,6 +292,7 @@ pub struct GeneralSettings {
pub project_name: String,
/// Where updates come from: `auto` (the CNB mirror for the Chinese UI, else GitHub) | `github` | `cnb`.
pub update_source: String,
pub auto_check_updates: bool,
}
impl Default for GeneralSettings {
@@ -307,6 +308,7 @@ impl Default for GeneralSettings {
power_save_mode: false,
project_name: String::new(),
update_source: "auto".into(),
auto_check_updates: true,
}
}
}
+151
Переглянути файл
@@ -0,0 +1,151 @@
use serde::{Deserialize, Serialize};
use specta::Type;
use std::collections::HashSet;
use std::time::{Duration, Instant};
pub const CHECK_INTERVAL: Duration = Duration::from_secs(4 * 60 * 60);
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum UpdateSource {
#[default]
Github,
Cnb,
}
impl UpdateSource {
pub fn resolve(preference: &str, locale: &str, system_locale: &str) -> Self {
match preference {
"github" => return Self::Github,
"cnb" => return Self::Cnb,
_ => {}
}
let locale = locale.trim();
let locale = if matches!(locale, "" | "auto" | "system") { system_locale } else { locale };
if locale.split(['-', '_']).next().is_some_and(|base| base.eq_ignore_ascii_case("zh")) {
Self::Cnb
} else {
Self::Github
}
}
}
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct UpdateInfo {
pub version: String,
pub current_version: String,
pub notes: Option<String>,
pub date: Option<String>,
}
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct UpdateCheck {
pub enabled: bool,
pub update: Option<UpdateInfo>,
}
#[derive(Clone, Debug, Default, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct UpdateStatus {
/// Unix milliseconds of the last successful check in this process.
pub last_checked: Option<f64>,
pub checking: bool,
}
/// One schedule and announcement history for the desktop process, independent of its windows.
#[derive(Default)]
pub struct UpdatePolicy {
attempted: Option<Instant>,
pub status: UpdateStatus,
announced: HashSet<String>,
}
impl UpdatePolicy {
pub fn due_in(&self, now: Instant) -> Duration {
self.attempted.map_or(Duration::ZERO, |at| CHECK_INTERVAL.saturating_sub(now.saturating_duration_since(at)))
}
pub fn begin(&mut self, now: Instant) {
self.attempted = Some(now);
self.status.checking = true;
}
pub fn finish(&mut self, checked_at: Option<f64>) {
self.status.checking = false;
if let Some(at) = checked_at {
self.status.last_checked = Some(at);
}
}
pub fn announced(&self, version: &str) -> bool {
self.announced.contains(version)
}
/// Manual checks always show their result, but also count as an announcement.
pub fn announce(&mut self, version: &str) -> bool {
self.announced.insert(version.to_owned())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn automatic_and_manual_checks_resolve_the_same_preferred_source() {
for (preference, locale, system, expected) in [
("auto", "zh-CN", "en-US", UpdateSource::Cnb),
("auto", " ZH_CN ", "en-US", UpdateSource::Cnb),
("auto", "system", "zh-CN", UpdateSource::Cnb),
("auto", "auto", "zh-TW", UpdateSource::Cnb),
("auto", "", "zh", UpdateSource::Cnb),
("auto", "en", "zh-CN", UpdateSource::Github),
("github", "zh", "zh-CN", UpdateSource::Github),
("cnb", "en", "en-US", UpdateSource::Cnb),
] {
assert_eq!(UpdateSource::resolve(preference, locale, system), expected);
}
}
#[test]
fn checks_at_startup_and_every_four_hours_even_after_failure() {
let mut policy = UpdatePolicy::default();
let now = Instant::now();
assert_eq!(policy.due_in(now), Duration::ZERO);
policy.begin(now);
assert!(policy.status.checking);
policy.finish(None);
assert_eq!(policy.status.last_checked, None);
assert_eq!(policy.due_in(now + CHECK_INTERVAL - Duration::from_secs(1)), Duration::from_secs(1));
assert_eq!(policy.due_in(now + CHECK_INTERVAL), Duration::ZERO);
policy.begin(now + CHECK_INTERVAL);
policy.finish(Some(1234.0));
assert_eq!(policy.status.last_checked, Some(1234.0));
assert!(!policy.status.checking);
assert_eq!(policy.due_in(now + CHECK_INTERVAL), CHECK_INTERVAL);
}
#[test]
fn manual_checks_reset_the_schedule_without_losing_last_success_on_failure() {
let mut policy = UpdatePolicy::default();
let now = Instant::now();
policy.begin(now);
policy.finish(Some(1000.0));
policy.begin(now + Duration::from_secs(60));
policy.finish(None);
assert_eq!(policy.status.last_checked, Some(1000.0));
assert_eq!(policy.due_in(now + CHECK_INTERVAL), Duration::from_secs(60));
}
#[test]
fn announcements_are_per_version_across_windows_sources_and_manual_checks() {
let mut policy = UpdatePolicy::default();
assert!(policy.announce("0.1.40"));
assert!(!policy.announce("0.1.40"));
assert!(policy.announce("0.1.41"));
assert!(!policy.announce("0.1.40"));
assert!(UpdatePolicy::default().announce("0.1.40"));
}
}
+3
Переглянути файл
@@ -1130,6 +1130,9 @@ impl DebugManager {
/// Ends a session: `terminate` (when asked and supported) → `disconnect` → kill.
pub(crate) async fn shutdown(&self, s: &Arc<Session>, terminate: bool) {
if terminate {
crate::session::remember_debuggee(s).await;
}
// java-debug runs the program itself and pipes its stdout over DAP. A `disconnect`
// ends that DAP session, so every line the program writes while shutting down is lost.
// Ask the program to exit ourselves and keep the adapter attached until it has drained
+34 -6
Переглянути файл
@@ -59,6 +59,8 @@ pub(crate) struct Session {
/// adapter may report the launcher shell, whose child is the program).
#[cfg_attr(not(unix), allow(dead_code))]
pub stop_pids: parking_lot::Mutex<Vec<i32>>,
#[cfg(windows)]
pub stop_tree: Mutex<Option<ide_core::process::ProcessTree>>,
/// Breakpoints replaced for run to cursor / force stepping, restored on the next stop.
pub pending_restore: Mutex<PendingRestore>,
/// Adapter breakpoint id → (file, index in the stored list).
@@ -111,6 +113,8 @@ impl Session {
stop_force: AtomicBool::new(false),
debuggee_pid: AtomicI64::new(0),
stop_pids: parking_lot::Mutex::new(Vec::new()),
#[cfg(windows)]
stop_tree: Mutex::new(None),
pending_restore: Mutex::default(),
breakpoint_ids: Mutex::new(HashMap::new()),
resolved_paths: Mutex::new(HashMap::new()),
@@ -298,6 +302,21 @@ impl Session {
/// How long Stop waits for a launched program to exit before reporting the session ended.
pub(crate) const DEBUGGEE_EXIT_WAIT: Duration = Duration::from_secs(10);
pub(crate) async fn remember_debuggee(s: &Arc<Session>) {
#[cfg(windows)]
{
let Ok(pid) = u32::try_from(s.debuggee_pid.load(Ordering::Acquire)) else { return };
if s.request != "launch" || pid == 0 || s.stop_tree.lock().is_some() {
return;
}
if let Ok(tree) = tokio::task::spawn_blocking(move || ide_core::process::ProcessTree::capture(pid)).await {
s.stop_tree.lock().get_or_insert(tree);
}
}
#[cfg(not(windows))]
let _ = s;
}
/// The program and everything it started: an adapter may report the launcher shell, whose
/// child is the debugged program, so stopping only the reported pid leaves the program alive.
#[cfg(unix)]
@@ -349,12 +368,10 @@ pub(crate) fn signal_debuggee(s: &Arc<Session>, force: bool) {
}
#[cfg(windows)]
{
let mut cmd = std::process::Command::new("taskkill");
cmd.args(["/PID", &pid.to_string(), "/T"]);
if force {
cmd.arg("/F");
// Console programs have no external graceful signal; the adapter gets its chance first.
if force && let Some(tree) = s.stop_tree.lock().as_ref() {
tree.terminate();
}
let _ = cmd.status();
}
#[cfg(not(any(unix, windows)))]
let _ = (pid, force);
@@ -391,7 +408,18 @@ pub(crate) async fn wait_for_debuggee(s: &Arc<Session>, terminate: bool) {
tokio::time::sleep(Duration::from_millis(50)).await;
}
}
#[cfg(not(unix))]
#[cfg(windows)]
{
remember_debuggee(s).await;
let deadline = std::time::Instant::now() + DEBUGGEE_EXIT_WAIT;
while s.stop_tree.lock().as_ref().is_some_and(|tree| tree.is_running()) {
if s.stop_force.swap(false, Ordering::AcqRel) || std::time::Instant::now() >= deadline {
signal_debuggee(s, true);
}
tokio::time::sleep(Duration::from_millis(50)).await;
}
}
#[cfg(not(any(unix, windows)))]
{
let _ = pid;
}
+87
Переглянути файл
@@ -14,6 +14,93 @@ use tokio::io::{AsyncRead, AsyncWrite, AsyncWriteExt, BufReader};
type Log = Arc<Mutex<Vec<Value>>>;
#[cfg(windows)]
#[test]
#[ignore = "child process for Windows stop tests"]
fn windows_debuggee_process() {
if std::env::var_os("OPENIDEA_TEST_DEBUGGEE").is_none() {
return;
}
if std::env::var("OPENIDEA_TEST_DEBUGGEE").unwrap() == "wrapper" {
let mut command = std::process::Command::new(std::env::current_exe().unwrap());
let mut child = ide_core::process::prepare(&mut command)
.args(["--exact", "tests::windows_debuggee_process", "--ignored", "--nocapture"])
.env("OPENIDEA_TEST_DEBUGGEE", "leaf")
.spawn()
.unwrap();
let _ = child.wait();
return;
}
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
println!("LISTENING {}", listener.local_addr().unwrap().port());
std::thread::sleep(Duration::from_secs(60));
}
#[cfg(windows)]
#[tokio::test]
async fn windows_stop_releases_the_debuggees_port_before_returning() {
use std::io::BufRead;
use std::sync::atomic::Ordering;
struct Child(std::process::Child, Option<ide_core::process::ProcessTree>);
impl Drop for Child {
fn drop(&mut self) {
if let Some(tree) = &self.1 {
tree.terminate();
}
let _ = self.0.kill();
let _ = self.0.wait();
}
}
for (second_stop, wrapper, supports_terminate) in
[(false, false, false), (true, false, false), (true, true, false), (true, true, true)]
{
let mut command = std::process::Command::new(std::env::current_exe().unwrap());
ide_core::process::prepare(&mut command)
.args(["--exact", "tests::windows_debuggee_process", "--ignored", "--nocapture"])
.env("OPENIDEA_TEST_DEBUGGEE", if wrapper { "wrapper" } else { "leaf" })
.stdout(std::process::Stdio::piped());
let mut child = Child(command.spawn().unwrap(), None);
let port: u16 = std::io::BufReader::new(child.0.stdout.take().unwrap())
.lines()
.map(Result::unwrap)
.find_map(|line| line.split("LISTENING ").nth(1).and_then(|p| p.parse().ok()))
.unwrap();
let pid = child.0.id();
child.1 = Some(ide_core::process::ProcessTree::capture(pid));
let h = harness(Script { debuggee_pid: Some(pid), supports_terminate, ..Default::default() });
let id = h.start(config()).await.unwrap();
let session = h.manager.session(id).unwrap();
while session.debuggee_pid.load(Ordering::Acquire) != i64::from(pid) {
tokio::time::sleep(Duration::from_millis(10)).await;
}
let stop = tokio::spawn({
let manager = h.manager.clone();
async move { manager.stop(id).await }
});
let deadline = std::time::Instant::now() + Duration::from_secs(5);
while session.stop_tree.lock().is_none() && !stop.is_finished() {
assert!(std::time::Instant::now() < deadline, "Stop did not capture the program tree");
tokio::time::sleep(Duration::from_millis(10)).await;
}
assert!(!stop.is_finished(), "Stop must wait for the live program");
if wrapper {
assert!(session.stop_tree.lock().is_some());
child.0.kill().unwrap();
child.0.wait().unwrap();
assert!(std::net::TcpListener::bind(("127.0.0.1", port)).is_err(), "the child still owns its port");
}
if second_stop {
h.manager.stop(id).await.unwrap();
}
let limit = if second_stop { 10 } else { 25 };
tokio::time::timeout(Duration::from_secs(limit), stop).await.unwrap().unwrap().unwrap();
assert!(child.0.try_wait().unwrap().is_some(), "Stop returned with the program alive");
let _listener = std::net::TcpListener::bind(("127.0.0.1", port)).expect("Stop returned with its port occupied");
}
}
#[derive(Clone)]
struct Script {
/// Send a `runInTerminal` reverse request when `launch` arrives.
+2 -1
Переглянути файл
@@ -552,7 +552,8 @@ pub async fn build_run(
let mut combined: Option<compile::BuildPlan> = None;
for member in workspace.projects.iter().filter(|p| file.as_ref().is_none_or(|f| f.starts_with(p))) {
let settings = ide_workspace::SettingsStore::load(&config_dir, Some(member)).effective();
let member_cache = cache.join(crate::project::project_key(member));
let member_cache =
if member == &root { cache.clone() } else { cache.join(crate::project::project_key(member)) };
let model = with_profiles(load(member, &member_cache, &settings), &member_cache);
let plan = prepare_plan(
compile::plan(member, &model, kind, file.as_deref(), settings.cmake.profiles.as_deref())?,
+35 -4
Переглянути файл
@@ -12,13 +12,18 @@ pub(super) fn scopes(project: &Project, config: &Path) -> IdeResult<Vec<Scope>>
}
fn scopes_at(root: &Path, cache: &Path, config: &Path, settings: Settings) -> IdeResult<Vec<Scope>> {
let window_root = root;
Ok(match ide_workspace::workspace::Workspace::load(root)? {
Some(workspace) => workspace
.projects
.into_iter()
.filter(|p| p.is_dir())
.map(|root| Scope {
cache: cache.join(crate::project::project_key(&root)),
cache: if root == window_root {
cache.to_owned()
} else {
cache.join(crate::project::project_key(&root))
},
settings: ide_workspace::SettingsStore::load(config, Some(&root)).effective(),
root,
})
@@ -36,10 +41,12 @@ pub(super) fn load_scopes(root: &Path, scopes: &[Scope]) -> BuildModel {
let mut combined = BuildModel::default();
for scope in scopes {
let mut model = load(&scope.root, &scope.cache, &scope.settings);
if scope.root == root {
if scopes.len() == 1 && scope.root == root {
return model;
}
if let Some(maven) = &mut model.maven {
if scope.root != root
&& let Some(maven) = &mut model.maven
{
let owner = ide_core::ipc_path::to_ipc(&scope.root);
for p in &mut maven.projects {
p.project_root = Some(owner.clone());
@@ -73,7 +80,7 @@ pub(super) fn load_scopes(root: &Path, scopes: &[Scope]) -> BuildModel {
}
}
}
for g in &mut model.gradle {
for g in model.gradle.iter_mut().filter(|_| scope.root != root) {
g.dir = absolute(&scope.root, &g.dir);
for p in &mut g.projects {
p.dir = absolute(&scope.root, &p.dir);
@@ -145,6 +152,30 @@ pub(super) fn update_files(root: &Path, scopes: &[Scope], model: &BuildModel, to
mod tests {
use super::*;
#[test]
fn attached_primary_keeps_its_cache_and_combines_build_models() {
let tmp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(tmp.path()).unwrap();
let root = base.join("primary");
let other = base.join("other");
for path in [&root, &other] {
std::fs::create_dir(path).unwrap();
std::fs::write(path.join("pom.xml"), "<project><artifactId>app</artifactId></project>").unwrap();
}
let cache = base.join("cache");
ide_build::save_maven_profiles(&cache, &["kept".into()]).unwrap();
ide_workspace::workspace::Workspace::attach(&root, "Primary", vec![root.clone(), other.clone()]).unwrap();
let scopes = scopes_at(&root, &cache, &base.join("config"), Settings::default()).unwrap();
assert_eq!(scopes[0].cache, cache);
assert_eq!(ide_build::maven_profiles(&scopes[0].cache), ["kept"]);
assert_eq!(scopes[1].cache, cache.join(crate::project::project_key(&other)));
let model = load_scopes(&root, &scopes);
let projects = model.maven.unwrap().projects;
assert_eq!(projects.len(), 2);
assert_eq!(projects[0].pom, "pom.xml");
assert_eq!(projects[1].pom, absolute(&other, "pom.xml"));
}
#[test]
fn workspace_models_use_member_settings_paths_and_caches() {
let temp = tempfile::tempdir().unwrap();
+1 -1
Переглянути файл
@@ -82,7 +82,7 @@ fn go_source(project: &crate::Project, config_dir: &Path, path: &Path) -> IdeRes
workspace
.projects
.into_iter()
.filter(|root| path.starts_with(root))
.filter(|root| **root != project.root && path.starts_with(root))
.max_by_key(|root| root.components().count())
});
let settings = match &member {
+61 -20
Переглянути файл
@@ -13,6 +13,8 @@ pub struct ProjectInfo {
pub trusted: bool,
pub root: ide_core::IpcPath,
pub name: String,
#[serde(default)]
pub display_name: String,
pub is_git: bool,
pub settings: Settings,
#[serde(default, skip_serializing_if = "Option::is_none")]
@@ -24,17 +26,23 @@ pub struct ProjectInfo {
pub fn info(project: &Project) -> ProjectInfo {
let settings = project.settings.effective();
let custom = settings.general.project_name.trim();
let primary = if custom.is_empty() {
project.root.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default()
} else {
custom.to_owned()
};
let workspace = ide_workspace::workspace::Workspace::load(&project.root).ok().flatten();
ProjectInfo {
trusted: project.is_trusted(),
name: if custom.is_empty() {
project.root.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default()
} else {
custom.to_owned()
},
display_name: workspace
.as_ref()
.map(|w| w.display_name(&project.root, &primary))
.unwrap_or_else(|| primary.clone()),
name: workspace.as_ref().filter(|w| w.is_container(&project.root)).map(|w| w.name.clone()).unwrap_or(primary),
is_git: !project.repos.read().is_empty(),
settings,
root: project.root.clone().into(),
workspace: ide_workspace::workspace::Workspace::load(&project.root).ok().flatten(),
workspace,
unity: ide_workspace::unity::detect(&project.root),
}
}
@@ -63,38 +71,71 @@ pub fn roots(host: &Host, window: &str) -> IdeResult<ide_workspace::ProjectRoots
pub fn save_workspace(host: &Host, window: &str, name: &str, paths: Vec<std::path::PathBuf>) -> IdeResult<ProjectInfo> {
let project = host.project(window)?;
ide_workspace::workspace::Workspace::save(&project.root, name, paths, false)?;
let previous = ide_workspace::workspace::Workspace::load(&project.root)?
.ok_or_else(|| ide_core::IdeError::invalid("This folder is not a workspace"))?;
for path in paths.iter().filter(|p| !previous.projects.contains(p)) {
require_attachment_trust(host, path)?;
}
if !previous.is_container(&project.root) && paths.first() != Some(&project.root) {
return Err(ide_core::IdeError::invalid("The primary project cannot be detached"));
}
if !previous.is_container(&project.root) && paths == [project.root.clone()] {
std::fs::remove_file(project.root.join(ide_workspace::workspace::FILE))?;
} else {
let workspace = ide_workspace::workspace::Workspace::save(&project.root, name, paths, false)?;
keep_attachment_private(&project.root, &workspace)?;
}
refresh_workspace(&project);
Ok(info(&project))
}
fn require_attachment_trust(host: &Host, path: &Path) -> IdeResult<()> {
if !host.trust.trusted(path)? {
return Err(ide_core::IdeError::invalid("Trust the project before attaching it"));
}
Ok(())
}
fn keep_attachment_private(root: &Path, workspace: &ide_workspace::workspace::Workspace) -> IdeResult<()> {
if !workspace.is_container(root) {
ide_vcs::changelists::ensure_ignored(&root.join(".openidea"), &["/workspace.json"])?;
}
Ok(())
}
fn refresh_workspace(project: &Project) {
project.settings.reload();
project.refresh_index_scope();
project.refresh_repositories();
project.sink.emit(ide_core::IdeEvent::ProjectRootsChanged { root: project.root.clone().into() });
Ok(info(&project))
}
/// Links a folder, or prepares an automatic workspace for the caller to open in place.
/// Attaches a trusted folder without replacing the current project.
pub fn attach_workspace(host: &Host, window: &str, path: &Path) -> IdeResult<ide_core::IpcPath> {
let project = host.project(window)?;
let path = dunce::canonicalize(path)?;
if project.light {
return Err(ide_core::IdeError::invalid("Open a project before attaching a folder"));
}
if path == project.root {
return Ok(project.root.clone().into());
}
require_attachment_trust(host, &path)?;
if let Some(mut workspace) = ide_workspace::workspace::Workspace::load(&project.root)? {
if !workspace.projects.contains(&path) {
workspace.projects.push(path);
save_workspace(host, window, &workspace.name, workspace.projects)?;
}
return Ok(project.root.clone().into());
} else {
let workspace = ide_workspace::workspace::Workspace::attach(
&project.root,
&info(&project).name,
vec![project.root.clone(), path],
)?;
keep_attachment_private(&project.root, &workspace)?;
refresh_workspace(&project);
}
if path == project.root {
return Ok(project.root.clone().into());
}
Ok(ide_workspace::workspace::Workspace::create_for_project(
&host.data_dir,
&project.root,
&info(&project).name,
&path,
)?
.into())
Ok(project.root.clone().into())
}
/// What [`set_settings`] changed; the caller tells the windows.
+11 -10
Переглянути файл
@@ -24,7 +24,7 @@ pub(super) fn project_configs(
let root_suppressed = ide_run::load_suppressed_config_ids(root)?;
let mut all = detected_and_saved(root, settings, &user, &root_suppressed);
if let Some(workspace) = ide_workspace::workspace::Workspace::load(root)? {
for member in workspace.projects.into_iter().filter(|p| p.is_dir()) {
for member in workspace.projects.into_iter().filter(|p| p != root && p.is_dir()) {
let settings = ide_workspace::SettingsStore::load(config_dir, Some(&member)).effective();
let saved = ide_run::load_user_configs(&member)?;
let suppressed = ide_run::load_suppressed_config_ids(&member)?;
@@ -145,20 +145,21 @@ fn settings_for(
config: &mut RunConfig,
) -> IdeResult<(std::path::PathBuf, ide_core::settings::Settings)> {
let workspace = ide_workspace::workspace::Workspace::load(&project.root)?;
if workspace.is_some() {
let owner = ide_run::scope::owner(&project.root, config);
let member = workspace.as_ref().and_then(|workspace| {
workspace
.projects
.iter()
.filter(|root| **root != project.root && owner.starts_with(root))
.max_by_key(|root| root.components().count())
.cloned()
});
if workspace.as_ref().is_some_and(|w| w.is_container(&project.root)) || member.is_some() {
if config.extras.module.is_none() && !matches!(config.kind.as_str(), "application" | "spring-boot") {
config.extras.module = config.cwd.as_deref().map(ide_core::ipc_path::to_ipc);
}
ide_run::scope::rebase(config, &project.root, None);
}
let member = workspace.and_then(|workspace| {
let owner = ide_run::scope::owner(&project.root, config);
workspace
.projects
.into_iter()
.filter(|root| owner.starts_with(root))
.max_by_key(|root| root.components().count())
});
Ok(match member {
Some(root) => {
let settings = ide_workspace::SettingsStore::load(&host.config_dir, Some(&root)).effective();
+1 -1
Переглянути файл
@@ -61,7 +61,7 @@ pub(crate) fn search_project(
ide_search::SearchScope::FileSet { set } => Some(set),
_ => None,
};
let workspace = ide_workspace::workspace::Workspace::load(root)?.is_some();
let workspace = ide_workspace::workspace::Workspace::load(root)?.is_some_and(|w| w.is_container(root));
let include_root = !workspace
|| matches!(query.scope, ide_search::SearchScope::Directory { .. } | ide_search::SearchScope::Files { .. });
let content_roots = match query.scope {
+2
Переглянути файл
@@ -24,8 +24,10 @@ fn tools(host: &Host, window: &str) -> IdeResult<Tools> {
.collect();
// Godot is usually an app bundle / Flatpak outside the search path.
let found = ide_sdk::godot::find(None).map(|p| (ide_sdk::godot::COMMAND.to_owned(), p));
let runtime = ide_sdk::apply::tool_install_environment(&root, &settings);
let work_dir = (!root.as_os_str().is_empty()).then_some(root);
Ok(Tools::new(&data)
.with_runtime(runtime.commands, runtime.env)
.with_custom_paths(custom)
.with_found_paths(found.into_iter().collect())
.with_work_dir(work_dir))
+23 -7
Переглянути файл
@@ -96,7 +96,7 @@ impl Host {
self.wait_detached_closes();
let sink: SharedSink = (self.sink_for)(window);
// Before anything the project starts: its children get the project's environment.
let trusted = Arc::new(AtomicBool::new(self.trust.trusted(&root)?));
let trusted = Arc::new(AtomicBool::new(self.trust.window_trusted(&root)?));
let post_start =
trusted.load(Ordering::Acquire).then(|| self.environment.project_opened(&root, &sink)).flatten();
let settings = SettingsStore::load(&self.config_dir, Some(&root));
@@ -198,14 +198,15 @@ impl Host {
.as_ref()
.map(|p| SettingsStore::load(&config_dir, Some(p)).effective())
.unwrap_or_else(|| settings.effective());
let root = member.as_ref().unwrap_or(&root);
let window_root = &root;
let root = member.as_ref().unwrap_or(window_root);
ide_sdk::apply::server_launch_overrides(cfg, &effective);
ide_sdk::apply::configure_server(cfg, root, server_root, &effective);
if cfg.name == "jdtls" {
// A workspace member keeps its build model under its own key (Build Project).
let cache = match &member {
Some(member) => build_cache.join(crate::project::project_key(member)),
None => build_cache.clone(),
Some(member) if member != window_root => build_cache.join(crate::project::project_key(member)),
_ => build_cache.clone(),
};
let profiles = ide_build::maven_profiles(&cache);
ide_sdk::maven_profiles::configure_jdtls(cfg, root, &effective, &profiles, &cache);
@@ -1224,17 +1225,32 @@ pub fn history_retention(settings: &ide_core::settings::Settings) -> ide_workspa
}
}
/// A workspace uses its root only for state, never as indexed content.
/// Only explicit workspace containers exclude their root from indexed content.
fn index_roots(root: &Path, folders: Vec<PathBuf>) -> ide_index::IndexRoots {
ide_index::IndexRoots { include_root: !root.join(ide_workspace::workspace::FILE).is_file(), folders }
let container =
ide_workspace::workspace::Workspace::load(root).ok().flatten().is_some_and(|w| w.is_container(root));
ide_index::IndexRoots { include_root: !container, folders: folders.into_iter().filter(|p| p != root).collect() }
}
/// Workspace members in manifest order, or extra Project Structure directories and the
/// Gradle project folders outside the project as of the last sync (`build_cache`).
fn content_roots(settings: &ide_core::settings::Settings, root: &Path, build_cache: &Path) -> Vec<PathBuf> {
if let Ok(Some(workspace)) = ide_workspace::workspace::Workspace::load(root) {
return workspace.projects;
if workspace.is_container(root) {
return workspace.projects;
}
let mut roots = workspace.projects.into_iter().filter(|p| !p.starts_with(root)).collect::<Vec<_>>();
for path in extra_content_roots(settings, root, build_cache) {
if !roots.contains(&path) {
roots.push(path);
}
}
return roots;
}
extra_content_roots(settings, root, build_cache)
}
fn extra_content_roots(settings: &ide_core::settings::Settings, root: &Path, build_cache: &Path) -> Vec<PathBuf> {
let mut out: Vec<PathBuf> = Vec::new();
let user = settings.project_structure.content_roots.iter().map(|r| PathBuf::from(r.trim()));
for p in user.chain(ide_build::gradle_external_roots(root, build_cache, &settings.languages.java.gradle)) {
+21 -2
Переглянути файл
@@ -56,6 +56,22 @@ impl TrustStore {
|| self.inherited.lock().contains(&root)))
}
pub fn window_trusted(&self, root: &Path) -> IdeResult<bool> {
if !self.trusted(root)? {
return Ok(false);
}
if let Some(workspace) = ide_workspace::workspace::Workspace::load(root)?
&& !workspace.is_container(root)
{
for member in workspace.projects.iter().filter(|p| *p != root && p.exists()) {
if !self.trusted(member)? {
return Ok(false);
}
}
}
Ok(true)
}
/// Trusts `path` for this process without recording a decision (see [`TRUSTED_ROOT_ENV`]).
pub fn inherit(&self, path: &Path) -> IdeResult<()> {
let root = dunce::canonicalize(path)?;
@@ -134,7 +150,7 @@ impl crate::Host {
pub async fn refresh_project_trust(&self) -> IdeResult<()> {
for project in self.projects().into_iter().filter(|p| !p.light) {
let trusted = self.trust.trusted(&project.root).unwrap_or(false);
let trusted = self.trust.window_trusted(&project.root).unwrap_or(false);
let previous = project.trusted.swap(trusted, std::sync::atomic::Ordering::AcqRel);
if previous == trusted {
continue;
@@ -221,12 +237,15 @@ pub fn restricted_command_allowed(cmd: &str) -> bool {
| "app_cli_uninstall"
| "app_log_location"
| "app_check_update"
| "app_startup_update_check"
| "app_update_window_ready"
| "app_update_status"
| "app_update_announcement"
| "app_install_update"
| "caches_schedule_invalidation"
| "clear_caches"
| "clipboard_file_list"
| "clipboard_has_files"
| "clipboard_image"
| "clipboard_set_file_list"
| "jdk_download_vendors"
| "jdk_download_releases"
+34 -1
Переглянути файл
@@ -38,12 +38,15 @@ async fn application_commands_work_in_restricted_projects_and_without_a_project(
"app_cli_uninstall",
"app_log_location",
"app_check_update",
"app_startup_update_check",
"app_update_window_ready",
"app_update_status",
"app_update_announcement",
"app_install_update",
"caches_schedule_invalidation",
"clear_caches",
"clipboard_file_list",
"clipboard_has_files",
"clipboard_image",
"clipboard_set_file_list",
"jdk_download_vendors",
"jdk_download_releases",
@@ -448,3 +451,33 @@ async fn revocation_still_applies_when_a_project_folder_was_removed() {
assert!(!project.is_trusted());
host.shutdown().await;
}
#[test]
fn attached_member_trust_is_required_after_restart_and_revocation() {
let tmp = tempfile::tempdir().unwrap();
let (config, data) = (tmp.path().join("config"), tmp.path().join("data"));
let base = dunce::canonicalize(tmp.path()).unwrap();
let root = base.join("primary");
let other = base.join("other");
for path in [&root, &other] {
std::fs::create_dir(path).unwrap();
}
ide_workspace::workspace::Workspace::attach(&root, "Primary", vec![root.clone(), other.clone()]).unwrap();
let trust = TrustStore::load(&config, &data);
trust.decide(&root, true, false).unwrap();
trust.inherit(&other).unwrap();
assert!(trust.window_trusted(&root).unwrap());
let trust = TrustStore::load(&config, &data);
assert!(trust.status(&root).unwrap().trusted);
assert!(!trust.window_trusted(&root).unwrap());
assert!(!trust.status(&other).unwrap().decided);
trust.decide(&root, true, false).unwrap();
assert!(!trust.window_trusted(&root).unwrap(), "trusting only the root does not recover the window");
trust.decide(&other, true, false).unwrap();
assert!(trust.window_trusted(&root).unwrap());
trust.decide(&other, false, false).unwrap();
assert!(trust.status(&other).unwrap().decided);
assert!(!trust.window_trusted(&root).unwrap());
trust.decide(&other, true, false).unwrap();
assert!(trust.window_trusted(&root).unwrap());
}
+134 -14
Переглянути файл
@@ -32,11 +32,15 @@ async fn linked_projects_share_navigation_but_keep_files_repositories_and_run_di
});
std::fs::write(root.join("internal-needle.txt"), "needle").unwrap();
host.trust.decide(&root, true, false).unwrap();
for member in &roots {
host.trust.decide(member, true, false).unwrap();
}
let project = host.open_project("main", &root).unwrap();
assert_eq!(ops::project::info(&project).name, "Full stack");
assert_eq!(ops::project::attach_workspace(&host, "main", &roots[1]).unwrap().as_ref(), root.as_path());
ops::project::attach_workspace(&host, "main", &roots[1]).unwrap();
assert_eq!(project.content_roots(), roots);
assert!(!root.join(".openidea/.gitignore").exists());
assert!(project.index.wait_idle(Duration::from_secs(10)));
assert!(project.index.find_files("internal-needle", 100).is_empty());
assert!(project.index.find_files("workspace.json", 100).is_empty());
@@ -98,20 +102,6 @@ async fn linked_projects_share_navigation_but_keep_files_repositories_and_run_di
std::fs::write(invalid.join(ide_workspace::workspace::FILE), "broken").unwrap();
assert!(host.open_project("main", &invalid).is_err());
assert!(Arc::ptr_eq(&host.project("main").unwrap(), &project));
host.open_project("main", &roots[0]).unwrap();
let automatic = ops::project::attach_workspace(&host, "main", &roots[1]).unwrap();
assert_eq!(host.project("main").unwrap().root, roots[0]);
let automatic = host.open_project("main", &automatic).unwrap();
assert_eq!(automatic.content_roots(), roots);
assert_eq!(ops::project::info(&automatic).name, "frontend");
assert!(automatic.root.starts_with(base.join("data/workspaces")));
assert!(automatic.index.wait_idle(Duration::from_secs(10)));
assert!(automatic.index.find_files("workspace.json", 100).is_empty());
let updated = ops::project::save_workspace(&host, "main", "frontend", vec![roots[1].clone()]).unwrap();
assert_eq!(updated.workspace.unwrap().projects, vec![roots[1].clone()]);
assert_eq!(automatic.root, updated.root.as_ref());
assert!(automatic.index.wait_idle(Duration::from_secs(10)));
assert_eq!(automatic.index.find_files("same.txt", 100).len(), 1);
host.close_project("main");
}
@@ -206,3 +196,133 @@ async fn build_tool_availability_follows_workspace_members_and_trust() {
assert_eq!(model.gradle.len(), 1);
host.close_project("main");
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn attach_and_detach_preserve_the_primary_project_session() {
let temp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(temp.path()).unwrap();
let roots = vec![base.join("primary"), base.join("other")];
for root in &roots {
std::fs::create_dir(root).unwrap();
std::fs::write(root.join("same.txt"), "needle").unwrap();
std::fs::write(root.join("package.json"), r#"{"scripts":{"test":"echo test"}}"#).unwrap();
}
let host = Host::new(HostConfig {
config_dir: base.join("config"),
data_dir: base.join("data"),
local_data_dir: base.join("data"),
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: Arc::default(),
sink_for: Box::new(|_| Arc::new(NullSink)),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
});
host.trust.decide(&roots[0], true, false).unwrap();
let project = host.open_project("main", &roots[0]).unwrap();
assert!(project.index.wait_idle(Duration::from_secs(10)));
let configs = ops::run::configs(&host, "main").unwrap();
assert!(!configs.is_empty());
let cache = project.build_cache_dir();
let doc = ops::doc::open(&host, "main", roots[0].join("same.txt")).await.unwrap();
ops::doc::edit(
&host,
"main",
doc.id,
doc.version,
ChangeSet { changes: vec![TextChange { from: 0, to: 0, insert: "unsaved ".into() }] },
)
.unwrap();
assert!(ops::project::attach_workspace(&host, "main", &roots[1]).is_err());
host.trust.decide(&roots[1], false, false).unwrap();
assert!(ops::project::attach_workspace(&host, "main", &roots[1]).is_err());
assert!(!roots[0].join(ide_workspace::workspace::FILE).exists());
let existing_index = &project.index as *const _;
host.trust.decide(&roots[1], true, false).unwrap();
assert_eq!(ops::project::attach_workspace(&host, "main", &roots[1]).unwrap().as_ref(), roots[0]);
assert!(Arc::ptr_eq(&host.project("main").unwrap(), &project));
assert_eq!(&host.project("main").unwrap().index as *const _, existing_index);
assert_eq!(project.root, roots[0]);
assert_eq!(project.build_cache_dir(), cache);
assert!(!base.join("data/workspaces").exists());
assert_eq!(Workspace::load(&roots[0]).unwrap().unwrap().projects, roots);
assert!(
std::fs::read_to_string(roots[0].join(".openidea/.gitignore")).unwrap().lines().any(|l| l == "/workspace.json")
);
assert_eq!(project.content_roots(), vec![roots[1].clone()]);
let attached = ops::project::info(&project);
assert_eq!(attached.name, "primary");
assert_eq!(attached.display_name, "primary, other");
ops::project::set_settings(
&host,
"main",
ide_workspace::SettingsScope::Project,
"general.projectName",
&serde_json::to_string(&attached.name).unwrap(),
)
.unwrap();
assert_eq!(ops::project::info(&project).display_name, "primary, other");
let restricted = base.join("restricted");
std::fs::create_dir(&restricted).unwrap();
host.trust.decide(&restricted, false, false).unwrap();
assert!(
ops::project::save_workspace(&host, "main", "Primary", vec![roots[0].clone(), roots[1].clone(), restricted])
.is_err()
);
let all = ops::run::configs(&host, "main").unwrap();
assert_eq!(all.len(), configs.len() * 2);
for config in &configs {
assert_eq!(all.iter().filter(|c| c.id == config.id).count(), 1);
}
assert!(project.index.wait_idle(Duration::from_secs(10)));
assert_eq!(project.index.find_files("same.txt", 100).len(), 2);
let hits = Arc::new(Mutex::new(Vec::new()));
let out = hits.clone();
let query = serde_json::from_value(serde_json::json!({"pattern":"needle", "isRegex":false,"caseSensitive":false,"wholeWord":false,"include":[],"exclude":[],"scope":{"kind":"project"},"maxMatches":100})).unwrap();
ops::search::start(
&host,
"main",
RequestId::next(),
query,
Arc::new(move |event| {
if let ops::search::SearchEvent::File { file } = event {
out.lock().unwrap().push(file);
}
}),
)
.await
.unwrap();
assert_eq!(hits.lock().unwrap().len(), 2);
assert!(ops::project::save_workspace(&host, "main", "Primary", vec![roots[1].clone()]).is_err());
let updated = ops::project::save_workspace(&host, "main", "Primary", vec![roots[0].clone()]).unwrap();
assert!(updated.workspace.is_none());
assert_eq!(updated.name, "primary");
assert_eq!(updated.root.as_ref(), roots[0]);
assert!(!roots[0].join(ide_workspace::workspace::FILE).exists());
assert!(project.content_roots().is_empty());
assert_eq!(
ops::run::configs(&host, "main").unwrap().iter().map(|c| &c.id).collect::<Vec<_>>(),
configs.iter().map(|c| &c.id).collect::<Vec<_>>()
);
assert!(project.documents.text_of(&roots[0].join("same.txt")).unwrap().starts_with("unsaved"));
assert!(project.index.wait_idle(Duration::from_secs(10)));
assert_eq!(project.index.find_files("same.txt", 100).len(), 1);
let nested = roots[0].join("nested");
std::fs::create_dir(&nested).unwrap();
std::fs::write(nested.join("same.txt"), "needle").unwrap();
host.trust.decide(&nested, true, false).unwrap();
Workspace::attach(&nested, "Nested", vec![nested.clone()]).unwrap();
ops::project::attach_workspace(&host, "main", &nested).unwrap();
assert!(project.content_roots().is_empty());
let container = base.join("container");
Workspace::save(&container, "Container", vec![], true).unwrap();
host.trust.decide(&container, true, false).unwrap();
assert!(ops::project::attach_workspace(&host, "main", &container).is_err());
host.close_project("main");
let reopened = host.open_project("main", &roots[0]).unwrap();
assert_eq!(ops::project::info(&reopened).name, "primary");
assert_eq!(ops::project::info(&reopened).display_name, "primary, nested");
host.set_project_trust(&nested, false, false).await.unwrap();
assert!(!reopened.is_trusted());
host.close_project("main");
}
+6
Переглянути файл
@@ -268,6 +268,12 @@ impl Handler for ClientHandler {
"window/showMessage" => self.show_message(&mgr, &params),
"window/logMessage" => {
let text = params.get("message").and_then(Value::as_str).unwrap_or_default();
if self.server.name == "jdtls"
&& text.contains("Can't use Java ")
&& text.contains(" to import Gradle project ")
{
self.show_message(&mgr, &json!({ "type": 1, "message": text.lines().next().unwrap_or(text) }));
}
match params.get("type").and_then(Value::as_u64) {
Some(1) if self.server.name == "jdtls" && text.contains(crate::jdtls::reserved_names::IMPORT_FAILURE) => {
tracing::warn!("[{}] {text}", self.server.name);
+4
Переглянути файл
@@ -2584,6 +2584,10 @@ impl LspManager {
let watchers = run.watchers.read();
let roots = self.server_workspace_roots(&s);
let changes: Vec<(&PathBuf, Change)> = if watchers.is_empty() {
// Dart watches the filesystem itself and rejects this unregistered notification.
if s.name == "dart" {
continue;
}
let languages = s.languages();
all.filter(|(p, change)| {
roots.iter().any(|root| p.starts_with(root))
+70 -7
Переглянути файл
@@ -52,6 +52,7 @@ pub enum Phase {
struct State {
generation: u64,
conn: Conn,
restarting: bool,
events: VecDeque<IdeEvent>,
publishing: bool,
}
@@ -140,7 +141,13 @@ impl Server {
effective: Mutex::new(None),
resolved_binary: RwLock::new(None),
languages: Mutex::new(vec![language]),
state: Mutex::new(State { generation: 0, conn: Conn::Idle, events: VecDeque::new(), publishing: false }),
state: Mutex::new(State {
generation: 0,
conn: Conn::Idle,
restarting: false,
events: VecDeque::new(),
publishing: false,
}),
initializing: Mutex::new(None),
start_cancel: Mutex::new(CancellationToken::new()),
phase: watch::channel(Phase::Down).0,
@@ -217,6 +224,7 @@ impl Server {
}
st.generation += 1;
st.conn = Conn::Starting;
st.restarting = false;
*self.start_cancel.lock() = CancellationToken::new();
*self.started.lock() = Some(Instant::now());
self.phase.send_replace(Phase::Starting);
@@ -300,21 +308,43 @@ impl Server {
self.running().filter(|r| r.generation == generation)
}
/// Waits while the server is starting; returns the instance once ready.
/// Waits through startup or a planned restart; returns the instance once ready.
pub async fn wait_ready(&self, timeout: Duration) -> Option<Running> {
let mut rx = self.phase.subscribe();
let _ = tokio::time::timeout(timeout, rx.wait_for(|p| *p != Phase::Starting)).await;
self.running()
tokio::time::timeout(timeout, async {
loop {
{
let st = self.state.lock();
// Read both under the writer's lock: a restart can begin just after a wakeup.
if *rx.borrow_and_update() != Phase::Starting {
return match &st.conn {
Conn::Ready(run) => Some(run.clone()),
_ => None,
};
}
}
if rx.changed().await.is_err() {
return None;
}
}
})
.await
.ok()
.flatten()
}
/// Ready → Stopping, returning the instance to shut down. An in-flight
/// start is abandoned instead.
pub fn begin_stop(&self, sink: &SharedSink, final_stop: bool) -> Option<Running> {
let mut st = self.state.lock();
if final_stop {
st.restarting = false;
}
match std::mem::replace(&mut st.conn, Conn::Idle) {
Conn::Ready(run) => {
st.conn = Conn::Stopping;
self.phase.send_replace(Phase::Down);
st.restarting = !final_stop;
self.phase.send_replace(if st.restarting { Phase::Starting } else { Phase::Down });
Some(run)
}
Conn::Starting => {
@@ -322,7 +352,8 @@ impl Server {
self.start_cancel.lock().cancel();
self.queue_cleanup(&mut st);
self.queue_status(&mut st, ServerStatus::Stopped, None);
self.phase.send_replace(Phase::Down);
st.restarting = !final_stop;
self.phase.send_replace(if st.restarting { Phase::Starting } else { Phase::Down });
drop(st);
self.publish(sink);
None
@@ -331,6 +362,7 @@ impl Server {
st.conn = other;
if final_stop {
self.queue_status(&mut st, ServerStatus::Stopped, None);
self.phase.send_replace(Phase::Down);
}
drop(st);
self.publish(sink);
@@ -352,7 +384,7 @@ impl Server {
self.queue_cleanup(&mut st);
self.queue_status(&mut st, ServerStatus::Stopped, None);
st.conn = Conn::Idle;
self.phase.send_replace(Phase::Down);
self.phase.send_replace(if st.restarting { Phase::Starting } else { Phase::Down });
drop(st);
self.publish(sink);
}
@@ -906,6 +938,37 @@ mod tests {
assert_eq!(s.status(), ServerStatus::Stopped);
}
#[tokio::test]
async fn final_stop_cancels_pending_restarts_in_every_phase() {
for phase in ["starting", "stopping", "between"] {
let s = server();
let sink: SharedSink = Arc::new(|_: IdeEvent| {});
let generation = s.begin_start().unwrap();
if phase == "starting" {
s.begin_stop(&sink, false);
} else {
let mut st = s.state.lock();
st.conn = Conn::Stopping;
st.restarting = true;
}
if phase == "between" {
s.end_stop(generation, &sink);
}
assert!(
tokio::time::timeout(Duration::from_millis(10), s.wait_ready(Duration::from_secs(30))).await.is_err()
);
s.begin_stop(&sink, true);
s.end_stop(generation, &sink);
assert_eq!(*s.phase.borrow(), Phase::Down);
assert!(
tokio::time::timeout(Duration::from_secs(1), s.wait_ready(Duration::from_secs(30)))
.await
.unwrap()
.is_none()
);
}
}
#[test]
fn failure_publication_can_restart_without_overwriting_the_new_phase() {
for conn in [Conn::Missing, Conn::Failed] {
+100
Переглянути файл
@@ -420,6 +420,45 @@ fn change(range: Range, text: &str) -> AppliedChange {
AppliedChange { range, text: text.into() }
}
#[tokio::test(flavor = "multi_thread")]
async fn dart_file_watching_requires_an_explicit_registration() {
for (language, extension, name, fallback) in
[("dart", "dart", "dart", false), ("dart", "dart", "alternative-dart", true), ("java", "java", "jdtls", true)]
{
let h = harness_for(language, extension, &[(name, incremental_caps())], &[]);
let (doc, _) = h.open(&format!("open.{extension}"), "x");
h.wait_status(name, ServerStatus::Ready).await;
let s = h.launcher.state(name);
let path = h.root.join(format!("closed.{extension}"));
let notify = || h.mgr.watched_files_changed(&[], std::slice::from_ref(&path), &[], &[]);
notify();
h.mgr.hover(doc, Pos::new(0, 0), Default::default()).await.unwrap();
assert_eq!(s.notified("workspace/didChangeWatchedFiles").len(), usize::from(fallback), "{name}");
s.peer()
.request::<_, Value>(
"client/registerCapability",
json!({ "registrations": [{ "id": "watch", "method": "workspace/didChangeWatchedFiles", "registerOptions": { "watchers": [{ "globPattern": "**/*" }] } }] }),
None,
)
.await
.unwrap();
notify();
eventually(|| s.notified("workspace/didChangeWatchedFiles").len() == usize::from(fallback) + 1).await;
s.peer()
.request::<_, Value>(
"client/unregisterCapability",
json!({ "unregisterations": [{ "id": "watch", "method": "workspace/didChangeWatchedFiles" }] }),
None,
)
.await
.unwrap();
notify();
h.mgr.hover(doc, Pos::new(0, 0), Default::default()).await.unwrap();
assert_eq!(s.notified("workspace/didChangeWatchedFiles").len(), usize::from(fallback) * 2 + 1, "{name}");
h.mgr.shutdown_all().await;
}
}
// ------------------------------------------------------------------ tests
#[tokio::test(flavor = "multi_thread")]
@@ -2347,6 +2386,34 @@ async fn java_source_paths_reach_initialization_live_configuration_and_builds()
assert_eq!(init["initializationOptions"]["triggerFiles"], json!([uri_of(&file)]));
}
#[tokio::test(flavor = "multi_thread")]
async fn java_build_waits_for_a_reconfigured_server_to_restart() {
let h = harness_for("java", "java", &[("jdtls", incremental_caps())], &[]);
h.open("App.java", "class App {}\n");
h.wait_status("jdtls", ServerStatus::Ready).await;
let state = h.launcher.state("jdtls");
state.respond("java/buildWorkspace", json!(1));
let gate = Arc::new(Gate::default());
*state.held.lock() = Some(("exit".into(), gate.clone()));
h.mgr.set_config_hook(Box::new(|cfg, _| cfg.args.push("--new-configuration".into())));
let reconfigure = tokio::spawn({
let mgr = h.mgr.clone();
async move { mgr.reconfigure().await }
});
eventually(|| gate.entered()).await;
let mut build = tokio::spawn({
let (mgr, root) = (h.mgr.clone(), h.root.clone());
async move { mgr.java_build(&root, false, &Default::default()).await }
});
let early = tokio::time::timeout(Duration::from_millis(100), &mut build).await;
gate.open();
reconfigure.await.unwrap();
assert!(early.is_err(), "a planned restart must not fail a pending build: {early:?}");
assert_eq!(build.await.unwrap().unwrap(), ide_lsp::jdtls::JavaBuildStatus::Succeeded);
assert_eq!(state.launches.load(Ordering::SeqCst), 2);
h.mgr.shutdown_all().await;
}
#[tokio::test(flavor = "multi_thread")]
async fn java_build_asks_for_a_full_build_when_rebuilding() {
let h = harness_for("java", "java", &[("jdtls", incremental_caps())], &[]);
@@ -5606,6 +5673,39 @@ async fn jdtls_import_failure_names_reserved_device_files_on_windows() {
let _ = std::fs::remove_file(&nul);
}
#[tokio::test(flavor = "multi_thread")]
async fn gradle_incompatible_jdk_log_is_surfaced_once_across_message_channels() {
let h = harness_for("java", "java", &[("jdtls", incremental_caps())], &[]);
let s = h.launcher.state("jdtls");
h.open("A.java", "class A {}");
h.wait_status("jdtls", ServerStatus::Ready).await;
let failure = "Can't use Java 27.0.1.0.3 and Gradle 9.7.1 to import Gradle project kotlin-gradle.";
for _ in 0..2 {
s.peer()
.notify(
"window/logMessage",
json!({ "type": 1, "message": format!("{failure}\njava.lang.Exception: details stay in the log") }),
)
.unwrap();
}
eventually(|| h.events.lock().iter().any(|e| matches!(e, IdeEvent::Notify { body: Some(b), .. } if b == failure)))
.await;
s.peer().notify("window/showMessage", json!({ "type": 1, "message": failure })).unwrap();
s.peer().notify("window/logMessage", json!({ "type": 1, "message": "unrelated internal error" })).unwrap();
s.peer().notify("window/showMessage", json!({ "type": 2, "message": "after" })).unwrap();
eventually(|| h.events.lock().iter().any(|e| matches!(e, IdeEvent::Notify { body: Some(b), .. } if b == "after")))
.await;
let events = h.events.lock();
let messages: Vec<_> = events
.iter()
.filter_map(|e| match e {
IdeEvent::Notify { body: Some(body), .. } => Some(body.as_str()),
_ => None,
})
.collect();
assert_eq!(messages, vec![failure, "after"]);
}
/// Pull Members Up / Push Members Down: the extension's answers, refusals and edits.
#[tokio::test(flavor = "multi_thread")]
async fn java_hierarchy_refactorings_use_the_extension_commands() {
+28
Переглянути файл
@@ -130,6 +130,34 @@ pub(crate) fn goroot(root: &Path, s: &Settings) -> Option<PathBuf> {
.or_else(|| pinned::pinned_install(root, Tool::Go).and_then(|(dir, _)| pinned::goroot_in_install(&dir)))
}
/// Runtime choices for package-manager based IDE tool installs.
#[derive(Default)]
pub struct ToolInstallEnvironment {
pub commands: std::collections::BTreeMap<String, PathBuf>,
pub env: std::collections::BTreeMap<String, String>,
}
/// Uses the same configured / project-pinned SDKs as Run and language servers.
/// Build tags and target OS settings intentionally do not apply to host tools.
pub fn tool_install_environment(root: &Path, s: &Settings) -> ToolInstallEnvironment {
let mut runtime = ToolInstallEnvironment::default();
if let Some(go) = goroot(root, s) {
runtime.commands.insert("go".into(), go.join("bin").join(exe("go")));
runtime.env.insert("GOROOT".into(), go.to_string_lossy().into_owned());
}
if let Some(node) = node_dir(root, s) {
let node = setting_path(root, &s.languages.node.interpreter).unwrap_or_else(|| node.join(exe("node")));
runtime.commands.insert("node".into(), node);
}
if let Some(ruby) = ruby_interpreter(root, s) {
runtime.commands.insert("ruby".into(), ruby);
}
if let Some(python) = python_interpreter(root, s) {
runtime.commands.insert("python".into(), python);
}
runtime
}
/// A JDK setting: a JDK home, its `bin` or its `bin/java`.
fn jdk_setting(root: &Path, value: &str) -> Option<Result<crate::java::Jdk, PathBuf>> {
let p = setting_path(root, value)?;
+23 -1
Переглянути файл
@@ -1,6 +1,6 @@
use crate::apply::{
apply_to_run_configs, configure_server, jdtls_jdk, maven_command, maven_options, project_jdk, python_interpreter,
ruff_configuration, terminal_activation, tsdk, without_derived,
ruff_configuration, terminal_activation, tool_install_environment, tsdk, without_derived,
};
use crate::python::parse_pip_list;
use crate::{bin_dir, exe, venv_of};
@@ -2246,3 +2246,25 @@ fn plugin_interpreter_targets_route_all_php_node_command_families() {
assert_eq!(config.extras.target.as_deref(), Some(""));
}
}
#[test]
fn tool_installs_resolve_project_relative_sdks_and_leave_path_fallback_unconfigured() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
let mut s = Settings::default();
let defaults = tool_install_environment(root, &s);
assert!(!defaults.commands.contains_key("go"));
assert!(!defaults.commands.contains_key("node"));
assert!(!defaults.commands.contains_key("python"));
assert!(!defaults.env.contains_key("GOROOT"));
s.languages.go.goroot = "go-sdk".into();
s.languages.node.interpreter = "node-sdk/bin/node".into();
s.languages.python.interpreter = "python-sdk/bin/python3.14".into();
s.languages.ruby.interpreter = "ruby-sdk/bin/ruby".into();
let runtime = tool_install_environment(root, &s);
assert_eq!(runtime.commands["go"], root.join("go-sdk/bin").join(if cfg!(windows) { "go.exe" } else { "go" }));
assert_eq!(runtime.env["GOROOT"], root.join("go-sdk").to_string_lossy());
assert_eq!(runtime.commands["node"], root.join("node-sdk/bin/node"));
assert_eq!(runtime.commands["python"], root.join("python-sdk/bin/python3.14"));
assert_eq!(runtime.commands["ruby"], root.join("ruby-sdk/bin/ruby"));
}
+70 -1
Переглянути файл
@@ -421,6 +421,7 @@ pub fn managed_bundle(app_data: &Path, name: &str) -> Option<PathBuf> {
}
/// Installer and detector over one tools directory.
#[derive(Clone)]
pub struct Tools {
root: PathBuf,
/// Search path for system tools (excludes our own dirs).
@@ -432,6 +433,8 @@ pub struct Tools {
custom: BTreeMap<String, PathBuf>,
/// Executables found outside the search path (app bundles), by command.
found: BTreeMap<String, PathBuf>,
runtime_commands: BTreeMap<String, PathBuf>,
runtime_env: BTreeMap<String, String>,
version_timeout: Duration,
/// The project the tools are used for: tools that install into "the active runtime" (gems) run here,
/// so a version manager picks the project's Ruby.
@@ -456,11 +459,41 @@ impl Tools {
platform,
custom: BTreeMap::new(),
found: BTreeMap::new(),
runtime_commands: BTreeMap::new(),
runtime_env: BTreeMap::new(),
version_timeout: Duration::from_secs(4),
work_dir: None,
}
}
/// Applies the project's SDKs to prerequisite lookup, probes and installer children.
pub fn with_runtime(mut self, commands: BTreeMap<String, PathBuf>, env: BTreeMap<String, String>) -> Self {
self.runtime_commands = commands;
self.runtime_env = env;
self
}
fn for_method(&self, method: Method) -> Self {
let commands: &[&str] = match method {
Method::Go { .. } => &["go"],
Method::Npm { .. } => &["node"],
Method::Gem { .. } | Method::GemActive { .. } => &["ruby"],
Method::PipVenv { .. } | Method::PipUser { .. } | Method::PipTarget { .. } => &["python"],
_ => &[],
};
let mut runtime = self.clone();
runtime.runtime_commands.retain(|name, _| commands.contains(&name.as_str()));
runtime.runtime_env.retain(|name, _| name == "GOROOT" && commands.contains(&"go"));
let dirs: Vec<PathBuf> =
runtime.runtime_commands.values().filter_map(|p| p.parent().map(Path::to_path_buf)).collect();
runtime.system_path =
std::env::join_paths(dirs.iter().cloned().chain(std::env::split_paths(&self.system_path)))
.unwrap_or_else(|_| self.system_path.clone());
runtime.child_path = std::env::join_paths(dirs.iter().cloned().chain(std::env::split_paths(&self.child_path)))
.unwrap_or_else(|_| self.child_path.clone());
runtime
}
/// Reports the executables chosen in settings (command → path) as the tools' location.
pub fn with_custom_paths(mut self, custom: BTreeMap<String, PathBuf>) -> Self {
self.custom = custom;
@@ -493,6 +526,9 @@ impl Tools {
}
fn which(&self, cmd: &str) -> Option<PathBuf> {
if let Some(path) = self.runtime_commands.get(cmd) {
return path.is_file().then(|| path.clone());
}
ide_core::tool_path::find_command(cmd, &self.system_path, &self.root)
}
@@ -502,7 +538,7 @@ impl Tools {
fn command(&self, program: impl AsRef<std::ffi::OsStr>) -> Command {
let mut cmd = Command::new(program);
ide_core::process::prepare(&mut cmd).env("PATH", &self.child_path);
ide_core::process::prepare(&mut cmd).envs(&self.runtime_env).env("PATH", &self.child_path);
cmd
}
@@ -524,6 +560,9 @@ impl Tools {
/// Aliases that only open the Store unless the Store's Python is installed, so they count
/// only when they run.
fn python(&self) -> Option<PathBuf> {
if self.runtime_commands.contains_key("python") {
return self.which("python");
}
if self.platform.os != Os::Windows {
return self.which_any(&["python3", "python"]);
}
@@ -664,6 +703,13 @@ impl Tools {
}
fn info_for(&self, name: &str, usage: Option<&Usage>) -> Option<ToolInfo> {
match registry::find(name) {
Some(spec) => self.for_method(spec.method).info_for_runtime(name, usage),
None => self.info_for_runtime(name, usage),
}
}
fn info_for_runtime(&self, name: &str, usage: Option<&Usage>) -> Option<ToolInfo> {
let spec = registry::find(name);
let languages = usage.map(|u| u.languages.clone()).unwrap_or_default();
let install_hint = usage.and_then(|u| u.install_hint.clone());
@@ -868,6 +914,19 @@ impl Tools {
langs: &[LanguageConfig],
cancel: &CancellationToken,
emit: Emit,
) -> IdeResult<ToolInfo> {
match registry::find(name) {
Some(spec) => self.for_method(spec.method).install_for_runtime(name, langs, cancel, emit),
None => self.install_for_runtime(name, langs, cancel, emit),
}
}
fn install_for_runtime(
&self,
name: &str,
langs: &[LanguageConfig],
cancel: &CancellationToken,
emit: Emit,
) -> IdeResult<ToolInfo> {
let spec = registry::find(name).ok_or_else(|| {
let hint = usages(langs).get(name).and_then(|u| u.install_hint.clone());
@@ -1130,6 +1189,9 @@ impl Tools {
if let Some(uv) = self.which("uv") {
let mut c = self.command(&uv);
c.arg("venv").arg(&venv);
if let Some(python) = self.runtime_commands.get("python") {
c.arg("--python").arg(python);
}
run_streamed(c, cancel, emit)?;
let mut c = self.command(&uv);
c.args(["pip", "install", "--python"]).arg(&python).arg(package);
@@ -1371,6 +1433,13 @@ impl Tools {
/// Removes a tool the IDE installed.
pub fn uninstall(&self, name: &str, langs: &[LanguageConfig]) -> IdeResult<ToolInfo> {
match registry::find(name) {
Some(spec) => self.for_method(spec.method).uninstall_for_runtime(name, langs),
None => self.uninstall_for_runtime(name, langs),
}
}
fn uninstall_for_runtime(&self, name: &str, langs: &[LanguageConfig]) -> IdeResult<ToolInfo> {
let spec = registry::find(name).ok_or_else(|| IdeError::not_found(format!("unknown tool `{name}`")))?;
// Uninstalling mid-install would tear down the directory under the running installer.
if INSTALLING.lock().as_ref().is_some_and(|m| m.contains_key(name)) {
+113 -8
Переглянути файл
@@ -438,12 +438,15 @@ esac"#,
#[test]
fn npm_install_uses_tools_prefix() {
let env = Env::new();
let sdk = env._tmp.path().join("selected-sdk/bin");
fs::create_dir_all(&sdk).unwrap();
let log = env.root.parent().unwrap().join("npm-args.txt");
env.script(
&env.sys,
&sdk,
"npm",
&format!(
r#"echo "$@" > '{log}'
r#"node --version >/dev/null || exit 98
echo "$@" > '{log}'
prefix=""; while [ $# -gt 0 ]; do [ "$1" = "--prefix" ] && prefix="$2"; shift; done
/bin/mkdir -p "$prefix/node_modules/.bin" "$prefix/node_modules/bash-language-server"
printf '#!/bin/sh\necho 5.4.0\n' > "$prefix/node_modules/.bin/bash-language-server"
@@ -453,7 +456,14 @@ echo "added 1 package""#,
log = log.display()
),
);
let info = env.tools().install("bash-language-server", &langs(), &CancellationToken::new(), &|_| {}).unwrap();
env.script(&sdk, "node", "exit 0");
env.script(&env.sys, "node", "exit 99");
env.script(&env.sys, "npm", "exit 99");
let tools = env.tools().with_runtime(
BTreeMap::from([("node".into(), sdk.join("node")), ("ruby".into(), env.sys.join("ruby"))]),
BTreeMap::new(),
);
let info = tools.install("bash-language-server", &langs(), &CancellationToken::new(), &|_| {}).unwrap();
assert_eq!(info.status, ToolStatus::Installed);
assert_eq!(info.version.as_deref(), Some("5.4.0"));
let args = fs::read_to_string(&log).unwrap();
@@ -581,14 +591,19 @@ fn elixir_ls_needs_elixir_and_lists_its_debugger() {
#[test]
fn gem_install_wraps_stubs_with_gem_home() {
let env = Env::new();
let sdk = env._tmp.path().join("selected-sdk/bin");
fs::create_dir_all(&sdk).unwrap();
// `gem install --no-document --install-dir <home> --bindir <bin> solargraph`
env.script(
&env.sys,
&sdk,
"gem",
r#"home="$4"; bin="$6"; /bin/mkdir -p "$home/gems/solargraph-0.50.0" "$bin"
printf '#!/bin/sh\necho "$GEM_HOME"\n' > "$bin/solargraph"; /bin/chmod +x "$bin/solargraph""#,
);
let tools = env.tools();
env.script(&sdk, "ruby", "exit 0");
env.script(&env.sys, "ruby", "exit 99");
env.script(&env.sys, "gem", "exit 99");
let tools = env.tools().with_runtime(BTreeMap::from([("ruby".into(), sdk.join("ruby"))]), BTreeMap::new());
let info = tools.install("solargraph", &langs(), &CancellationToken::new(), &|_| {}).unwrap();
assert_eq!(info.status, ToolStatus::Installed);
assert_eq!(info.version.as_deref(), Some("0.50.0"));
@@ -602,16 +617,18 @@ printf '#!/bin/sh\necho "$GEM_HOME"\n' > "$bin/solargraph"; /bin/chmod +x "$bin/
#[test]
fn ruby_lsp_installs_into_the_project_ruby_not_a_private_gem_home() {
let env = Env::new();
let sdk = env._tmp.path().join("selected-sdk/bin");
fs::create_dir_all(&sdk).unwrap();
let project = env._tmp.path().join("project");
fs::create_dir_all(&project).unwrap();
let marker = env._tmp.path().join("installed");
// Homebrew's Ruby: the gem bindir is not on the search path; only the Ruby knows it.
let bindir = env._tmp.path().join("gems/bin");
fs::create_dir_all(&bindir).unwrap();
env.script(&env.sys, "ruby", &format!("echo '{}'", bindir.display()));
env.script(&sdk, "ruby", &format!("echo '{}'", bindir.display()));
// `gem list --exact ruby-lsp` knows the gem once `gem install ruby-lsp` ran, in the cwd it was given.
env.script(
&env.sys,
&sdk,
"gem",
&format!(
r#"case "$1" in
@@ -623,7 +640,10 @@ esac"#,
b = bindir.display()
),
);
let tools = env.tools().with_work_dir(Some(project.clone()));
env.script(&env.sys, "ruby", "exit 99");
env.script(&env.sys, "gem", "exit 99");
let tools = env.tools().with_runtime(BTreeMap::from([("ruby".into(), sdk.join("ruby"))]), BTreeMap::new());
let tools = tools.with_work_dir(Some(project.clone()));
assert_eq!(find(&tools.list(&langs()), "ruby-lsp").status, ToolStatus::Missing);
let info = tools.install("ruby-lsp", &langs(), &CancellationToken::new(), &|_| {}).unwrap();
assert_eq!(info.status, ToolStatus::OnPath);
@@ -800,3 +820,88 @@ fn python_probes_run_in_an_empty_private_directory() {
let dir = env.root.join(".python-cwd");
assert_eq!(out.trim(), dir.canonicalize().unwrap().to_string_lossy());
}
#[cfg(unix)]
#[test]
fn go_installers_use_selected_sdk_instead_of_broken_mise_shim() {
for spec in registry::TOOLS.iter().filter(|s| matches!(s.method, registry::Method::Go { .. })) {
let env = Env::new();
env.script(&env.sys, "go", "echo 'mise ERROR No version is set for shim: go' >&2; exit 1");
let sdk = env._tmp.path().join("selected go");
let log = env._tmp.path().join("go.log");
env.script(
&sdk.join("bin"),
"go",
&format!(
r#"
[ "$GOROOT" = '{sdk}' ] || exit 99
echo "$@" >> '{log}'
case "$1" in
install) printf '#!/bin/sh\necho 1.2.3\n' > "$GOBIN/{command}"; /bin/chmod +x "$GOBIN/{command}" ;;
version) echo 'mod example.com/tool v1.2.3' ;;
esac
"#,
sdk = sdk.display(),
log = log.display(),
command = spec.commands[0]
),
);
let tools = env.tools().with_runtime(
BTreeMap::from([("go".into(), sdk.join("bin/go"))]),
BTreeMap::from([("GOROOT".into(), sdk.to_string_lossy().into_owned())]),
);
let info = tools.install(spec.name, &langs(), &CancellationToken::new(), &|_| {}).unwrap();
assert_eq!(info.status, ToolStatus::Installed, "{}", spec.name);
assert_eq!(info.version.as_deref(), Some("1.2.3"));
let log = fs::read_to_string(log).unwrap();
assert!(log.contains("install -v ") && log.contains("version -m"), "{log}");
tools.uninstall(spec.name, &langs()).unwrap();
assert!(
env.tools()
.install(spec.name, &langs(), &CancellationToken::new(), &|_| {})
.unwrap_err()
.message
.contains("failed")
);
}
}
#[cfg(unix)]
#[test]
fn selected_python_is_used_for_pip_and_uv_even_with_a_versioned_filename() {
let env = Env::new();
env.script(&env.sys, "python3", "exit 99");
let sdk = env._tmp.path().join("python-sdk");
let pip_log = env._tmp.path().join("pip.log");
env.script(
&sdk,
"python3.14",
&format!(
r#"
echo "$@" >> '{log}'
[ "$1" = "-c" ] && exit 1
while [ $# -gt 0 ]; do
if [ "$1" = "--target" ]; then
/bin/mkdir -p "$2/debugpy" "$2/debugpy-1.2.3.dist-info"
/usr/bin/touch "$2/debugpy/__init__.py"
exit 0
fi
shift
done
exit 1
"#,
log = pip_log.display()
),
);
let tools = env.tools().with_runtime(BTreeMap::from([("python".into(), sdk.join("python3.14"))]), BTreeMap::new());
assert_eq!(tools.python(), Some(sdk.join("python3.14")));
let info = tools.install("debugpy", &langs(), &CancellationToken::new(), &|_| {}).unwrap();
assert_eq!(info.status, ToolStatus::Installed);
assert_eq!(info.version.as_deref(), Some("1.2.3"));
assert!(fs::read_to_string(pip_log).unwrap().contains("-m pip install"));
let log = env._tmp.path().join("uv.log");
env.script(&env.sys, "uv", &format!("echo \"$@\" >> '{}'; exit 1", log.display()));
let _ = tools.install("ruff", &langs(), &CancellationToken::new(), &|_| {});
let args = fs::read_to_string(log).unwrap();
assert!(args.contains(&format!("--python {}", sdk.join("python3.14").display())), "{args}");
}
+2 -1
Переглянути файл
@@ -201,8 +201,9 @@ impl SettingsStore {
let mut settings: Settings = serde_json::from_value(merged).unwrap_or_default();
if let Some(root) = self.project_file.as_deref().and_then(Path::parent).and_then(Path::parent)
&& let Ok(Some(workspace)) = crate::workspace::Workspace::load(root)
&& workspace.is_container(root)
{
settings.general.project_name = workspace.name;
settings.general.project_name = workspace.name.clone();
settings.project_structure.content_roots =
workspace.projects.iter().map(|p| ide_core::ipc_path::to_ipc(p)).collect();
}
+97 -49
Переглянути файл
@@ -1,4 +1,5 @@
//! A workspace owns its settings and references project folders without changing them.
//! Explicit workspaces reference project folders without changing them.
//! Attaching folders writes only the primary project's `.openidea/` directory.
use ide_core::{IdeError, IdeResult};
use serde::{Deserialize, Serialize};
use specta::Type;
@@ -22,31 +23,22 @@ fn serialize_projects<S: serde::Serializer>(projects: &[PathBuf], serializer: S)
}
impl Workspace {
/// Creates an automatically named workspace outside all linked projects.
pub fn create_for_project(data_dir: &Path, current: &Path, name: &str, attached: &Path) -> IdeResult<PathBuf> {
let projects = vec![current.to_path_buf(), attached.to_path_buf()];
let base = destination(&data_dir.join("workspaces"))?;
let folder = current.file_name().and_then(|n| n.to_str()).unwrap_or("workspace");
// Validate before creating anything, including when app data is inside a project.
let normalized = normalize_projects(&base, projects.clone(), false)?;
if normalized.iter().any(|p| base.starts_with(p)) {
return Err(IdeError::invalid("Store the workspace outside its linked project folders"));
pub fn is_container(&self, root: &Path) -> bool {
self.projects.first().is_none_or(|p| p != root)
}
pub fn display_name(&self, root: &Path, primary: &str) -> String {
if self.is_container(root) {
return self.name.clone();
}
std::fs::create_dir_all(&base)?;
for suffix in 0.. {
let root = base.join(if suffix == 0 { folder.to_owned() } else { format!("{folder}-{suffix}") });
match std::fs::create_dir(&root) {
Ok(()) => {}
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue,
Err(e) => return Err(e.into()),
}
if let Err(error) = Self::save(&root, name, projects.clone(), true) {
let _ = std::fs::remove_dir(&root);
return Err(error);
}
return Ok(root);
match self.projects.get(1) {
Some(other) => format!(
"{primary}, {}{}",
other.file_name().unwrap_or_default().to_string_lossy(),
if self.projects.len() > 2 { "..." } else { "" }
),
None => primary.to_owned(),
}
unreachable!()
}
pub fn load(root: &Path) -> IdeResult<Option<Self>> {
@@ -61,11 +53,20 @@ impl Workspace {
return Err(IdeError::invalid("Unsupported workspace version"));
}
workspace.name = valid_name(&workspace.name)?;
workspace.projects = normalize_projects(root, workspace.projects, true)?;
workspace.projects = normalize_projects(root, workspace.projects)?;
Ok(Some(workspace))
}
pub fn save(root: &Path, name: &str, projects: Vec<PathBuf>, create: bool) -> IdeResult<Self> {
Self::write(root, name, projects, create, false)
}
/// Creates private attachment metadata in an existing primary project.
pub fn attach(root: &Path, name: &str, projects: Vec<PathBuf>) -> IdeResult<Self> {
Self::write(root, name, projects, true, true)
}
fn write(root: &Path, name: &str, projects: Vec<PathBuf>, create: bool, attach: bool) -> IdeResult<Self> {
let name = valid_name(name)?;
let root = destination(root)?;
let previous = Self::load(&root)?;
@@ -75,14 +76,23 @@ impl Workspace {
if !create && previous.is_none() {
return Err(IdeError::invalid("This folder is not a workspace"));
}
let projects = normalize_projects(&root, projects, true)?;
let projects = normalize_projects(&root, projects)?;
if !attach
&& previous.as_ref().is_none_or(|w| w.is_container(&root))
&& projects.iter().any(|p| root.starts_with(p))
{
return Err(IdeError::invalid("Store the workspace outside its linked project folders"));
}
if attach && projects.first() != Some(&root) {
return Err(IdeError::invalid("The primary project must be the first attached folder"));
}
for path in &projects {
if !path.is_dir() && !previous.as_ref().is_some_and(|w| w.projects.contains(path)) {
return Err(IdeError::invalid(format!("Project folder does not exist: {}", path.display())));
}
}
if projects.iter().any(|p| p == &root || root.starts_with(p)) {
return Err(IdeError::invalid("Store the workspace outside its linked project folders"));
if previous.as_ref().is_some_and(|w| !w.is_container(&root)) && projects.first() != Some(&root) {
return Err(IdeError::invalid("The primary project cannot be detached"));
}
std::fs::create_dir_all(&root)?;
let workspace = Self { version: 1, name, projects };
@@ -118,22 +128,33 @@ fn valid_name(name: &str) -> IdeResult<String> {
Ok(name.to_owned())
}
fn normalize_projects(root: &Path, projects: Vec<PathBuf>, allow_missing: bool) -> IdeResult<Vec<PathBuf>> {
fn normalize_projects(root: &Path, projects: Vec<PathBuf>) -> IdeResult<Vec<PathBuf>> {
let mut result = Vec::new();
for path in projects {
let path = if path.is_absolute() { path } else { root.join(path) };
let path = match dunce::canonicalize(&path) {
Ok(path) if path.is_dir() => path,
Err(e) if allow_missing && e.kind() == std::io::ErrorKind::NotFound => path,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => path,
_ => return Err(IdeError::invalid(format!("Project folder does not exist: {}", path.display()))),
};
if path.join(FILE).exists() {
return Err(IdeError::invalid("Add project folders instead of nesting workspaces"));
if path != root && path.join(FILE).exists() {
let mut nested: Workspace = serde_json::from_slice(&std::fs::read(path.join(FILE))?)
.map_err(|e| IdeError::invalid(format!("Invalid workspace: {e}")))?;
let primary = nested.projects.first().map(|p| if p.is_absolute() { p.clone() } else { path.join(p) });
if let Some(primary) = primary.and_then(|p| dunce::canonicalize(p).ok()) {
nested.projects[0] = primary;
}
if nested.is_container(&path) {
return Err(IdeError::invalid("Add project folders instead of nesting workspaces"));
}
}
if !result.contains(&path) {
result.push(path);
}
}
if result.iter().enumerate().any(|(i, p)| (p == root && i != 0) || (p != root && root.starts_with(p))) {
return Err(IdeError::invalid("Store the workspace outside its linked project folders"));
}
Ok(result)
}
@@ -142,24 +163,51 @@ mod tests {
use super::*;
#[test]
fn automatic_workspace_is_unique_and_outside_projects() {
fn update_cannot_turn_a_container_into_an_attachment() {
let tmp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(tmp.path()).unwrap();
let a = base.join("a");
let b = base.join("b");
std::fs::create_dir(&a).unwrap();
std::fs::create_dir(&b).unwrap();
let data = base.join("data");
let root = Workspace::create_for_project(&data, &a, "A", &b).unwrap();
let workspace = Workspace::load(&root).unwrap().unwrap();
assert_eq!(workspace.name, "A");
assert_eq!(workspace.projects, vec![a.clone(), b.clone()]);
assert_eq!(root, data.join("workspaces/a"));
let other = Workspace::create_for_project(&data, &a, "A", &b).unwrap();
assert_eq!(other, data.join("workspaces/a-1"));
assert!(Workspace::create_for_project(&a.join("data"), &a, "A", &b).is_err());
assert!(!a.join("data").exists());
assert!(!a.join(FILE).exists());
let root = dunce::canonicalize(tmp.path()).unwrap();
Workspace::save(&root, "Container", vec![], true).unwrap();
let before = std::fs::read(root.join(FILE)).unwrap();
assert!(Workspace::save(&root, "Attached", vec![root.clone()], false).is_err());
assert_eq!(std::fs::read(root.join(FILE)).unwrap(), before);
}
#[test]
fn create_workspace_refuses_a_location_equal_to_any_member() {
let tmp = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(tmp.path()).unwrap();
let other = root.join("other");
std::fs::create_dir(&other).unwrap();
for projects in [vec![root.clone(), other.clone()], vec![other, root.clone()]] {
let error = Workspace::save(&root, "Invalid", projects, true).unwrap_err();
assert_eq!(error.message, "Store the workspace outside its linked project folders");
assert!(!root.join(FILE).exists());
}
}
#[test]
fn attachments_keep_the_primary_and_allow_attached_folders() {
let tmp = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(tmp.path()).unwrap();
let a = root.join("a");
let b = root.join("b");
let c = root.join("c");
for path in [&a, &b, &c] {
std::fs::create_dir(path).unwrap();
}
let nested = Workspace::attach(&b, "B", vec![b.clone(), c.clone()]).unwrap();
assert!(!nested.is_container(&b));
let saved = Workspace::attach(&a, "A", vec![a.clone(), b.clone()]).unwrap();
assert_eq!(Workspace::load(&a).unwrap(), Some(saved.clone()));
assert_eq!(saved.display_name(&a, "Primary"), "Primary, b");
assert!(Workspace::save(&a, "A", vec![b.clone()], false).is_err());
let saved = Workspace::save(&a, "A", vec![a.clone(), b, c], false).unwrap();
assert_eq!(saved.display_name(&a, "Primary"), "Primary, b...");
let container = root.join("container");
Workspace::save(&container, "Container", vec![], true).unwrap();
assert!(Workspace::save(&a, "A", vec![a.clone(), container], false).is_err());
assert!(Workspace::save(&a, "A", vec![root.clone()], false).is_err());
assert!(Workspace::save(&root.join("other"), "Other", vec![a, root], true).is_err());
}
#[test]
+3
Переглянути файл
@@ -24,3 +24,6 @@ multiple-versions = "warn"
unknown-registry = "deny"
unknown-git = "deny"
allow-registry = ["https://github.com/rust-lang/crates.io-index"]
# SQLx's unreleased SQLite dependency ceiling fix, pinned in Cargo.toml.
allow-git = ["https://github.com/transact-rs/sqlx"]
required-git-spec = "rev"
+159
Переглянути файл
@@ -0,0 +1,159 @@
import { expect, ipcCalls, openFromTree, stubDesktop, test } from "./fixtures";
test.use({ video: "on" });
test("Attach preserves unsaved tabs and detaches back to the plain project", async ({ workbench: page }) => {
const editor = await openFromTree(page, "README.md");
await editor.locator(".cm-content").click();
await page.keyboard.press("Meta+End");
await page.keyboard.type("unsaved attach text");
await page.screenshot({ path: test.info().outputPath("plain-project.png"), animations: "disabled" });
await stubDesktop(page);
await page.evaluate(async () => {
const module = "/src/platform/project.ts";
const { useProject } = await import(/* @vite-ignore */ module);
const project = useProject.getState().project;
useProject.setState({
settings: { ...project.settings, general: { ...project.settings.general, openProjectIn: "ask" } },
});
const attached = {
...project,
displayName: "acme-api, other",
workspace: { version: 1, name: project.name, projects: [project.root, "/dev/other"] },
};
let current = project;
window.__ipc.handlers.project_trust_status = ({ path }) => ({ root: path, trusted: true, decided: true });
window.__ipc.handlers.workspace_attach = () => {
current = attached;
return project.root;
};
window.__ipc.handlers.project_current = () => current;
window.__ipc.handlers.menu_refresh = () => null;
window.__ipc.handlers.project_rename = ({ name }) => {
current = { ...attached, name, displayName: `${name}, other` };
return current;
};
window.__ipc.handlers.workspace_update = () => {
current = project;
return project;
};
window.__ipc.handlers.project_roots = () => ({ folders: [] });
window.__ipc.handlers.fs_read_dir = () => [];
window.__ipc.handlers.run_configs = () => [];
window.__ipc.handlers.recent_projects = () => [
{ path: current.root, name: current.displayName || current.name, branch: null, openedAtMs: Date.now() },
];
const windows = "/src/features/app/windows.ts";
void (await import(/* @vite-ignore */ windows)).openProjectWithPolicy("/dev/other");
});
const dialog = page.getByRole("dialog", { name: "Open Project" });
await expect(dialog).toBeVisible();
await page.screenshot({ path: test.info().outputPath("attach-dialog.png"), animations: "disabled" });
await dialog.getByRole("button", { name: "Attach", exact: true }).click();
await expect(
page.locator("header").first().getByRole("button", { name: "acme-api, other", exact: true }),
).toBeVisible();
await expect(page.getByRole("treeitem", { name: /^other / })).toBeVisible();
await expect(editor.locator(".cm-content")).toContainText("unsaved attach text");
expect(await ipcCalls(page, "open_project")).toHaveLength(0);
expect(await ipcCalls(page, "workspace_attach")).toHaveLength(1);
await page.evaluate(async () => {
const actions = "/src/platform/actions.ts";
void (await import(/* @vite-ignore */ actions)).executeAction("file.renameProject");
});
const rename = page.getByRole("dialog", { name: "Rename Project", exact: true });
await expect(rename.getByRole("textbox")).toHaveValue("acme-api");
await rename.getByRole("button", { name: "Rename", exact: true }).click();
await expect(
page.locator("header").first().getByRole("button", { name: "acme-api, other", exact: true }),
).toBeVisible();
expect((await ipcCalls(page, "project_rename"))[0]!.name).toBe("acme-api");
await page.screenshot({ path: test.info().outputPath("attached-project.png"), animations: "disabled" });
await page.locator("header").first().getByRole("button", { name: "acme-api, other", exact: true }).click();
await expect(page.getByText("/dev/acme-api", { exact: true }).last()).toBeVisible();
await page.screenshot({ path: test.info().outputPath("attached-recent.png"), animations: "disabled" });
await page.keyboard.press("Escape");
await page.getByRole("treeitem", { name: /^other / }).click({ button: "right" });
await expect(page.getByRole("menuitem", { name: "Detach Project", exact: true })).toBeVisible();
await expect(page.getByRole("menuitem", { name: "Remove from Workspace" })).toHaveCount(0);
await page.screenshot({ path: test.info().outputPath("detach-menu.png"), animations: "disabled" });
await page.getByRole("menuitem", { name: "Detach Project", exact: true }).click();
const detach = page.getByRole("dialog", { name: "Detach Project" });
await expect(detach).toBeVisible();
await detach.getByRole("button", { name: "Detach", exact: true }).click();
await expect(page.locator("header").first().getByRole("button", { name: "acme-api", exact: true })).toBeVisible();
await expect(editor.locator(".cm-content")).toContainText("unsaved attach text");
await expect(page.getByRole("treeitem", { name: /^other / })).toHaveCount(0);
await page.screenshot({ path: test.info().outputPath("detached-project.png"), animations: "disabled" });
});
test("restricting an attached folder leaves the current project untouched", async ({ workbench: page }) => {
await stubDesktop(page);
await page.evaluate(async () => {
const projectModule = "/src/platform/project.ts";
const { useProject } = await import(/* @vite-ignore */ projectModule);
useProject.setState({ settings: { ...useProject.getState().settings, general: { openProjectIn: "ask" } } });
let decided = false;
window.__ipc.handlers.project_trust_status = ({ path }) => ({ root: path, trusted: false, decided });
window.__ipc.handlers.project_trust_set = () => {
decided = true;
};
const module = "/src/features/app/windows.ts";
void (await import(/* @vite-ignore */ module)).openProjectWithPolicy("/dev/untrusted");
});
await page.getByRole("dialog", { name: "Open Project" }).getByRole("button", { name: "Attach", exact: true }).click();
const trust = page.getByRole("dialog", { name: "Trust and Open Project?" });
await expect(trust).toBeVisible();
await trust.getByRole("button", { name: "Preview in Restricted Mode" }).click();
await expect(trust).toBeHidden();
expect(await ipcCalls(page, "workspace_attach")).toHaveLength(0);
expect(await ipcCalls(page, "open_project")).toHaveLength(0);
await expect(page.locator("header").first().getByRole("button", { name: "acme-api", exact: true })).toBeVisible();
});
test("restricted attachments can be trusted individually from the banner", async ({ workbench: page }) => {
await stubDesktop(page);
await page.evaluate(async () => {
const m = "/src/platform/project.ts";
const { useProject } = await import(/* @vite-ignore */ m);
const primary = useProject.getState().project;
let current = {
...primary,
trusted: false,
displayName: "acme-api, other...",
workspace: { version: 1, name: primary.name, projects: [primary.root, "/dev/other", "/dev/third"] },
};
const trusted = new Set([primary.root]);
window.__ipc.handlers.project_trust_status = ({ path }) => ({
root: path,
trusted: trusted.has(path),
decided: true,
});
window.__ipc.handlers.project_trust_set = ({ path, trusted: allow }) => {
if (allow) trusted.add(path);
current = { ...current, trusted: current.workspace.projects.every((path) => trusted.has(path)) };
};
window.__ipc.handlers.project_current = () => current;
window.__ipc.handlers.fs_read_dir = () => [];
window.__ipc.handlers.project_roots = () => ({ folders: [] });
window.__ipc.handlers.run_configs = () => [];
useProject.setState({ project: current });
});
const banner = page.getByRole("status").filter({ hasText: "Restricted Mode" });
await expect(banner).toContainText("/dev/other");
await page.screenshot({ path: test.info().outputPath("restricted-member.png"), animations: "disabled" });
await banner.getByRole("button", { name: "Trust Project" }).click();
const dialog = page.getByRole("dialog", { name: "Trust and Open Project?" });
await expect(dialog).toContainText("/dev/other");
await dialog.getByRole("button", { name: "Don't Open" }).click();
expect(await ipcCalls(page, "project_trust_set")).toHaveLength(0);
await banner.getByRole("button", { name: "Trust Project" }).click();
await dialog.getByRole("button", { name: "Trust Project", exact: true }).click();
await expect(banner).toContainText("/dev/third");
expect(await ipcCalls(page, "project_trust_set")).toEqual([{ path: "/dev/other", trusted: true, folder: false }]);
await banner.getByRole("button", { name: "Trust Project" }).click();
await expect(dialog).toContainText("/dev/third");
await dialog.getByRole("button", { name: "Trust Project", exact: true }).click();
await expect(banner).toBeHidden();
await page.screenshot({ path: test.info().outputPath("trusted-members.png"), animations: "disabled" });
});
+1 -1
Переглянути файл
@@ -300,7 +300,7 @@ test.describe("10,000-line files", () => {
await expect.poll(async () => (await rendered(page)).b.words).toContainEqual(["computeFast", "modified"]);
}
// The last difference is reachable and still highlighted.
await page.keyboard.press("Meta+ArrowDown");
await page.keyboard.press("Meta+End");
await page.keyboard.press("Shift+F7");
await expect(counter(page)).toHaveText("42 of 42 differences");
if (opts.mode === "unified") {
+34
Переглянути файл
@@ -0,0 +1,34 @@
import { expect, openFromTree, test } from "./fixtures";
test("an open editor leaves nothing for the page itself to scroll", async ({ workbench: page }) => {
await openFromTree(page, "README.md");
const page_ = await page.evaluate(() => {
window.scrollBy(0, 100);
const root = document.documentElement;
return { scrollY: window.scrollY, scrollHeight: root.scrollHeight, clientHeight: root.clientHeight };
});
expect(page_.scrollY).toBe(0);
expect(page_.scrollHeight).toBe(page_.clientHeight);
});
test("scrolling to where the editor already is keeps the page in place", async ({ workbench: page }) => {
const editor = await openFromTree(page, "README.md");
await expect(editor.locator(".cm-content")).toBeVisible();
const scrollY = await page.evaluate(async () => {
const content = document.querySelector(".cm-content") as HTMLElement & {
cmTile?: { view: never };
cmView?: { view: never };
};
const view = (content.cmTile ?? content.cmView)!.view as {
constructor: { scrollIntoView(pos: number, options: { y: string }): unknown };
dispatch(spec: { effects: unknown }): void;
requestMeasure(): void;
};
for (let i = 0; i < 2; i++) {
view.dispatch({ effects: view.constructor.scrollIntoView(0, { y: "start" }) });
await new Promise((resolve) => requestAnimationFrame(() => setTimeout(resolve)));
}
return window.scrollY;
});
expect(scrollY).toBe(0);
});
+2 -1
Переглянути файл
@@ -122,7 +122,8 @@ test("font picker supports manual families and CJK fallback in browser developme
expect(interLoaded).toBe(true);
await family.fill("Inter");
await family.press("Enter");
await expect(dialog.getByLabel("Font preview")).toHaveCSS("font-family", /^"Inter Variable",/);
// Computed styles drop redundant quotes around single-token families ("Inter" -> Inter).
await expect(dialog.getByLabel("Font preview")).toHaveCSS("font-family", /^Inter, "Inter Variable",/);
const fallback = dialog.getByRole("combobox", { name: "Fallback font", exact: true });
await family.fill("Maple Mono NF");
await family.press("Enter");
+52
Переглянути файл
@@ -0,0 +1,52 @@
import { expect, test } from "./fixtures";
test("Updates shows check status and keeps manual checks available when automatic checks are off", async ({
workbench: page,
}) => {
await page.evaluate(async () => {
const ipcPath = "/src/platform/ipc.ts";
const actionsPath = "/src/platform/actions.ts";
const { commands } = await import(/* @vite-ignore */ ipcPath);
const { registerAction, executeAction } = await import(/* @vite-ignore */ actionsPath);
Object.assign(commands, {
appBuildInfo: async () => ({ version: "0.1.39", updates: true }),
appUpdateStatus: async () => ({ status: "ok", data: { lastChecked: null, checking: false } }),
});
registerAction({
id: "app.checkForUpdates",
title: "Check for Updates…",
run: () => document.body.setAttribute("data-update-checked", "true"),
});
await executeAction("file.settings", "general");
});
const dialog = page.getByRole("dialog", { name: "Settings", exact: true });
await expect(dialog).toBeVisible();
await dialog.getByRole("textbox", { name: "Search settings" }).fill("update");
await dialog.getByRole("treeitem", { name: "Updates", exact: true }).click();
await expect(dialog.getByText("0.1.39", { exact: true })).toBeVisible();
await expect(dialog.getByText("Never", { exact: true })).toBeVisible();
const automatic = dialog.getByRole("checkbox", { name: "Check for updates automatically" });
await expect(automatic).toBeChecked();
await automatic.uncheck();
await dialog.getByRole("button", { name: "Apply", exact: true }).click();
await expect(automatic).not.toBeChecked();
await dialog.getByRole("button", { name: "Check Now", exact: true }).click();
await expect(page.locator("body")).toHaveAttribute("data-update-checked", "true");
});
test("builds without update endpoints hide Updates from settings and search", async ({ workbench: page }) => {
await page.evaluate(async () => {
const ipcPath = "/src/platform/ipc.ts";
const actionsPath = "/src/platform/actions.ts";
const { commands } = await import(/* @vite-ignore */ ipcPath);
commands.appBuildInfo = async () => ({ version: "0.1.39", updates: false });
const { executeAction } = await import(/* @vite-ignore */ actionsPath);
await executeAction("file.settings", "general");
});
const dialog = page.getByRole("dialog", { name: "Settings", exact: true });
await expect(dialog).toBeVisible();
await expect(dialog.getByRole("treeitem", { name: "Updates", exact: true })).toHaveCount(0);
await expect(dialog.getByText("Update source", { exact: true })).toHaveCount(0);
await dialog.getByRole("textbox", { name: "Search settings" }).fill("update");
await expect(dialog.getByRole("treeitem", { name: "Updates", exact: true })).toHaveCount(0);
});
+17 -8
Переглянути файл
@@ -85,7 +85,7 @@ pub async fn open_project(window: Window, path: PathBuf) -> IdeResult<ProjectInf
.await
.map_err(|e| IdeError::internal(e.to_string()))??;
let info = project_info(&project);
let _ = window.set_title(&info.name);
let _ = window.set_title(&info.display_name);
window.state::<AppState>().sink.emit(ide_core::IdeEvent::WindowGroupsChanged);
// Every project window is part of the session reopened at the next start.
crate::window_groups::persist(window.app_handle()).await?;
@@ -121,14 +121,19 @@ fn project_info(project: &crate::state::Project) -> ProjectInfo {
pub fn project_rename(window: Window, state: State<'_, AppState>, name: String) -> IdeResult<ProjectInfo> {
let project = state.project(window.label())?;
let name = name.trim();
if let Some(workspace) = ide_workspace::workspace::Workspace::load(&project.root)? {
return ide_host::ops::project::save_workspace(&state.host, window.label(), name, workspace.projects);
if let Some(workspace) = ide_workspace::workspace::Workspace::load(&project.root)?
&& workspace.is_container(&project.root)
{
ide_host::ops::project::save_workspace(&state.host, window.label(), name, workspace.projects)?;
} else {
let value = if name.is_empty() { serde_json::Value::Null } else { serde_json::Value::String(name.to_owned()) };
project.settings.set(SettingsScope::Project, "general.projectName", value)?;
}
let value = if name.is_empty() { serde_json::Value::Null } else { serde_json::Value::String(name.to_owned()) };
project.settings.set(SettingsScope::Project, "general.projectName", value)?;
state.recent.rename(&project.root, (!name.is_empty()).then_some(name))?;
crate::jump_list::refresh(&state.app, state.recent.list());
Ok(project_info(&project))
let info = project_info(&project);
state.record_project(&project)?;
let _ = window.set_title(&info.display_name);
state.sink.emit(ide_core::IdeEvent::WindowGroupsChanged);
Ok(info)
}
// Not on the main thread: closing stops the project's language servers, runs and file watcher.
@@ -184,6 +189,9 @@ pub fn settings_set(
if key == "mcpServer" || key.starts_with("mcpServer.") {
crate::commands::mcp::apply(&state);
}
if !applied.project_scope {
state.updates.wake.notify_one();
}
// A project value concerns only that project's window (and its settings window).
let event = ide_core::IdeEvent::SettingsChanged { key };
if applied.project_scope {
@@ -238,6 +246,7 @@ pub async fn settings_import(window: Window, state: State<'_, AppState>, path: P
crate::commands::ssh::apply_ssh_settings(&state);
crate::commands::mcp::apply(&state);
state.host.apply_proxy();
state.updates.wake.notify_one();
state.sink.emit(ide_core::IdeEvent::SettingsChanged { key: String::new() });
let settings = ide_host::ops::project::settings(&state.host, window.label());
Ok(SettingsImport { settings, storage })
+33
Переглянути файл
@@ -31,6 +31,39 @@ pub async fn clipboard_set_file_list(app: AppHandle, paths: Vec<PathBuf>) -> Ide
with_clipboard(app, move || Ok(ide_clipboard::set_files(&paths))).await
}
/// The clipboard's image as a PNG data URL, for a paste whose event carried no
/// files: WebKitGTK leaves `clipboardData` empty for a raw image (a screenshot).
/// None when the clipboard holds no image, and always on other platforms.
#[tauri::command]
#[specta::specta]
pub async fn clipboard_image(app: AppHandle) -> IdeResult<Option<String>> {
#[cfg(target_os = "linux")]
{
use base64::Engine;
let (tx, rx) = tokio::sync::oneshot::channel();
app.run_on_main_thread(move || {
let sender = std::cell::Cell::new(Some(tx));
gtk::Clipboard::get(&gtk::gdk::SELECTION_CLIPBOARD).request_image(move |_, pixbuf| {
let png = pixbuf.and_then(|image| image.save_to_bufferv("png", &[]).ok());
if let Some(sender) = sender.take() {
let _ = sender.send(png);
}
});
})
.map_err(|error| {
ide_core::IdeError::internal(format!("Cannot dispatch clipboard access to the main thread: {error}"))
})?;
let png = rx.await.ok().flatten();
Ok(png
.map(|bytes| format!("data:image/png;base64,{}", base64::engine::general_purpose::STANDARD.encode(bytes))))
}
#[cfg(not(target_os = "linux"))]
{
let _ = app;
Ok(None)
}
}
/// AppKit and WebKit share the general pasteboard, so a worker-side mutex cannot
/// protect its type cache. Await the main thread without blocking a command thread.
async fn with_clipboard<T: Send + 'static>(
+4 -1
Переглянути файл
@@ -166,6 +166,7 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
fs::fs_read_text,
clipboard::clipboard_file_list,
clipboard::clipboard_has_files,
clipboard::clipboard_image,
clipboard::clipboard_set_file_list,
fonts::system_font_families,
doc::doc_open,
@@ -461,7 +462,9 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
window::app_cli_uninstall,
window::app_build_info,
window::app_check_update,
window::app_startup_update_check,
window::app_update_window_ready,
window::app_update_status,
window::app_update_announcement,
window::app_install_update,
debug::debug_exception_filters,
debug::debug_set_exception_breakpoints,
+33 -45
Переглянути файл
@@ -384,24 +384,10 @@ pub fn app_build_info(app: AppHandle) -> BuildInfo {
}
}
#[derive(Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct UpdateInfo {
pub version: String,
pub current_version: String,
pub notes: Option<String>,
pub date: Option<String>,
}
use ide_core::updates::UpdateInfo;
pub use ide_core::updates::{UpdateCheck, UpdateSource, UpdateStatus};
#[derive(Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct UpdateCheck {
/// False when no update endpoint is configured (no request was made).
pub enabled: bool,
pub update: Option<UpdateInfo>,
}
fn update_endpoint_env() -> Option<String> {
pub(crate) fn update_endpoint_env() -> Option<String> {
std::env::var("OPENIDEA_UPDATE_ENDPOINT").ok().filter(|s| !s.trim().is_empty())
}
@@ -412,17 +398,6 @@ pub fn updates_configured<R: tauri::Runtime>(app: &AppHandle<R>) -> bool {
!config_endpoints(app).is_empty() || update_endpoint_env().is_some()
}
/// Where updates are downloaded from (System Settings › Updates).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum UpdateSource {
/// The GitHub releases named in tauri.conf.json.
#[default]
Github,
/// The CNB mirror of the same releases, for networks where GitHub is slow.
Cnb,
}
const CNB_ENDPOINT: &str = "https://cnb.cool/l0ng-ai/openidea/-/releases/latest/download/latest.json";
fn config_endpoints<R: tauri::Runtime>(app: &AppHandle<R>) -> Vec<String> {
@@ -476,10 +451,17 @@ fn updater(app: &AppHandle, source: UpdateSource) -> IdeResult<Option<tauri_plug
#[tauri::command]
#[specta::specta]
pub async fn app_check_update(app: AppHandle, source: UpdateSource) -> IdeResult<UpdateCheck> {
let Some(updater) = updater(&app, source)? else {
crate::updates::check(&app, Some(source)).await
}
pub(crate) async fn check_update(app: &AppHandle, source: UpdateSource) -> IdeResult<UpdateCheck> {
let Some(updater) = updater(app, source)? else {
return Ok(UpdateCheck { enabled: false, update: None });
};
let update = updater.check().await.map_err(|e| IdeError::unavailable(e.to_string()))?;
let update = tokio::time::timeout(std::time::Duration::from_secs(60), updater.check())
.await
.map_err(|e| IdeError::unavailable(e.to_string()))?
.map_err(|e| IdeError::unavailable(e.to_string()))?;
Ok(UpdateCheck {
enabled: true,
update: update.map(|u| UpdateInfo {
@@ -491,23 +473,29 @@ pub async fn app_check_update(app: AppHandle, source: UpdateSource) -> IdeResult
})
}
/// The background check made once per process when the first window starts;
/// later calls (other windows) and debug builds get `None`. Failures are logged,
/// not reported: the user didn't ask for this check.
#[tauri::command]
#[specta::specta]
pub async fn app_startup_update_check(app: AppHandle, source: UpdateSource) -> Option<UpdateInfo> {
static DONE: AtomicBool = AtomicBool::new(false);
if cfg!(debug_assertions) || DONE.swap(true, Ordering::SeqCst) {
return None;
}
match app_check_update(app, source).await {
Ok(check) => check.update,
Err(e) => {
tracing::warn!("startup update check failed: {e}");
None
}
}
pub fn app_update_window_ready(
app: AppHandle,
window: WebviewWindow,
ready: bool,
system_locale: String,
) -> IdeResult<()> {
crate::updates::window_ready(&app, window.label(), ready, system_locale);
Ok(())
}
#[tauri::command]
#[specta::specta]
pub fn app_update_status(state: State<'_, AppState>) -> IdeResult<UpdateStatus> {
Ok(state.updates.state.lock().policy.status.clone())
}
#[tauri::command]
#[specta::specta]
pub fn app_update_announcement(state: State<'_, AppState>, version: String, automatic: bool) -> IdeResult<bool> {
let claimed = state.updates.state.lock().policy.announce(&version);
Ok(!automatic || claimed)
}
/// Progress of [`app_install_update`], streamed to the UI's background task.
+14 -4
Переглянути файл
@@ -42,7 +42,10 @@ pub async fn workspace_update(window: WebviewWindow, name: String, projects: Vec
})
.await
.map_err(|e| IdeError::internal(e.to_string()))??;
let _ = window.set_title(&info.name);
let state = window.state::<AppState>();
let project = state.project(window.label())?;
state.record_project(&project)?;
let _ = window.set_title(&info.display_name);
window.state::<AppState>().sink.emit(ide_core::IdeEvent::WindowGroupsChanged);
Ok(info)
}
@@ -52,7 +55,14 @@ pub async fn workspace_update(window: WebviewWindow, name: String, projects: Vec
pub async fn workspace_attach(window: WebviewWindow, path: PathBuf) -> IdeResult<ide_core::IpcPath> {
let host = window.state::<AppState>().host.clone();
let label = window.label().to_owned();
tauri::async_runtime::spawn_blocking(move || ide_host::ops::project::attach_workspace(&host, &label, &path))
.await
.map_err(|e| IdeError::internal(e.to_string()))?
let root =
tauri::async_runtime::spawn_blocking(move || ide_host::ops::project::attach_workspace(&host, &label, &path))
.await
.map_err(|e| IdeError::internal(e.to_string()))??;
let state = window.state::<AppState>();
let project = state.project(window.label())?;
state.record_project(&project)?;
let _ = window.set_title(&ide_host::ops::project::info(&project).display_name);
state.sink.emit(ide_core::IdeEvent::WindowGroupsChanged);
Ok(root)
}
+2
Переглянути файл
@@ -31,6 +31,7 @@ mod state;
mod theme_frame;
#[cfg(target_os = "macos")]
mod titlebar;
mod updates;
mod window_groups;
#[cfg(any(windows, test))]
mod window_work_area;
@@ -240,6 +241,7 @@ pub fn run() {
window_groups::destroyed(window.app_handle(), window.label());
windows::close_auxiliary_windows(window.app_handle(), window.label());
if let Some(state) = window.try_state::<AppState>() {
state.updates.forget_window(window.label());
state.close_project(window.label());
state.plugins.forget_client(window.label());
}
+1
Переглянути файл
@@ -224,6 +224,7 @@ pub fn spec(os: Os) -> Vec<Entry> {
act("file.new", "New…"),
act("file.newScratchFile", "New Scratch File…"),
act("file.openProject", "Open…"),
act("project.attach", "Attach Project…"),
act("file.openFile", "Open File…"),
act("file.openInNewWindow", "Open in New Window…"),
sub(
+1 -1
Переглянути файл
@@ -528,7 +528,7 @@ pub async fn remote_connect(
peer.request("invoke", call, None).await.map_err(ide_host::rpc::error_from_reply)?;
// As the server resolved it (symlinks, a trailing `/`): the frontend compares it with the project's.
let root = serde_json::to_value(&project.root).ok().and_then(|v| v.as_str().map(str::to_owned)).unwrap_or(root);
let _ = window.set_title(&format!("{} [{title_tag}]", project.name));
let _ = window.set_title(&format!("{} [{title_tag}]", project.display_name));
let connection = Arc::new(Connection {
peer,
target: target.clone(),
+17 -7
Переглянути файл
@@ -15,6 +15,7 @@ pub struct AppState {
pub app: AppHandle,
pub host: Arc<Host>,
pub startup: Startup,
pub updates: crate::updates::Updates,
pub recent: RecentProjects,
/// Plugins (`ide_host::plugins`), shared by all windows.
pub plugins: Arc<ide_host::plugins::PluginHost>,
@@ -99,6 +100,7 @@ impl AppState {
}));
Ok(Self {
recent: RecentProjects::load(&config_dir),
updates: Default::default(),
askpass: start_askpass(&app),
sink: global_sink,
plugins: crate::commands::plugin::create_host(&app, &data_dir, &host)?,
@@ -142,16 +144,24 @@ impl AppState {
// A local project replaces a remote one in this window.
self.remote_dev.disconnect(window);
let project = self.host.open_project(window, root)?;
let branch = project.repos.read().primary().and_then(|r| r.branch_info().ok()).and_then(|b| b.head);
self.recent.touch(&project.root, branch)?;
let display_name = project.settings.effective().general.project_name;
if !display_name.trim().is_empty() {
self.recent.rename(&project.root, Some(display_name.trim()))?;
}
crate::jump_list::refresh(&self.app, self.recent.list());
self.record_project(&project)?;
Ok(project)
}
pub fn record_project(&self, project: &Project) -> IdeResult<()> {
let info = ide_host::ops::project::info(project);
let attached = info.workspace.as_ref().is_some_and(|w| !w.is_container(&project.root));
let branch = if attached {
None
} else {
project.repos.read().primary().and_then(|r| r.branch_info().ok()).and_then(|b| b.head)
};
self.recent.touch(&project.root, branch)?;
self.recent.rename(&project.root, Some(&info.display_name))?;
crate::jump_list::refresh(&self.app, self.recent.list());
Ok(())
}
/// Opens `window` for editing the loose file `file` (LightEdit); not a recent project.
pub fn open_light(&self, window: &str, file: &Path) -> IdeResult<Arc<Project>> {
self.remote_dev.disconnect(window);
+176
Переглянути файл
@@ -0,0 +1,176 @@
//! Desktop updater coordination shared by all webviews.
use crate::commands::window::{UpdateSource, check_update, update_endpoint_env, updates_configured};
use crate::state::AppState;
use ide_core::updates::{UpdateCheck, UpdatePolicy};
use ide_core::{IdeEvent, IdeResult};
use parking_lot::Mutex;
use std::collections::HashSet;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Instant, SystemTime, UNIX_EPOCH};
use tauri::{AppHandle, Manager};
use tokio::sync::Notify;
#[derive(Default)]
pub struct Updates {
started: AtomicBool,
ready: Mutex<HashSet<String>>,
system_locale: Mutex<String>,
pub wake: Notify,
gate: tokio::sync::Mutex<()>,
pub state: Mutex<CheckState>,
}
#[derive(Default)]
pub struct CheckState {
pub policy: UpdatePolicy,
revision: u64,
result: Option<IdeResult<UpdateCheck>>,
}
impl Updates {
pub fn forget_window(&self, window: &str) {
self.ready.lock().remove(window);
}
}
fn automatic_enabled(app: &AppHandle) -> bool {
updates_configured(app) && app.state::<AppState>().global_settings.effective().general.auto_check_updates
}
/// Called after an ordinary window has installed its event handlers. The task survives window closes and HMR.
pub fn window_ready(app: &AppHandle, window: &str, ready: bool, system_locale: String) {
if !ready {
app.state::<AppState>().updates.forget_window(window);
return;
}
app.state::<AppState>().updates.ready.lock().insert(window.to_owned());
*app.state::<AppState>().updates.system_locale.lock() = system_locale;
if !updates_configured(app) || (cfg!(debug_assertions) && update_endpoint_env().is_none()) {
return;
}
if app.state::<AppState>().updates.started.swap(true, Ordering::SeqCst) {
announce_available(app);
return;
}
let app = app.clone();
tauri::async_runtime::spawn(async move {
loop {
let state = app.state::<AppState>();
let wake = state.updates.wake.notified();
let delay = automatic_enabled(&app).then(|| state.updates.state.lock().policy.due_in(Instant::now()));
if delay.is_some_and(|d| d.is_zero()) {
if let Err(error) = check(&app, None).await {
tracing::warn!(%error, "automatic update check failed");
}
continue;
}
match delay {
Some(delay) => tokio::select! {
_ = tokio::time::sleep(delay) => {},
_ = wake => {},
},
None => wake.await,
}
}
});
}
/// `None` is an automatic check; explicit sources are manual checks and always return their result.
pub async fn check(app: &AppHandle, source: Option<UpdateSource>) -> IdeResult<UpdateCheck> {
let state = app.state::<AppState>();
let revision = state.updates.state.lock().revision;
let _gate = state.updates.gate.lock().await;
let automatic = source.is_none();
{
let current = state.updates.state.lock();
if !automatic
&& current.revision != revision
&& let Some(result) = &current.result
{
return result.clone();
}
if automatic && (!automatic_enabled(app) || !current.policy.due_in(Instant::now()).is_zero()) {
return Ok(UpdateCheck { enabled: updates_configured(app), update: None });
}
}
let settings = state.global_settings.effective();
let source = source.unwrap_or_else(|| {
UpdateSource::resolve(
&settings.general.update_source,
&settings.appearance.locale,
&state.updates.system_locale.lock(),
)
});
state.updates.state.lock().policy.begin(Instant::now());
emit_status(&state);
let result = check_update(app, source).await;
let checked_at = result
.as_ref()
.ok()
.filter(|check| check.enabled)
.map(|_| SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default().as_secs_f64() * 1000.0);
{
let mut current = state.updates.state.lock();
current.policy.finish(checked_at);
current.revision += 1;
current.result = Some(result.clone());
}
emit_status(&state);
state.updates.wake.notify_one();
if automatic {
announce_available(app);
}
result
}
fn emit_status(state: &AppState) {
let status = state.updates.state.lock().policy.status.clone();
state.sink.emit(IdeEvent::UpdateStatusChanged { status });
}
fn announce_available(app: &AppHandle) {
if !automatic_enabled(app) {
return;
}
let state = app.state::<AppState>();
let owner = {
let mut ready = state.updates.ready.lock();
ready.retain(|label| app.get_webview_window(label).is_some());
let focused = crate::windows::target_window(app);
ready_owner(focused.as_ref().map(|window| window.label()), &crate::windows::project_window_labels(app), &ready)
};
let Some(owner) = owner else { return };
let update = {
let current = state.updates.state.lock();
let update = current.result.as_ref().and_then(|r| r.as_ref().ok()).and_then(|r| r.update.clone());
update.filter(|update| !current.policy.announced(&update.version))
};
if let Some(update) = update {
state.window_sink(&owner).emit(IdeEvent::UpdateAvailable { update });
}
}
fn ready_owner(preferred: Option<&str>, live: &[String], ready: &HashSet<String>) -> Option<String> {
preferred
.map(AppState::owner_window)
.filter(|label| ready.contains(*label) && live.iter().any(|live| live.as_str() == *label))
.map(str::to_owned)
.or_else(|| live.iter().find(|label| ready.contains(*label)).cloned())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn notifications_only_target_live_owners_that_have_subscribed() {
let live = vec!["main".into(), "project-2".into()];
let ready = HashSet::from(["main".into(), "closed-window".into()]);
for focused in [Some("project-2"), Some("settings-main"), Some("closed-window"), None] {
assert_eq!(ready_owner(focused, &live, &ready), Some("main".into()));
}
assert_eq!(ready_owner(Some("main"), &live, &HashSet::new()), None);
assert_eq!(ready_owner(Some("closed-window"), &[], &ready), None);
}
}
+1 -1
Переглянути файл
@@ -37,7 +37,7 @@ pub fn current(app: &AppHandle, caller: &str) -> Vec<WindowTab> {
let project = host.project(label).ok();
let name = project
.as_ref()
.map(|p| ide_host::ops::project::info(p).name)
.map(|p| ide_host::ops::project::info(p).display_name)
.unwrap_or_else(|| window.title().unwrap_or_default());
Some(WindowTab {
label: label.clone(),
+21 -19
Переглянути файл
@@ -66,6 +66,7 @@ export const commands = {
trusted: boolean,
root: IpcPath,
name: string,
displayName: string,
isGit: boolean,
settings: Settings_Serialize,
workspace?: Workspace_Serialize | null,
@@ -226,6 +227,12 @@ export const commands = {
clipboardFileList: () => typedError<string[], IdeError>(__TAURI_INVOKE("clipboard_file_list")),
/** Whether the clipboard holds files: cheap, for the Paste item's enabled state. */
clipboardHasFiles: () => __TAURI_INVOKE<boolean>("clipboard_has_files"),
/**
* The clipboard's image as a PNG data URL, for a paste whose event carried no
* files: WebKitGTK leaves `clipboardData` empty for a raw image (a screenshot).
* None when the clipboard holds no image, and always on other platforms.
*/
clipboardImage: () => typedError<string | null, IdeError>(__TAURI_INVOKE("clipboard_image")),
/**
* Replaces the clipboard with `paths`, so Explorer can paste them. Best-effort:
* false when the clipboard stayed busy; the caller keeps working either way.
@@ -1004,17 +1011,9 @@ export const commands = {
appCliUninstall: () => typedError<IpcPath[], IdeError>(__TAURI_INVOKE("app_cli_uninstall")),
appBuildInfo: () => __TAURI_INVOKE<BuildInfo>("app_build_info"),
appCheckUpdate: (source: UpdateSource) => typedError<UpdateCheck, IdeError>(__TAURI_INVOKE("app_check_update", { source })),
/**
* The background check made once per process when the first window starts;
* later calls (other windows) and debug builds get `None`. Failures are logged,
* not reported: the user didn't ask for this check.
*/
appStartupUpdateCheck: (source: UpdateSource) => __TAURI_INVOKE<{
version: string,
currentVersion: string,
notes: string | null,
date: string | null,
} | null>("app_startup_update_check", { source }),
appUpdateWindowReady: (ready: boolean, systemLocale: string) => typedError<null, IdeError>(__TAURI_INVOKE("app_update_window_ready", { ready, systemLocale })),
appUpdateStatus: () => typedError<UpdateStatus, IdeError>(__TAURI_INVOKE("app_update_status")),
appUpdateAnnouncement: (version: string, automatic: boolean) => typedError<boolean, IdeError>(__TAURI_INVOKE("app_update_announcement", { version, automatic })),
/**
* Downloads and installs the available update, streaming progress to `on_progress`.
* Cancellable through `request` until the download completes; the UI then restarts
@@ -4396,6 +4395,7 @@ export type GeneralSettings = {
projectName?: string,
/** Where updates come from: `auto` (the CNB mirror for the Chinese UI, else GitHub) | `github` | `cnb`. */
updateSource?: string,
autoCheckUpdates?: boolean,
};
/** A repository of the signed-in account (owned, collaborator, or organization member). */
@@ -4871,7 +4871,7 @@ cancellable: boolean } |
* A setting was written (any window); the windows it concerns (all for a
* global value, the project's for a project value) re-read their effective settings.
*/
{ type: "settingsChanged"; key: string } |
{ type: "settingsChanged"; key: string } | { type: "updateStatusChanged"; status: UpdateStatus } | { type: "updateAvailable"; update: UpdateInfo } |
/**
* The project's source / test / resource / excluded roots changed (build files
* changed or folders were marked); the UI re-reads them with `project_roots`.
@@ -6948,6 +6948,7 @@ export type ProjectInfo_Deserialize = {
trusted: boolean,
root: IpcPath,
name: string,
displayName?: string,
isGit: boolean,
settings: Settings_Deserialize,
workspace?: Workspace_Deserialize | null,
@@ -6958,6 +6959,7 @@ export type ProjectInfo_Serialize = {
trusted: boolean,
root: IpcPath,
name: string,
displayName: string,
isGit: boolean,
settings: Settings_Serialize,
workspace?: Workspace_Serialize | null,
@@ -8744,7 +8746,6 @@ export type UnityProjectInfo = {
};
export type UpdateCheck = {
/** False when no update endpoint is configured (no request was made). */
enabled: boolean,
update: UpdateInfo | null,
};
@@ -8763,12 +8764,13 @@ export type UpdateProgress =
/** Download done; the new version is being written over this one. */
{ type: "installing" };
/** Where updates are downloaded from (System Settings › Updates). */
export type UpdateSource =
/** The GitHub releases named in tauri.conf.json. */
"github" |
/** The CNB mirror of the same releases, for networks where GitHub is slow. */
"cnb";
export type UpdateSource = "github" | "cnb";
export type UpdateStatus = {
/** Unix milliseconds of the last successful check in this process. */
lastChecked: number | null,
checking: boolean,
};
export type Variable = {
name: string,
+11 -1
Переглянути файл
@@ -324,6 +324,13 @@ export interface SetupOptions {
* below its top edge. WebKit positions them `absolute` within `.cm-editor`, so
* a window-wide right bound makes CodeMirror skip the shift left and the
* browser squeezes the box into the space left of the editor's edge.
*
* They are parented to the body (#2310): tooltips are `position: fixed` but
* appended inside the editor by default, whose `.content{isolation:isolate}`
* stacking context paints as one unit below the later bottom toolwindow — so
* completion popups got covered where they overflowed the editor's bottom
* edge. At the body level their z-index (500) sits above panels
* (`--z-panel: 10`) while staying below dialogs (`--z-dialog: 900`).
*/
export function tooltipBounds(view: { scrollDOM: Element; dom: Element }) {
const { top } = view.scrollDOM.getBoundingClientRect();
@@ -336,7 +343,10 @@ export function tooltipBounds(view: { scrollDOM: Element; dom: Element }) {
};
}
const tooltipSpace = tooltips({ tooltipSpace: tooltipBounds });
const tooltipSpace = tooltips({
parent: typeof document === "undefined" ? undefined : document.body,
tooltipSpace: tooltipBounds,
});
export function baseExtensions(o: SetupOptions): Extension {
return [
+2 -1
Переглянути файл
@@ -121,8 +121,9 @@ export const overviewStyles = {
};
export const openideaTheme = EditorView.theme({
// Not on "&": the tooltip container in `body` carries the theme classes too.
"&.cm-editor": { height: "100%" },
"&": {
height: "100%",
backgroundColor: "var(--bg-editor, var(--bg-island, var(--bg-app)))",
color: "var(--fg-editor, var(--fg))",
"--editor-line-number": "var(--fg-line-number, var(--fg-gutter))",
+18 -6
Переглянути файл
@@ -216,7 +216,7 @@ describe("EditorController", () => {
expect(pane().tabs.map((t) => t.input.path)).toEqual(["/p/a.ts", "/p/c.ts"]);
});
it("carries the plain project's editor tabs into its automatic workspace", async () => {
it("keeps editor tabs and unsaved documents through attach and detach", async () => {
const settings = {};
useProject.setState({
project: { root: "/attach-a", name: "A", trusted: true, isGit: false, settings },
@@ -227,19 +227,31 @@ describe("EditorController", () => {
ctrl.start();
await ctrl.openFile("/attach-a/one.txt", { focus: false, preview: false });
await ctrl.openFile("/attach-a/two.txt", { focus: false, preview: false });
const slot = ctrl.activeSlot!;
const host = document.createElement("div");
const view = slot.mount(host);
ctrl.onMounted(slot);
view.dispatch({ changes: { from: 0, insert: "unsaved " }, userEvent: "input.type" });
const tabs = useTabs.getState();
useProject.setState({
project: {
root: "/attach-workspace",
name: "A",
root: "/attach-a",
name: "A, attach-b",
trusted: true,
isGit: false,
settings,
workspace: { version: 1, name: "A", projects: ["/attach-a", "/attach-b"] },
},
});
await vi.waitFor(() =>
expect(openFilePaths(useTabs.getState())).toEqual(["/attach-a/one.txt", "/attach-a/two.txt"]),
);
expect(useTabs.getState()).toBe(tabs);
expect(ctrl.activeSlot).toBe(slot);
expect(view.state.doc.toString()).toContain("unsaved ");
expect(openFilePaths(useTabs.getState())).toEqual(["/attach-a/one.txt", "/attach-a/two.txt"]);
useProject.setState({ project: { root: "/attach-a", name: "A", trusted: true, isGit: false, settings } });
expect(useTabs.getState()).toBe(tabs);
expect(ctrl.activeSlot).toBe(slot);
expect(view.state.doc.toString()).toContain("unsaved ");
host.remove();
useProject.setState({ project: null });
});
-9
Переглянути файл
@@ -307,15 +307,6 @@ export class EditorController implements SlotHost {
prevRoot = root;
prevLight = s.lightEdit;
this.saveSession();
if (
root &&
previous.project &&
!previous.project.workspace &&
s.project?.workspace?.projects[0] === previous.project.root
) {
const session = loadSession(previous.project.root);
if (session) storeSession(root, session);
}
this.sessionRoot = null;
const generation = ++this.projectGeneration;
const documents = customDocuments(useTabs.getState(), useContributions.getState().editorKinds);
+2 -1
Переглянути файл
@@ -110,7 +110,8 @@ describe.each([
view = editor();
activateHover(view, 2, 1);
await settle();
const tooltip = view.dom.querySelector(".cm-tooltip")!;
// Tooltips are parented to the body (#2310), not to the editor element.
const tooltip = document.querySelector(".cm-tooltip")!;
tooltip.dispatchEvent(new MouseEvent("mousemove", { bubbles: true }));
expect(pointerTarget()).toBe(tooltip);
key("keydown", mod, { [flag]: true });
+17 -5
Переглянути файл
@@ -300,13 +300,15 @@ export function Composer(props: ComposerProps) {
[id],
);
const fitsLimit = (name: string, size: number) => {
if (size <= MAX_IMAGE_BYTES) return true;
notifications().notify({ level: "warning", title: "Image too large", body: tx`${name} is over 5 MB.` });
return false;
};
const readImageFiles = (picked: Iterable<File>) => {
for (const file of picked) {
if (!file.type.startsWith("image/")) continue;
if (file.size > MAX_IMAGE_BYTES) {
notifications().notify({ level: "warning", title: "Image too large", body: tx`${file.name} is over 5 MB.` });
continue;
}
if (!file.type.startsWith("image/") || !fitsLimit(file.name, file.size)) continue;
const reader = new FileReader();
reader.onload = () => {
const image = typeof reader.result === "string" ? imageFromDataUrl(reader.result, file.name || "image") : null;
@@ -316,6 +318,12 @@ export function Composer(props: ComposerProps) {
}
};
const pasteClipboardImage = async () => {
const url = await call(commands.clipboardImage());
const image = url ? imageFromDataUrl(url, "image") : null;
if (image && fitsLimit("image", (image.data.length * 3) / 4)) addImages([image]);
};
// Files dropped from the OS onto the box: images are attached, other files referenced.
useEffect(() => {
if (!isTauri()) return;
@@ -571,6 +579,10 @@ export function Composer(props: ComposerProps) {
if (pasted.length) {
e.preventDefault();
readImageFiles(pasted);
} else if (isTauri() && !e.clipboardData.types.length) {
pasteClipboardImage().catch((error: unknown) =>
notifications().notify({ level: "error", title: tx("Cannot insert image"), body: String(error) }),
);
}
}}
/>
+20 -1
Переглянути файл
@@ -7,6 +7,7 @@ const agentCommands = vi.fn();
const agentCreate = vi.fn();
const vcsBranches = vi.fn();
const vcsBranchInfo = vi.fn();
const clipboardImage = vi.fn();
vi.mock("@/platform/ipc", async (importOriginal) => {
const real = await importOriginal<typeof import("@/platform/ipc")>();
@@ -17,6 +18,7 @@ vi.mock("@/platform/ipc", async (importOriginal) => {
...real.commands,
agentCommands: (provider: string, task: string | null) => agentCommands(provider, task),
agentCreate: (request: unknown) => agentCreate(request),
clipboardImage: () => clipboardImage(),
vcsBranchInfo: (root: string | null) => vcsBranchInfo(root),
vcsBranches: (root: string | null) => vcsBranches(root),
},
@@ -33,7 +35,7 @@ import { defaultTaskProject } from "./project";
import { HomeEditor } from "./HomeEditor";
import composerStyles from "./Composer.module.css";
import tagStyles from "@/ui/InlineTag.module.css";
import { HOME, updateComposer, useAgents } from "./store";
import { composerDraft, HOME, updateComposer, useAgents } from "./store";
import { emptyDraft } from "./composerModel";
const command = (name: string, description: string, source: "command" | "skill" = "command"): AgentCommand => ({
@@ -72,6 +74,7 @@ beforeEach(() => {
Promise.resolve({ status: "ok", data: { head: root === "/project-b" ? "b-main" : "a-main" } }),
);
agentCommands.mockReset();
clipboardImage.mockReset().mockResolvedValue({ status: "ok", data: "data:image/png;base64,iVBORw0KGgo=" });
agentCreate.mockReset().mockResolvedValue({ status: "error", error: { kind: "invalid", message: "stop here" } });
useAgents.setState({
providers: [claude],
@@ -227,6 +230,22 @@ describe("New Task composer commands", () => {
});
});
describe("New Task composer paste", () => {
it("attaches the clipboard's image when WebKitGTK pastes an empty clipboardData", async () => {
render(<HomeEditor />);
fireEvent.paste(screen.getByRole("textbox"), { clipboardData: { types: [], files: [] } });
await waitFor(() =>
expect(composerDraft(HOME).images).toEqual([{ mimeType: "image/png", data: "iVBORw0KGgo=", name: "image" }]),
);
});
it("leaves a text paste to the text box", () => {
render(<HomeEditor />);
fireEvent.paste(screen.getByRole("textbox"), { clipboardData: { types: ["text/plain"], files: [] } });
expect(clipboardImage).not.toHaveBeenCalled();
});
});
describe("workspace task project", () => {
const project = {
root: "/workspace",
+11 -1
Переглянути файл
@@ -2,6 +2,7 @@ import { useEffect, useRef, useState } from "react";
import { create } from "zustand";
import { call, commands, isCancelled, nextRequestId, type ProjectDiscovery, type RequestId } from "@/platform/ipc";
import { invokeLocal } from "@/platform/tauriCore";
import { confirmProjectTrust } from "@/platform/projectTrust";
import { basename, dirname, useProject } from "@/platform/project";
import { isRemoteWindow } from "@/platform/remote";
import { tx } from "@/platform/i18n";
@@ -101,12 +102,21 @@ function WorkspaceDialog({ mode, onClose }: { mode: "create" | "manage"; onClose
const root = await call(commands.workspaceCreate(path.trim(), name.trim(), included));
await openProjectWithPolicy(root);
} else {
for (const path of included.filter((p) => !workspace?.projects.includes(p))) {
await confirmProjectTrust(path);
if (!(await call(commands.projectTrustStatus(path))).trusted) {
setError(
tx`Cannot attach ${path} because it is restricted. Open it separately and choose Trust Project, then attach it again.`,
);
return;
}
}
const updated = await call(commands.workspaceUpdate(name.trim(), included));
useProject.setState({ project: updated, settings: updated.settings });
}
onClose();
} catch (e) {
setError(e instanceof Error ? e.message : String(e));
if (!isCancelled(e)) setError(e instanceof Error ? e.message : String(e));
} finally {
setBusy(false);
}
+41
Переглянути файл
@@ -2,6 +2,7 @@ import { beforeEach, expect, it, vi } from "vitest";
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { open } from "@tauri-apps/plugin-dialog";
import { commands, type ProjectDiscovery } from "@/platform/ipc";
import { provideProjectTrustPrompt } from "@/platform/projectTrust";
import { invokeLocal } from "@/platform/tauriCore";
import { useProject } from "@/platform/project";
import { WorkspaceDialogHost, showWorkspaceDialog } from "../WorkspaceDialog";
@@ -19,6 +20,10 @@ beforeEach(() => {
vi.restoreAllMocks();
vi.mocked(openProjectWithPolicy).mockClear();
vi.mocked(open).mockReset();
vi.spyOn(commands, "projectTrustStatus").mockResolvedValue({
status: "ok",
data: { root: "/work", trusted: true, decided: true },
});
vi.mocked(invokeLocal).mockClear();
useProject.setState({ project: null, settings: null, lightEdit: false });
});
@@ -191,3 +196,39 @@ it("retains the form and linked folders when saving fails", async () => {
fireEvent.click(screen.getByRole("button", { name: /^Cancel$/ }));
expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
});
it.each(["restricted", "cancelled"])("retains Manage Workspace when project trust is %s", async (decision) => {
useProject.setState({
project: {
root: "/work/primary",
name: "primary",
trusted: true,
isGit: false,
settings: {},
workspace: { version: 1, name: "primary", projects: ["/work/primary"] },
},
} as never);
vi.mocked(commands.projectTrustStatus).mockResolvedValue({
status: "ok",
data: { root: "/work/restricted", trusted: false, decided: true },
});
const update = vi.spyOn(commands, "workspaceUpdate");
const dispose = provideProjectTrustPrompt(async () => decision !== "cancelled");
try {
showWorkspaceDialog("manage");
render(<WorkspaceDialogHost />);
fireEvent.change(screen.getByLabelText("Project folder path"), { target: { value: "/work/restricted" } });
fireEvent.click(screen.getByRole("button", { name: /^Apply$/ }));
await waitFor(() => expect(screen.getByRole("button", { name: /^Apply$/ })).toBeEnabled());
expect(update).not.toHaveBeenCalled();
if (decision === "restricted") {
expect(screen.getByRole("alert")).toHaveTextContent(
"Cannot attach /work/restricted because it is restricted. Open it separately and choose Trust Project, then attach it again.",
);
} else expect(screen.queryByRole("alert")).not.toBeInTheDocument();
expect(screen.getByLabelText("Project folder path")).toHaveValue("/work/restricted");
fireEvent.click(screen.getByRole("button", { name: /^Cancel$/ }));
} finally {
dispose();
}
});
+52
Переглянути файл
@@ -0,0 +1,52 @@
import { afterEach, expect, it, vi } from "vitest";
import { useProject } from "@/platform/project";
import { projectActions } from "../projectActions";
import { installWindowTitle } from "../title";
const { rename, prompt } = vi.hoisted(() => ({ rename: vi.fn(), prompt: vi.fn() }));
vi.mock("@/platform/ipc", async (original) => ({
...(await original<typeof import("@/platform/ipc")>()),
isTauri: () => true,
commands: { projectRename: rename, menuRefresh: vi.fn() },
}));
vi.mock("@tauri-apps/api/window", () => ({ getCurrentWindow: () => ({ setTitle: async () => {} }) }));
vi.mock("@/workbench/inputDialogs", () => ({ promptInput: prompt }));
afterEach(() => {
useProject.setState({ project: null, settings: null });
});
it("renames from the primary name while updating the attached window label", async () => {
const project = {
root: "/primary",
name: "primary",
displayName: "primary, other",
trusted: true,
isGit: false,
settings: {},
workspace: { version: 1, name: "primary", projects: ["/primary", "/other"] },
};
useProject.setState({ project });
const dispose = installWindowTitle();
try {
expect(document.title).toBe("primary, other");
prompt.mockImplementation(async ({ initial }) => initial);
rename.mockImplementation(async (name) => ({
status: "ok",
data: { ...project, name, displayName: `${name}, other` },
}));
await projectActions()
.find((a) => a.id === "file.renameProject")!
.run({ ctx: {} });
expect(rename).toHaveBeenCalledWith("primary");
expect(document.title).toBe("primary, other");
prompt.mockResolvedValueOnce("Renamed");
await projectActions()
.find((a) => a.id === "file.renameProject")!
.run({ ctx: {} });
expect(useProject.getState().project).toMatchObject({ name: "Renamed", displayName: "Renamed, other" });
expect(document.title).toBe("Renamed, other");
} finally {
dispose();
}
});
+54 -13
Переглянути файл
@@ -25,7 +25,9 @@ const appInstallUpdate = vi.fn((_source: string, _request: number, ch: Channel)
return install.promise;
});
const appCheckUpdate = vi.fn(() => check.promise);
const appStartupUpdateCheck = vi.fn(async (): Promise<UpdateInfo | null> => null);
const appUpdateWindowReady = vi.fn(async (_ready: boolean, _systemLocale: string) => ({ status: "ok", data: null }));
const appUpdateAnnouncement = vi.fn(async () => ({ status: "ok", data: true }));
const updateListeners = new Map<string, (event: { update: UpdateInfo }) => void>();
const appRestart = vi.fn(async () => null);
const cancelRequest = vi.fn(async () => null);
const appBuildInfo = vi.fn(async () => ({ version: "0.1.21" }));
@@ -36,11 +38,17 @@ vi.mock("@/platform/ipc", async (orig) => {
return {
...actual,
isTauri: () => true,
ideEventsReady: async () => {},
onIdeEvent: (type: string, handler: (event: { update: UpdateInfo }) => void) => {
updateListeners.set(type, handler);
return () => updateListeners.delete(type);
},
commands: {
...actual.commands,
appInstallUpdate,
appCheckUpdate,
appStartupUpdateCheck,
appUpdateWindowReady,
appUpdateAnnouncement,
appRestart,
cancelRequest,
appBuildInfo,
@@ -51,7 +59,7 @@ vi.mock("@/platform/ipc", async (orig) => {
const {
checkForUpdates,
checkForUpdatesOnStartup,
installUpdateChecks,
installUpdate,
notifyUpdate,
progressText,
@@ -115,7 +123,7 @@ describe("Install and Restart", () => {
});
it("joins the running install on repeated clicks (balloon, log entry, a second check)", async () => {
notifyUpdate({ version: "0.1.22", currentVersion: "0.1.21", notes: null, date: null });
await notifyUpdate({ version: "0.1.22", currentVersion: "0.1.21", notes: null, date: null });
const action = notes[0]!.actions![0]!;
action.run();
action.run();
@@ -212,6 +220,30 @@ describe("Check for Updates", () => {
expect(task(CHECK_TASK_ID)?.done).toBe(true);
});
it("does not consume an announcement when a manual check is cancelled", async () => {
const done = checkForUpdates();
task(CHECK_TASK_ID)!.cancel!();
await done;
check.resolve(
ok({ enabled: true, update: { version: "0.1.22", currentVersion: "0.1.21", notes: null, date: null } }),
);
await tick();
expect(appUpdateAnnouncement).not.toHaveBeenCalled();
await notifyUpdate({ version: "0.1.22", currentVersion: "0.1.21", notes: null, date: null });
expect(appUpdateAnnouncement).toHaveBeenCalledWith("0.1.22", true);
expect(notes.at(-1)?.title).toBe("OpenIDEA 0.1.22 is available");
});
it("suppresses an already announced automatic version but still answers a manual check", async () => {
const update = { version: "0.1.22", currentVersion: "0.1.21", notes: null, date: null };
appUpdateAnnouncement.mockResolvedValueOnce({ status: "ok", data: false });
await notifyUpdate(update);
expect(notes).toHaveLength(0);
await notifyUpdate(update, true);
expect(appUpdateAnnouncement).toHaveBeenLastCalledWith("0.1.22", false);
expect(notes.at(-1)).toMatchObject({ title: "OpenIDEA 0.1.22 is available", userInitiated: true });
});
it("shows the check in a balloon where there is no status bar (the welcome screen)", async () => {
const done = checkForUpdates();
expect(notes[0]).toMatchObject({ level: "info", title: "Checking for updates…", key: UPDATE_KEY });
@@ -227,16 +259,25 @@ describe("Check for Updates", () => {
await done;
});
it("leaves the startup check to the IDE Updates notification settings", async () => {
appStartupUpdateCheck.mockResolvedValueOnce({
version: "0.1.22",
currentVersion: "0.1.21",
notes: null,
date: null,
it("starts the process scheduler after subscribing and leaves automatic results to notification settings", async () => {
const dispose = installUpdateChecks();
await tick();
expect(appUpdateWindowReady).toHaveBeenCalledTimes(1);
updateListeners.get("updateAvailable")!({
update: { version: "0.1.22", currentVersion: "0.1.21", notes: null, date: null },
});
await checkForUpdatesOnStartup();
expect(notes.at(-1)).toMatchObject({ title: "OpenIDEA 0.1.22 is available" });
expect(notes.at(-1)?.userInitiated).toBe(false);
await tick();
expect(notes.at(-1)).toMatchObject({ title: "OpenIDEA 0.1.22 is available", userInitiated: false });
dispose();
expect(updateListeners.has("updateAvailable")).toBe(false);
});
it("does not start a schedule after its window has been disposed", async () => {
const dispose = installUpdateChecks();
dispose();
await tick();
expect(appUpdateWindowReady).not.toHaveBeenCalledWith(true, expect.anything());
expect(appUpdateWindowReady).toHaveBeenCalledWith(false, navigator.language);
});
it('still pops up when IDE Updates is set to "No popup" (no other surface on the welcome screen)', async () => {
+75 -6
Переглянути файл
@@ -1,5 +1,8 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const projectTrustStatus = vi.fn();
vi.mock("@/platform/projectTrust", () => ({ confirmProjectTrust: vi.fn(async () => {}) }));
vi.mock("@/workbench/messages", () => ({ ask: vi.fn() }));
const workspaceAttach = vi.fn();
const workspaceUpdate = vi.fn();
const projectCurrent = vi.fn();
@@ -35,6 +38,7 @@ vi.mock("@/platform/ipc", async (orig) => {
isTauri: () => true,
commands: {
...real.commands,
projectTrustStatus: (...a: unknown[]) => projectTrustStatus(...a),
workspaceAttach: (...a: unknown[]) => workspaceAttach(...a),
workspaceUpdate: (...a: unknown[]) => workspaceUpdate(...a),
projectCurrent: () => projectCurrent(),
@@ -50,7 +54,7 @@ vi.mock("@/platform/ipc", async (orig) => {
});
vi.mock("@/platform/project", async (orig) => {
const real = await orig<typeof import("@/platform/project")>();
return { ...real, openProject: (p: string) => openProject(p) };
return { ...real, confirmLeaveProject: vi.fn(real.confirmLeaveProject), openProject: (p: string) => openProject(p) };
});
const diffs: unknown[] = [];
const openDiff = vi.fn(async (data: unknown) => void diffs.push(data));
@@ -66,9 +70,11 @@ const {
openProjectWithPolicy,
windowActions,
} = await import("../windows");
const { useProject, startupLaunchHandled } = await import("@/platform/project");
const { useProject, startupLaunchHandled, confirmLeaveProject } = await import("@/platform/project");
const { provideEditorService, provideNotificationService } = await import("@/workbench/contributions");
const { isRemoteWindow, connectRemote } = await import("@/platform/remote");
const { ask } = await import("@/workbench/messages");
const { confirmProjectTrust } = await import("@/platform/projectTrust");
const { IpcError } = await import("@/platform/ipc");
provideNotificationService({ notify });
@@ -99,6 +105,12 @@ function deferred() {
}
beforeEach(() => {
vi.mocked(ask).mockReset().mockResolvedValue({ button: "attach", checked: false });
vi.mocked(confirmProjectTrust).mockReset().mockResolvedValue();
projectTrustStatus.mockReset().mockResolvedValue(ok({ trusted: true }));
workspaceAttach.mockReset();
workspaceUpdate.mockReset();
projectCurrent.mockReset();
for (const f of [windowOpenProject, windowOpenFiles, windowTakeLaunch, wslResolve]) f.mockReset();
windowTakeLaunch.mockResolvedValue(null);
windowCompleteLaunch.mockReset().mockResolvedValue(ok(null));
@@ -106,6 +118,7 @@ beforeEach(() => {
vi.mocked(connectRemote).mockClear();
for (const f of [lightEditOpen, fsReadDir, openProject]) f.mockClear();
cancelClose.mockClear();
vi.mocked(confirmLeaveProject).mockClear();
notify.mockClear();
listen.mockReset();
openEditorFile.mockClear();
@@ -591,17 +604,54 @@ describe("launch", () => {
});
describe("Attach", () => {
it("switches a plain project to the automatic workspace in place", async () => {
it("attaches in place without reopening or asking to leave", async () => {
useProject.setState({
...projectState("/p/a"),
settings: { general: { openProjectIn: "attach" } },
} as never);
workspaceAttach.mockResolvedValue(ok("/data/workspaces/a"));
await openProjectWithPolicy("/p/b");
const project = {
...projectState("/p/a").project,
workspace: { version: 1, name: "a", projects: ["/p/a", "/p/b"] },
};
projectCurrent.mockResolvedValue(project);
workspaceAttach.mockResolvedValue(ok("/p/a"));
await openProjectWithPolicy("/p/b", ["/p/b/file.txt"]);
expect(confirmProjectTrust).toHaveBeenCalledWith("/p/b", "local");
expect(workspaceAttach).toHaveBeenCalledWith("/p/b");
expect(openProject).toHaveBeenCalledWith("/data/workspaces/a");
expect(openProject).not.toHaveBeenCalled();
expect(cancelClose).not.toHaveBeenCalled();
expect(confirmLeaveProject).not.toHaveBeenCalled();
expect(useProject.getState().project).toEqual(project);
expect(opened).toEqual(["/p/b/file.txt (focus)"]);
expect(ask).toHaveBeenCalledTimes(1);
expect(windowOpenProject).not.toHaveBeenCalled();
});
it("does not attach when trust is cancelled", async () => {
useProject.setState(projectState("/p/a"));
vi.mocked(confirmProjectTrust).mockRejectedValueOnce(new IpcError({ kind: "cancelled", message: "Cancelled" }));
await openProjectWithPolicy("/p/b");
expect(workspaceAttach).not.toHaveBeenCalled();
expect(openProject).not.toHaveBeenCalled();
expect(notify).not.toHaveBeenCalled();
});
it("does not attach a folder previewed in restricted mode", async () => {
useProject.setState(projectState("/p/a"));
projectTrustStatus.mockResolvedValueOnce(ok({ trusted: false }));
await openProjectWithPolicy("/p/b");
expect(workspaceAttach).not.toHaveBeenCalled();
});
it("explains how to attach a folder already decided as restricted", async () => {
useProject.setState(projectState("/p/a"));
projectTrustStatus.mockResolvedValueOnce(ok({ root: "/p/b", trusted: false, decided: true }));
await openProjectWithPolicy("/p/b");
expect(workspaceAttach).not.toHaveBeenCalled();
expect(notify).toHaveBeenCalledWith(
expect.objectContaining({
level: "warning",
body: "Cannot attach /p/b because it is restricted. Open it separately and choose Trust Project, then attach it again.",
}),
);
});
it("refreshes an existing workspace without reopening its editor session", async () => {
const before = {
root: "/workspace",
@@ -645,6 +695,25 @@ it("removes the first workspace member while retaining the workspace state root"
expect(useProject.getState().project?.workspace?.projects).toEqual(["/b"]);
});
it("confirms detaching an attachment and never removes the primary", async () => {
const project = { ...projectState("/a").project, workspace: { version: 1, name: "A", projects: ["/a", "/b"] } };
useProject.setState({ project });
const action = windowActions().find((a) => a.id === "project.detach")!;
expect(action.title).toBe("Detach Project");
expect(action.when).toBe("projectAttached");
await action.run({ arg: "/a" } as never);
expect(ask).not.toHaveBeenCalled();
expect(workspaceUpdate).not.toHaveBeenCalled();
vi.mocked(ask).mockResolvedValueOnce({ button: "cancel", checked: false });
await action.run({ arg: "/b" } as never);
expect(workspaceUpdate).not.toHaveBeenCalled();
vi.mocked(ask).mockResolvedValueOnce({ button: "detach", checked: false });
workspaceUpdate.mockResolvedValueOnce(ok(projectState("/a").project));
await action.run({ arg: "/b" } as never);
expect(workspaceUpdate).toHaveBeenCalledWith("A", ["/a"]);
expect(useProject.getState().project?.workspace).toBeUndefined();
});
describe("explicit project-window requests", () => {
it("honours current-window requests even when a project is already open", async () => {
useProject.setState(projectState("/p/old") as never);
+2 -2
Переглянути файл
@@ -201,7 +201,7 @@ async function onCloseRequested(deps: CloseDeps): Promise<boolean> {
confirmTerminate,
processes: confirmTerminate ? await processNames(deps) : [],
dirty: dirtyCount(),
project: s.project?.name ?? null,
project: s.project?.displayName || s.project?.name || null,
},
deps,
);
@@ -223,7 +223,7 @@ async function onCloseRequested(deps: CloseDeps): Promise<boolean> {
*/
export async function confirmLeave(
deps: CloseDeps = defaultDeps,
project = useProject.getState().project?.name ?? null,
project = (useProject.getState().project?.displayName || useProject.getState().project?.name) ?? null,
): Promise<boolean> {
if (!(await closeDocumentWindows())) return false;
const confirmTerminate = workflowSettings().run.confirmTerminate;
+2 -2
Переглянути файл
@@ -5,7 +5,7 @@
import { registerOverlay, registerStatusItem } from "@/workbench/contributions";
import { AboutOverlay } from "./AboutDialog";
import { appActions, updateActions } from "./appActions";
import { checkForUpdatesOnStartup } from "./updates";
import { installUpdateChecks } from "./updates";
import { cliActions } from "./cliCommand";
import { installCloseGuard } from "./closeGuard";
import { TerminationOverlay } from "./termination";
@@ -60,7 +60,7 @@ export function activate(): () => void {
void buildInfo().then((b) => {
if (!b?.updates || disposed) return;
disposers.push(registerLocalizedActions(updateActions));
void checkForUpdatesOnStartup();
disposers.push(installUpdateChecks());
});
return () => {
disposed = true;
+2 -2
Переглянути файл
@@ -224,9 +224,9 @@ export function installMenuBridge(): () => void {
useMenuSlotItems.subscribe(push),
useContextKeys.subscribe(() => pushEnablement()),
useActions.subscribe(() => pushEnablement()),
// Opening / closing a project changes the Open Recent list.
// Project membership and names also change the Open Recent list.
useProject.subscribe((s, prev) => {
if (s.project?.root !== prev.project?.root) void commands.menuRefresh();
if (s.project !== prev.project) void commands.menuRefresh();
if (s.lightEdit !== prev.lightEdit) push();
// View › Appearance check marks and Status Bar Widgets.
if (s.settings?.appearance !== prev.settings?.appearance) push();
+1 -1
Переглянути файл
@@ -129,7 +129,7 @@ async function renameProject() {
if (name === null) return;
try {
const info = await call(commands.projectRename(name));
useProject.setState((s) => ({ project: s.project && { ...s.project, name: info.name }, settings: info.settings }));
useProject.setState((s) => ({ project: s.project && info, settings: info.settings }));
void commands.menuRefresh();
} catch (e) {
notifications().notify({ level: "error", title: "Cannot rename project", body: errorText(e) });
+6 -1
Переглянути файл
@@ -35,7 +35,12 @@ export function installWindowTitle(): () => void {
const { project, settings } = useProject.getState();
const fullPath = settings?.appearance?.fullPathInTitle === true;
const host = useRemote.getState().session?.host ?? null;
const title = windowTitle(project?.name, useEditorRegistry.getState().active?.ctx.path, fullPath, host);
const title = windowTitle(
project?.displayName || project?.name,
useEditorRegistry.getState().active?.ctx.path,
fullPath,
host,
);
if (title === last) return;
last = title;
if (typeof document !== "undefined") document.title = title;
+27 -7
Переглянути файл
@@ -13,6 +13,8 @@ import {
commands,
isCancelled,
isTauri,
ideEventsReady,
onIdeEvent,
nextRequestId,
type UpdateInfo,
type UpdateProgress,
@@ -110,7 +112,7 @@ async function runCheck() {
userInitiated: true,
});
} else if (!installing) {
notifyUpdate(r.update, true);
await notifyUpdate(r.update, true);
}
} catch (e) {
notifications().notify({
@@ -125,15 +127,33 @@ async function runCheck() {
}
}
/** Silent check once per app start; only an available update is shown. */
export async function checkForUpdatesOnStartup(): Promise<void> {
if (!isTauri()) return;
const update = await commands.appStartupUpdateCheck(updateSource()).catch(() => null);
if (update) notifyUpdate(update);
/** Start one backend schedule after this window can receive its notifications. */
export function installUpdateChecks(): () => void {
let disposed = false;
const off = onIdeEvent("updateAvailable", ({ update }) => {
if (!installing) void notifyUpdate(update);
});
void ideEventsReady().then(() => {
if (!disposed && isTauri())
void call(commands.appUpdateWindowReady(true, navigator.language)).catch((e) =>
console.warn("cannot start update checks", e),
);
});
return () => {
disposed = true;
off();
if (isTauri()) void call(commands.appUpdateWindowReady(false, navigator.language)).catch(() => {});
};
}
/** `userInitiated`: the update came from a manual check, so it pops up regardless of the balloon settings. */
export function notifyUpdate(update: UpdateInfo, userInitiated = false) {
export async function notifyUpdate(update: UpdateInfo, userInitiated = false): Promise<void> {
if (isTauri()) {
const claimed = await call(commands.appUpdateAnnouncement(update.version, !userInitiated)).catch(
() => userInitiated,
);
if (!claimed) return;
}
notifications().notify({
level: "info",
title: t("app.update.available", { version: update.version }),
+72 -30
Переглянути файл
@@ -8,7 +8,7 @@
* editor tabs only. One LightEdit window collects them all.
*/
import { executeAction, type Action } from "@/platform/actions";
import { t } from "@/platform/i18n";
import { t, tx } from "@/platform/i18n";
import { call, commands, isCancelled, isTauri } from "@/platform/ipc";
import {
basename,
@@ -19,6 +19,8 @@ import {
provideStartupLaunch,
useProject,
} from "@/platform/project";
import { confirmProjectTrust } from "@/platform/projectTrust";
import { ask } from "@/workbench/messages";
import { connectRemote, isRemoteWindow } from "@/platform/remote";
import { holdSplash } from "@/platform/splash";
import { editorService, maybeEditorService, notifications } from "@/workbench/contributions";
@@ -160,22 +162,7 @@ export async function openProjectWithPolicy(path: string, files: readonly string
if (!mode) return;
if (mode === "new") return openProjectInWindow(path, true, files);
if (mode === "attach") {
try {
if (!current?.workspace && !(await confirmLeaveProject())) return;
const root = await call(commands.workspaceAttach(path));
if (root === current?.root) {
if (!current.workspace) maybeEditorService()?.cancelClose?.();
const project = await commands.projectCurrent();
if (project) useProject.setState({ project, settings: project.settings });
} else {
await openProject(root);
}
await executeAction("project.reveal", path);
await openInEditor(files);
} catch (e) {
maybeEditorService()?.cancelClose?.();
openFailed(path, e);
}
await attachProject(path, files);
return;
}
try {
@@ -187,6 +174,27 @@ export async function openProjectWithPolicy(path: string, files: readonly string
}
}
async function attachProject(path: string, files: readonly string[] = []): Promise<void> {
try {
await confirmProjectTrust(path, "local");
if (!(await call(commands.projectTrustStatus(path))).trusted) {
notifications().notify({
level: "warning",
title: tx("Project not attached"),
body: tx`Cannot attach ${path} because it is restricted. Open it separately and choose Trust Project, then attach it again.`,
});
return;
}
await call(commands.workspaceAttach(path));
const project = await commands.projectCurrent();
if (project) useProject.setState({ project, settings: project.settings });
await executeAction("project.reveal", path);
await openInEditor(files);
} catch (e) {
openFailed(path, e);
}
}
/** LightEdit: opens the current file's folder as a project ("Open project in" applies) and the file there. */
export async function openLightEditFileAsProject(): Promise<void> {
if (!useProject.getState().lightEdit) return;
@@ -291,24 +299,58 @@ function closeProjectTabs(side: "others" | "left" | "right"): Action["run"] {
};
}
const removeProject: Action["run"] = async ({ arg }) => {
const current = useProject.getState().project;
const workspace = current?.workspace;
if (typeof arg !== "string" || !workspace || !workspace.projects.includes(arg)) return;
if (workspace.projects[0] === current.root) {
if (arg === current.root) return;
const result = await ask({
title: t("app.window.detachTitle"),
body: t("app.window.detachBody", { name: basename(arg) }),
buttons: [
{ id: "cancel", label: t("common.cancel") },
{ id: "detach", label: t("app.window.detach"), primary: true },
],
});
if (result.button !== "detach") return;
}
const project = await call(
commands.workspaceUpdate(
workspace.name,
workspace.projects.filter((p) => p !== arg),
),
);
useProject.setState({ project, settings: project.settings });
};
export function windowActions(): Action[] {
return [
{
id: "project.attach",
title: t("app.action.attachProject"),
category: t("app.category.file"),
icon: "folder-open",
when: "projectLocal && !projectOpenAsk",
run: async () => {
if (desktopOnly()) return;
const path = await pickFolder(t("app.action.attachProject"));
if (path) await attachProject(path);
},
},
{
id: "workspace.removeProject",
title: "Remove from Workspace",
category: t("app.category.file"),
when: "workspaceOpen",
run: async ({ arg }) => {
const workspace = useProject.getState().project?.workspace;
if (typeof arg !== "string" || !workspace || !workspace.projects.includes(arg)) return;
const project = await call(
commands.workspaceUpdate(
workspace.name,
workspace.projects.filter((p) => p !== arg),
),
);
useProject.setState({ project, settings: project.settings });
},
when: "workspaceOpen && !projectAttached",
run: removeProject,
},
{
id: "project.detach",
title: "Detach Project",
category: t("app.category.file"),
when: "projectAttached",
run: removeProject,
},
{
id: "workspace.create",
@@ -334,7 +376,7 @@ export function windowActions(): Action[] {
id: "workspace.manage",
title: "Manage Workspace…",
category: t("app.category.file"),
when: "workspaceOpen",
when: "workspaceContainer",
run: () => showWorkspaceDialog("manage"),
},
{
+3 -4
Переглянути файл
@@ -23,7 +23,7 @@ import {
type RunConfig,
type SyncProgress,
} from "@/platform/ipc";
import { downloadJdkActions } from "@/platform/jdk";
import { buildToolRecovery } from "@/platform/buildToolRecovery";
import { useBuildModel } from "@/platform/buildModel";
import { useProject } from "@/platform/project";
import { editorService, notifications } from "@/workbench/contributions";
@@ -454,9 +454,8 @@ export async function syncTool(tool: BuildTool, buildDir: string | null = null):
group: "run",
level: "warning",
title: tool === "maven" ? "Maven sync finished with errors" : "Gradle sync failed",
body: error,
...buildToolRecovery(error),
key: `build-sync-${tool}`,
actions: downloadJdkActions(error),
});
} catch (e) {
if (!isCancelled(e))
@@ -464,7 +463,7 @@ export async function syncTool(tool: BuildTool, buildDir: string | null = null):
group: "run",
level: "error",
title: tool === "maven" ? "Cannot reload Maven projects" : "Cannot reload Gradle projects",
body: e instanceof Error ? e.message : String(e),
...buildToolRecovery(e instanceof Error ? e.message : String(e)),
key: `build-sync-${tool}`,
});
} finally {
+1 -1
Переглянути файл
@@ -80,7 +80,7 @@ export function CellEditor({
language.of([]),
readonly.current.of(EditorState.readOnly.of(session.getState().frozen)),
EditorView.lineWrapping,
EditorView.theme({ "&": { height: "auto" }, ".cm-scroller": { maxHeight: "640px", overflow: "auto" } }),
EditorView.theme({ "&.cm-editor": { height: "auto" }, ".cm-scroller": { maxHeight: "640px", overflow: "auto" } }),
EditorView.contentAttributes.of({
"aria-label": tx(type === "code" ? "Python cell source" : "Markdown cell source"),
}),
+20
Переглянути файл
@@ -247,3 +247,23 @@ it("offers workspace removal for every member root", () => {
expect.objectContaining({ action: "workspace.removeProject" }),
);
});
it("does not offer removal on the attached primary", () => {
useProject.setState({
project: {
root: "/a",
name: "A",
displayName: "A, b",
trusted: true,
isGit: false,
settings: {},
workspace: { version: 1, name: "A", projects: ["/a", "/b"] },
},
});
expect(contextMenuItems([node("/a", true, true)])).not.toContainEqual(
expect.objectContaining({ action: "project.detach" }),
);
expect(contextMenuItems([node("/b", true, true)])).toContainEqual(
expect.objectContaining({ action: "project.detach" }),
);
});
+14 -2
Переглянути файл
@@ -153,8 +153,20 @@ export function contextMenuItems(nodes: ProjectNode[]): MenuItem[] {
const items: MenuItem[] = [];
const push = (...list: Entry[]) => list.forEach((i) => i && items.push(i));
if (single && project?.workspace && project.workspace.projects.includes(single.path)) {
push({ kind: "action", action: "workspace.removeProject", arg: single.path }, { kind: "separator" });
if (
single &&
project?.workspace &&
single.path !== project.root &&
project.workspace.projects.includes(single.path)
) {
push(
{
kind: "action",
action: project.workspace.projects[0] === project.root ? "project.detach" : "workspace.removeProject",
arg: single.path,
},
{ kind: "separator" },
);
}
push({ id: "new", label: "New", submenu: newMenuItems(folder) }, { kind: "separator" });
+1 -1
Переглянути файл
@@ -112,7 +112,7 @@ export function activate(): () => void {
let shownRoots = "";
const syncContentRoots = () => {
const { project, settings } = useProject.getState();
const own = project && !project.workspace;
const own = project && (!project.workspace || project.workspace.projects[0] === project.root);
const paths = own ? validateProjectStructure(settings?.projectStructure).contentRoots : [];
// The Build tool window's model (one load per build change), not a load of our own.
const build = useBuildModel.getState();
+7
Переглянути файл
@@ -233,3 +233,10 @@ describe("single-click expansion", () => {
setViewOption("singleClickExpand", false);
});
});
it("keeps the primary first and sorts attachments by name", () => {
initProjectTree("/z", "Z", ["/z", "/c", "/a"]);
expect(currentModel().roots.map((n) => n.path)).toEqual(["/z", "/a", "/c"]);
initProjectTree("/ws", "Workspace", ["/z", "/c", "/a"]);
expect(currentModel().roots.map((n) => n.path)).toEqual(["/a", "/c", "/z"]);
});
+1 -1
Переглянути файл
@@ -221,7 +221,7 @@ export function selectModel(s: ProjectTreeState): TreeModel {
const contributed = projectViewRoots(extras);
const memberRoots = s.members
?.map((path) => ({ path, label: nameOf(path), icon: "", detail: path }))
.sort((a, b) => compareNames(a.label, b.label));
.sort((a, b) => (a.path === s.root ? -1 : b.path === s.root ? 1 : compareNames(a.label, b.label)));
const project = () =>
memberRoots
? withExtraRoots(EMPTY_MODEL, memberRoots, s.listings, options, placeholder)
+53 -14
Переглянути файл
@@ -83,13 +83,37 @@ function TrustDialog() {
);
}
async function untrustedAttachment() {
const project = useProject.getState().project;
if (!project?.workspace || project.workspace.projects[0] !== project.root) return null;
for (const path of project.workspace.projects) {
const status = await call(commands.projectTrustStatus(path)).catch(() => null);
if (status && !status.trusted) return status;
}
return null;
}
function RestrictedBanner() {
const restricted = useProject((s) => s.project?.trusted === false);
const project = useProject((s) => s.project);
const restricted = project?.trusted === false;
const [blocker, setBlocker] = useState<{ project: typeof project; path: string | null } | null>(null);
const path = blocker?.project === project ? blocker.path : null;
useEffect(() => {
let active = true;
if (restricted)
void untrustedAttachment().then((status) => {
if (active) setBlocker({ project, path: status?.root ?? null });
});
return () => {
active = false;
};
}, [project, restricted]);
return restricted ? (
<div className={styles.banner} role="status">
<span>
<T>Restricted Mode: project commands and tools are disabled.</T>
</span>
{path && <PathLine path={path} />}
<Button onClick={() => void executeAction("project.trust")}>
<T>Trust Project</T>
</Button>
@@ -182,6 +206,32 @@ async function decide(trusted: boolean) {
pending.finish?.(true);
}
function promptForTrust(status: TrustStatus, scope: ProjectTrustScope): Promise<boolean> {
usePrompt.getState().finish?.(false);
return new Promise<boolean>((resolve) =>
usePrompt.setState({
path: status.root,
scope,
folder: false,
finish: (open) => {
usePrompt.setState({ path: null, scope: "current", finish: null, folder: false });
resolve(open);
},
}),
);
}
async function trustProject() {
if (!usePrompt.getState().path) {
const status = await untrustedAttachment();
if (status) {
await promptForTrust(status, "current");
return;
}
}
await decide(true);
}
export function activate(): () => void {
initializeRemoteTrustMigration();
const disposers = [
@@ -190,24 +240,13 @@ export function activate(): () => void {
? invokeLocal<TrustStatus>("project_trust_status", { path })
: call(commands.projectTrustStatus(path)));
if (status.decided) return true;
usePrompt.getState().finish?.(false);
return new Promise<boolean>((resolve) =>
usePrompt.setState({
path: status.root,
scope,
folder: false,
finish: (open) => {
usePrompt.setState({ path: null, scope: "current", finish: null, folder: false });
resolve(open);
},
}),
);
return promptForTrust(status, scope);
}),
registerOverlay({ id: "project.trustDialog", component: TrustDialog }),
registerWorkbenchBanner({ id: "project.restrictedMode", component: RestrictedBanner }),
registerSettingsPage({ id: "projectTrust", title: "Project Trust", group: "Security", component: TrustSettings }),
registerActions([
{ id: "project.trust", title: "Trust Project", category: "Project", run: () => decide(true) },
{ id: "project.trust", title: "Trust Project", category: "Project", run: trustProject },
{
id: "project.previewRestricted",
title: "Preview in Restricted Mode",
+37
Переглянути файл
@@ -139,3 +139,40 @@ it.each(["Trust Project", "Preview in Restricted Mode"])(
expect(useProject.getState().project).toBe(project);
},
);
it.each([false, true])("recovers an attached member whose trust is lost (decided=%s)", async (decided) => {
useProject.setState({
project: {
root: "/primary",
name: "primary",
trusted: false,
isGit: false,
settings: {},
workspace: { version: 1, name: "primary", projects: ["/primary", "/other"] },
},
});
status.mockImplementation(async (root: string) => ({
status: "ok",
data: {
root,
trusted: root === "/primary",
decided: root === "/primary" || decided,
},
}));
const Banner = useContributions.getState().workbenchBanners.get("project.restrictedMode")!.component;
render(
<>
<Banner />
<OverlayHost />
</>,
);
const button = await screen.findByRole("button", { name: "Trust Project" });
await screen.findByText("/other");
fireEvent.click(button);
const dialog = await screen.findByRole("dialog", { name: "Trust and Open Project?" });
expect(dialog).toHaveTextContent("/other");
expect(decide).not.toHaveBeenCalled();
fireEvent.click(screen.getAllByRole("button", { name: "Trust Project" }).at(-1)!);
await act(async () => {});
expect(decide).toHaveBeenCalledWith("/other", true, false);
});
+3 -2
Переглянути файл
@@ -431,8 +431,8 @@ export function activate(): () => void {
// Only while the same project stays open: closing it tears its runs down separately.
useProject.subscribe((s, prev) => {
if (!s.project || s.project.root !== prev.project?.root) return;
const before = prev.project.workspace?.projects ?? [];
const after = s.project.workspace?.projects ?? [];
const before = prev.project.workspace?.projects ?? [prev.project.root];
const after = s.project.workspace?.projects ?? [s.project.root];
for (const root of before) if (!after.includes(root)) void cleanupRemovedProject(root);
}),
registerEditorContribution({ id: "run.targets", order: 55, extensions: runGutter }),
@@ -714,6 +714,7 @@ export function activate(): () => void {
},
]),
onIdeEvent("runExited", (e) => onRunExited(e.run, e.code)),
onIdeEvent("projectRootsChanged", scheduleReload),
// Lets other title items follow the selected configuration (e.g. Build shows only for compiled ones).
useRun.subscribe((s) => {
const selected = s.configs.find((c) => c.id === s.selectedId);
+22
Переглянути файл
@@ -17,6 +17,7 @@ import { ConsoleView, type ConsoleInput } from "./ConsoleView";
import { buildRows, mnemonics } from "./ConfigChooser";
import { activate } from "./index";
import {
onRunExited,
closeSessionTab,
resetRuns,
runtime,
@@ -322,3 +323,24 @@ describe("plugin test selection launches", () => {
}
});
});
describe("Go SDK recovery", () => {
it.each([
["mise ERROR No version is set for shim: go", "go", 1, true],
["No version is set for shim: go", "shell", 1, false],
["compile error", "go", 1, false],
["No version is set for shim: go", "go", 0, false],
] as const)("offers Go settings for %s (%s, %s)", async (text, kind, code, expected) => {
const notify = vi.fn();
provideNotificationService({ notify });
const session = (await startRun(config("go", { kind })))!;
runtime(session.id)!.console.append({ kind: "stderr", text: text.slice(0, 12) });
runtime(session.id)!.console.append({ kind: "stderr", text: text.slice(12) + "\n" });
const runId = 4321 as NonNullable<RunSession["runId"]>;
useRun.setState((s) => ({ sessions: s.sessions.map((x) => ({ ...x, runId })) }));
onRunExited(runId, code);
await vi.waitFor(() => expect(useRun.getState().sessions[0]!.status).toBe("finished"));
expect(notify).toHaveBeenCalledTimes(expected ? 1 : 0);
if (expected) expect(notify.mock.calls[0]![0].actions[0].label).toBe("Go Settings…");
});
});
+17 -1
Переглянути файл
@@ -27,6 +27,7 @@ import {
prepareJavaLaunch,
} from "@/platform/javaLaunch";
import { downloadJdkActions } from "@/platform/jdk";
import { buildToolRecovery } from "@/platform/buildToolRecovery";
import { useProject } from "@/platform/project";
import { executeAction } from "@/platform/actions";
import { workflowSettings } from "@/platform/workflowSettings";
@@ -930,7 +931,7 @@ export async function startRun(
group: "run",
level: "error",
title: `Error running '${remoteLabel(config)}'`,
body: message,
...buildToolRecovery(message),
});
}
return getSession(sessionId) ?? null;
@@ -1103,6 +1104,21 @@ export function testReportEvents(reports: readonly TestCaseReport[]): TestEvent[
function notifyExit(sessionId: string, code: number | null) {
const session = getSession(sessionId);
if (!session || session.stopped || code === 0 || code === null) return;
if (
session.config.kind === "go" &&
!useProject.getState().settings?.languages?.go?.goroot?.trim() &&
/No version (?:is )?set for (?:shim: )?go/i.test(runtimes.get(sessionId)?.console.text() ?? "")
) {
notifications().notify({
group: "run",
level: "error",
key: `run-exit-${sessionId}`,
title: tx("Choose a Go SDK"),
body: tx("The Go version manager has no SDK selected. Choose an installed SDK in Go settings and run again."),
actions: [{ label: tx("Go Settings…"), run: () => void executeAction("file.settings", "languages.go") }],
});
return;
}
let visible = true;
try {
visible = toolWindowService().isVisible("run");
+11 -1
Переглянути файл
@@ -3,9 +3,15 @@ import { formatPattern, formatTimestamp } from "@/platform/dateFormat";
import { resolveThemeId } from "@/workbench/theme";
import { applyAppearanceOptions, nextZoom, SMALL_TREE_INDENT } from "../appearanceRuntime";
import { validateSettings } from "../model/schema";
import { validateAppearanceExtras, validateNotifications } from "../model/behaviorSchema";
import { validateGeneralExtras, validateAppearanceExtras, validateNotifications } from "../model/behaviorSchema";
describe("appearance & behavior settings", () => {
it("defaults automatic update checks to on and respects an explicit opt-out", () => {
expect(validateSettings({}).general.autoCheckUpdates).toBe(true);
expect(validateSettings({ general: { autoCheckUpdates: false } }).general.autoCheckUpdates).toBe(false);
expect(validateSettings({ general: { autoCheckUpdates: "off" } }).general.autoCheckUpdates).toBe(true);
});
it("steps zoom within 50–300%", () => {
expect(nextZoom(100, 1)).toBe(110);
expect(nextZoom(100, -1)).toBe(90);
@@ -121,3 +127,7 @@ describe("appearance & behavior settings", () => {
});
});
});
it("loads an old attach setting as ask", () => {
expect(validateGeneralExtras({ openProjectIn: "attach" }).openProjectIn).toBe("ask");
});
+35
Переглянути файл
@@ -71,6 +71,15 @@ async function openDialog(page?: string) {
}
describe("Settings dialog", () => {
it("offers only new window, current window and ask, including old attach settings", async () => {
current = setAt(current, "general.openProjectIn", "attach");
const dialog = await openDialog("general");
const group = within(dialog).getByRole("radiogroup", { name: "Open project in" });
expect(within(group).getAllByRole("radio")).toHaveLength(3);
expect(within(group).getByRole("radio", { name: "Ask" })).toBeChecked();
expect(within(group).queryByRole("radio", { name: "Attach" })).not.toBeInTheDocument();
});
it("stages properties conversion through its action and applies the checkbox", async () => {
const dialog = await openDialog("editor.fileEncodings");
const checkbox = within(dialog).getByRole("checkbox", { name: "Transparent native-to-ascii conversion" });
@@ -769,3 +778,29 @@ describe("native Settings window background", () => {
}
});
});
it("uses the attached primary name for run-target paths", async () => {
useProject.setState({ project: { name: "primary", displayName: "primary, other", root: "/primary" } as never });
await openDialog("build.runTargets");
fireEvent.click(
within(screen.getByRole("toolbar", { name: "Run targets actions" })).getByRole("button", { name: "Add" }),
);
expect(screen.getByPlaceholderText("~/primary")).toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Type" }));
fireEvent.click(screen.getByRole("option", { name: "Docker" }));
expect(screen.getByPlaceholderText("/workspaces/primary")).toBeInTheDocument();
});
it("uses the primary name for module labels and artifact defaults", async () => {
useProject.setState({ project: { name: "primary", displayName: "primary, other", root: "/primary" } as never });
render(<ProjectStructureDialog />);
await act(async () => executeAction("file.projectStructure", "modules"));
expect(screen.getByRole("button", { name: /primary\s*custom/ })).toBeInTheDocument();
expect(screen.getByRole("tree", { name: "Content root" })).toHaveTextContent("primary");
fireEvent.click(screen.getByRole("button", { name: "Artifacts" }));
// Packaging is pending, but its default generator must still use the primary name.
screen.getByRole("button", { name: "JAR" }).closest("fieldset")!.removeAttribute("disabled");
fireEvent.click(screen.getByRole("button", { name: "JAR" }));
expect(screen.getByLabelText("Name")).toHaveValue("primary:jar");
expect(screen.getByLabelText("Output directory")).toHaveValue("out/artifacts/primary_jar");
});
+5 -2
Переглянути файл
@@ -10,7 +10,7 @@ import { ZOOM_LIMITS } from "@/platform/zoom";
import { validateIconThemeOptionsMap } from "@/platform/iconThemeOptions";
export type Antialiasing = "subpixel" | "greyscale" | "none";
export type OpenProjectIn = "ask" | "new" | "same" | "attach";
export type OpenProjectIn = "ask" | "new" | "same";
export type NotificationDisplay = "balloon" | "sticky" | "none";
/** Themes selectable as "preferred" when syncing with the OS. */
export type ConcreteTheme = ThemeChoiceId;
@@ -62,6 +62,7 @@ export type UpdateSourceSetting = "auto" | "github" | "cnb";
export interface GeneralExtras {
openProjectIn: OpenProjectIn;
updateSource: UpdateSourceSetting;
autoCheckUpdates: boolean;
defaultProjectDirectory: string;
saveOnIdle: boolean;
idleSeconds: number;
@@ -115,6 +116,7 @@ export const DEFAULT_APPEARANCE_EXTRAS: AppearanceExtras = {
export const DEFAULT_GENERAL_EXTRAS: GeneralExtras = {
openProjectIn: "ask",
updateSource: "auto",
autoCheckUpdates: true,
defaultProjectDirectory: "",
saveOnIdle: false,
idleSeconds: 15,
@@ -178,8 +180,9 @@ export function validateGeneralExtras(raw: unknown): GeneralExtras {
const d = DEFAULT_GENERAL_EXTRAS;
const df = obj(g.dateFormat);
return {
openProjectIn: oneOf(g.openProjectIn, ["ask", "new", "same", "attach"] as const, d.openProjectIn),
openProjectIn: oneOf(g.openProjectIn, ["ask", "new", "same"] as const, d.openProjectIn),
updateSource: oneOf(g.updateSource, ["auto", "github", "cnb"] as const, d.updateSource),
autoCheckUpdates: bool(g.autoCheckUpdates, d.autoCheckUpdates),
defaultProjectDirectory: typeof g.defaultProjectDirectory === "string" ? g.defaultProjectDirectory : "",
saveOnIdle: bool(g.saveOnIdle, d.saveOnIdle),
idleSeconds: int(g.idleSeconds, d.idleSeconds, IDLE_LIMITS),
+1 -21
Переглянути файл
@@ -26,7 +26,6 @@ import {
type NotificationDisplay,
type NotificationGroupValid,
type OpenProjectIn,
type UpdateSourceSetting,
} from "../model/behaviorSchema";
import { ACCENT_PRESETS, LIMITS, type ThemeId } from "../model/schema";
import type { PageSpec } from "./spec";
@@ -391,17 +390,10 @@ function ToolWindowsGrid() {
const OPEN_IN: Array<{ value: OpenProjectIn; label: string }> = [
{ value: "new", label: "New window" },
{ value: "attach", label: "Attach" },
{ value: "same", label: "Current window" },
{ value: "ask", label: "Ask" },
];
const UPDATE_SOURCES: SelectOption<UpdateSourceSetting>[] = [
{ value: "auto", label: "Automatic" },
{ value: "github", label: "GitHub" },
{ value: "cnb", label: "CNB (China mirror)" },
];
function OpenProjectInRow() {
const [value, set] = useSetting<OpenProjectIn>("general.openProjectIn");
const name = useId();
@@ -699,7 +691,7 @@ export const BEHAVIOR_PAGES: PageSpec[] = [
{
kind: "custom",
label: "Open project in",
keywords: ["New window", "Current window", "Attach", "Ask"],
keywords: ["New window", "Current window", "Ask"],
component: OpenProjectInRow,
},
{ kind: "custom", label: "Default directory", component: DefaultDirectoryRow },
@@ -749,18 +741,6 @@ export const BEHAVIOR_PAGES: PageSpec[] = [
},
],
},
{
title: "Updates",
options: [
{
kind: "select",
key: "general.updateSource",
label: "Update source",
hint: "Where updates are downloaded from. If it can't be reached, the other source is tried.",
options: UPDATE_SOURCES,
},
],
},
{
title: "Exit",
options: [{ kind: "toggle", key: "general.confirmExit", label: "Confirm before exiting the IDE" }],
+12 -1
Переглянути файл
@@ -1,4 +1,6 @@
/** Registers the built-in pages as ordinary settings-page contributions and indexes their labels. */
import { commands } from "@/platform/ipc";
import { UPDATES_PAGE } from "./updates";
import { onLanguageListChanged } from "@/platform/languageList";
import { registerSettingsPage, type SettingsPageContribution } from "@/workbench/contributions";
import { BEHAVIOR_PAGES } from "./behavior";
@@ -16,6 +18,7 @@ import { VCS_PAGES } from "./vcs";
const BUILTIN_PAGES = [
...BEHAVIOR_PAGES,
UPDATES_PAGE,
...CORE_PAGES,
...EDITOR_PAGES,
...VCS_PAGES,
@@ -55,9 +58,17 @@ function toContribution(spec: PageSpec): SettingsPageContribution {
}
export function registerBuiltinPages(): () => void {
const disposers = BUILTIN_PAGES.map((spec) => registerSettingsPage(toContribution(spec)));
const disposers = BUILTIN_PAGES.filter((spec) => spec !== UPDATES_PAGE).map((spec) =>
registerSettingsPage(toContribution(spec)),
);
// Code Style › <Language> pages come from the backend's language list, which plugins change.
let live = true;
void commands
.appBuildInfo()
.then((info) => {
if (live && info.updates) disposers.push(registerSettingsPage(toContribution(UPDATES_PAGE)));
})
.catch(() => {});
let languagePages: (() => void)[] = [];
let generation = 0;
const loadLanguagePages = () => {
+87
Переглянути файл
@@ -0,0 +1,87 @@
import { useEffect, useState } from "react";
import { executeAction, useActions } from "@/platform/actions";
import { formatClock, formatDay } from "@/platform/dateFormat";
import { call, commands, onIdeEvent, type UpdateStatus } from "@/platform/ipc";
import { useTx } from "@/platform/i18n";
import { Button, T } from "@/ui";
import { Row } from "../components/Form";
import type { PageSpec } from "./spec";
function UpdateStatusRows() {
const tx = useTx();
const [version, setVersion] = useState<string | null>(null);
const [status, setStatus] = useState<UpdateStatus | null>(null);
const canCheck = useActions((s) => s.actions.has("app.checkForUpdates"));
useEffect(() => {
let live = true;
let received = false;
const off = onIdeEvent("updateStatusChanged", ({ status }) => {
received = true;
if (live) setStatus(status);
});
void commands
.appBuildInfo()
.then((info) => live && setVersion(info.version))
.catch(() => {});
void call(commands.appUpdateStatus())
.then((status) => live && !received && setStatus(status))
.catch(() => {});
return () => {
live = false;
off();
};
}, []);
const date = status?.lastChecked == null ? null : new Date(status.lastChecked);
return (
<>
<Row label="Current version">
<span>{version ?? tx("Loading…")}</span>
</Row>
<Row label="Last checked">
<span>{!status ? tx("Loading…") : date ? `${formatDay(date)} ${formatClock(date)}` : tx("Never")}</span>
<Button
disabled={!canCheck || !status || status.checking}
onClick={() => void executeAction("app.checkForUpdates")}
>
<T>{status?.checking ? "Checking for updates…" : "Check Now"}</T>
</Button>
</Row>
</>
);
}
export const UPDATES_PAGE: PageSpec = {
id: "general.updates",
title: "Updates",
order: 3,
keywords: ["update", "upgrade", "version", "automatic", "GitHub", "CNB"],
sections: [
{
options: [
{
kind: "custom",
label: "Current version",
keywords: ["Last checked", "Check Now"],
component: UpdateStatusRows,
},
{
kind: "toggle",
key: "general.autoCheckUpdates",
label: "Check for updates automatically",
hint: "At startup and every 4 hours while OpenIDEA runs. Each new version is announced once per session.",
},
{
kind: "select",
key: "general.updateSource",
label: "Update source",
hint: "Where updates are downloaded from. If it can't be reached, the other source is tried.",
options: [
{ value: "auto", label: "Automatic" },
{ value: "github", label: "GitHub" },
{ value: "cnb", label: "CNB (China mirror)" },
],
},
],
},
],
};
+9 -9
Переглянути файл
@@ -302,7 +302,7 @@ describe("split layout", () => {
});
describe("terminalFont", () => {
const BASE = '"JetBrains Mono Variable", "JetBrains Mono", ui-monospace, Menlo, monospace';
const BASE = '"JetBrains Mono", "JetBrains Mono Variable", ui-monospace, Menlo, monospace';
const t = {
useEditorFont: true,
fontFamily: "JetBrains Mono",
@@ -320,13 +320,13 @@ describe("terminalFont", () => {
"editor font, default family",
t,
editor,
`"JetBrains Mono Variable", "JetBrains Mono", ${BASE.replace(", monospace", "")}, `,
`"JetBrains Mono", "JetBrains Mono Variable", ${BASE.replace(", monospace", "")}, `,
],
[
"editor font, no editor settings",
t,
undefined,
`"JetBrains Mono Variable", "JetBrains Mono", ${BASE.replace(", monospace", "")}, `,
`"JetBrains Mono", "JetBrains Mono Variable", ${BASE.replace(", monospace", "")}, `,
],
[
"editor font, custom family",
@@ -338,13 +338,13 @@ describe("terminalFont", () => {
"editor font, editor fallback",
t,
{ ...editor, fallbackFont: "PingFang SC" },
`"JetBrains Mono Variable", "JetBrains Mono", "PingFang SC", ${BASE.replace(", monospace", "")}, `,
`"JetBrains Mono", "JetBrains Mono Variable", "PingFang SC", ${BASE.replace(", monospace", "")}, `,
],
[
"own font, default family",
{ ...t, useEditorFont: false },
editor,
`"JetBrains Mono Variable", "JetBrains Mono", ${BASE.replace(", monospace", "")}, `,
`"JetBrains Mono", "JetBrains Mono Variable", ${BASE.replace(", monospace", "")}, `,
],
[
"own font, custom + fallback",
@@ -360,14 +360,14 @@ describe("terminalFont", () => {
});
it("resolves bundled Inter in inherited, independent and fallback selections", () => {
expect(terminalFont(t, { ...editor, fontFamily: "Inter" }, BASE).family).toMatch(/^"Inter Variable", "Inter",/);
expect(terminalFont(t, { ...editor, fontFamily: "Inter" }, BASE).family).toMatch(/^"Inter", "Inter Variable",/);
expect(terminalFont({ ...t, useEditorFont: false, fontFamily: "Inter" }, editor, BASE).family).toMatch(
/^"Inter Variable", "Inter",/,
/^"Inter", "Inter Variable",/,
);
expect(terminalFont({ ...t, fallbackFontFamily: "Inter" }, editor, BASE).family).toContain(
'"Inter Variable", "Inter"',
'"Inter", "Inter Variable"',
);
expect(terminalFont(t, { ...editor, fallbackFont: "Inter" }, BASE).family).toContain('"Inter Variable", "Inter"');
expect(terminalFont(t, { ...editor, fallbackFont: "Inter" }, BASE).family).toContain('"Inter", "Inter Variable"');
});
it("prefers the terminal's fallback over the editor's", () => {
+23 -1
Переглянути файл
@@ -23,7 +23,7 @@ import { ChangesTree, nodeMenu } from "../CommitView";
import type { ChangeNode } from "../changes";
import { VcsDialogHost } from "../dialogs";
import { useVcs } from "../store";
import { openDiffDialog } from "../diffDialog";
import { loadDiffDialogSize, openDiffDialog } from "../diffDialog";
const modified = (path: string) => ({
path,
@@ -116,6 +116,28 @@ describe("Commit dialog diff window (#1863)", () => {
await screen.findByRole("dialog", { name: "b.ts (HEAD ↔ Your version)" });
});
it("remembers the resized size for the next opening (#2328)", async () => {
render(<VcsDialogHost />);
let close: () => void = () => {};
act(() => {
close = openDiffDialog({ path: "/p/a.ts", left: { type: "rev", rev: "HEAD" }, right: { type: "worktree" } });
});
await diffDialogs();
// Drag the corner grip; jsdom reports a zero rect so the dialog clamps to its
// minimums — what matters is that the resize end is persisted.
fireEvent.pointerDown(screen.getByRole("separator", { name: "Resize" }), { button: 0, clientX: 0, clientY: 0 });
fireEvent.pointerMove(window, { buttons: 1, clientX: 100, clientY: 80 });
fireEvent.pointerUp(window);
expect(loadDiffDialogSize()).toEqual({ w: 480, h: 280 });
act(() => close());
// A fresh open starts at the remembered size rather than the default.
act(() => {
close = openDiffDialog({ path: "/p/a.ts", left: { type: "rev", rev: "HEAD" }, right: { type: "worktree" } });
});
const reopened = await diffDialogs();
expect([reopened.style.width, reopened.style.height]).toEqual(["480px", "280px"]);
});
it("closes on Jump to Source so the editor it opens is not hidden behind it", async () => {
render(
<>
+41
Переглянути файл
@@ -50,6 +50,9 @@ import { DiffEditorTab } from "../diff-editor-tab";
import { diffInput, withChain, type DiffData } from "../diffInput";
import { useToolWindowLayout } from "@/workbench/toolwindows/store";
import { useProject } from "@/platform/project";
import { applyKeymapSettings, installKeyboardDispatcher, useKeymap } from "@/platform/keymap";
import { setContext } from "@/platform/context";
import { registerCompareActions } from "../compare";
/** Git Log opens a commit's file: both sides are revisions. */
const input = {
@@ -456,6 +459,44 @@ describe("Jump to Source of a revision diff", () => {
render(<DiffEditor input={input} />);
expect(await jumpFrom(0, 2)).toEqual(["/p/a.ts", { selection: { line: 5, col: 1 }, focus: true }]);
});
it("jumps on ⌘↓ in the IntelliJ macOS keymap only while a diff pane has focus", async () => {
setUp();
const keymap = useKeymap.getState();
applyKeymapSettings("intellij-macos", {});
const unregister = registerCompareActions();
const uninstall = installKeyboardDispatcher(window);
const cmdDown = (target: EventTarget) => {
const e = new KeyboardEvent("keydown", {
key: "ArrowDown",
code: "ArrowDown",
metaKey: true,
bubbles: true,
cancelable: true,
});
target.dispatchEvent(e);
return e;
};
try {
render(<DiffEditor input={input} />);
const v = await pane(1);
v.dispatch({ selection: { anchor: v.state.doc.line(3).from + 1 } });
v.contentDOM.dispatchEvent(new FocusEvent("focus"));
v.contentDOM.dispatchEvent(new FocusEvent("focusin", { bubbles: true }));
expect(cmdDown(v.contentDOM).defaultPrevented).toBe(true);
await waitFor(() => expect(openFile).toHaveBeenCalled());
expect(openFile.mock.calls[0]).toEqual(["/p/a.ts", { selection: { line: 3, col: 1 }, focus: true }]);
setContext("diffEditorFocus", false);
const plain = document.body.appendChild(document.createElement("div"));
expect(cmdDown(plain).defaultPrevented).toBe(false);
plain.remove();
} finally {
uninstall();
unregister();
useKeymap.setState(keymap);
}
});
});
describe("Unified Revert", () => {
+112
Переглянути файл
@@ -0,0 +1,112 @@
import { beforeEach, expect, it, vi } from "vitest";
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
import type { RemoteOp } from "@/bindings";
const mocks = vi.hoisted(() => ({
ops: [] as Array<{ repo: string | null; op: RemoteOp }>,
failing: new Set<string>(),
}));
vi.mock("@tauri-apps/api/core", async (importOriginal) => ({
...(await importOriginal<typeof import("@tauri-apps/api/core")>()),
Channel: class {
onmessage: (line: string) => void = () => {};
},
}));
vi.mock("@/platform/ipc", async (importOriginal) => {
const real = await importOriginal<typeof import("@/platform/ipc")>();
const ok = (data: unknown) => Promise.resolve({ status: "ok" as const, data });
const remote = (name: string) => ({ name, fetchUrl: `/remotes/${name}`, pushUrl: `/remotes/${name}` });
return {
...real,
commands: {
...real.commands,
vcsBranchInfo: (repo: string) =>
ok({ head: "feat-x", headCommit: "c1", upstream: "origin/feat-x", ahead: 1, behind: 0, operation: null, repo }),
vcsRemotes: (repo: string) => ok(repo === "/p/b" ? [remote("origin"), remote("fork")] : [remote("origin")]),
vcsLog: (repo: string) =>
ok([{ id: `${repo}-1`, shortId: "c1", parents: ["c0"], summary: "Work", author: "me", timeMs: 0 }]),
vcsHasHook: () => ok(false),
vcsRemote: (repo: string | null, _request: number, op: RemoteOp) => {
mocks.ops.push({ repo, op });
return repo && mocks.failing.has(repo)
? Promise.resolve({ status: "error", error: { kind: "failed", message: "remote hung up" } })
: ok(null);
},
cancelRequest: () => ok(null),
},
};
});
import { provideNotificationService } from "@/workbench/contributions";
import { VcsDialogHost } from "../dialogs";
import { showPushDialog } from "../remoteUi";
import { useVcs } from "../store";
type Note = { title: string; body?: string };
let notes: Note[] = [];
beforeEach(() => {
mocks.ops = [];
mocks.failing = new Set();
notes = [];
useVcs.setState({ root: "/p", roots: ["/p/a", "/p/b", "/p/c"], repo: "/p/a", remoteBusy: null, available: false });
provideNotificationService({ notify: (n) => void notes.push(n as Note), expire: () => {} });
});
it("pushes each repository to its own remote and target branch, reporting the one that failed", async () => {
mocks.failing.add("/p/b");
render(<VcsDialogHost />);
await act(() => showPushDialog());
const targetOfA = await screen.findByRole("textbox", { name: "Target branch of a" });
expect(targetOfA).toHaveValue("feat-x");
expect(screen.getByRole("checkbox", { name: "Push tags:" })).toBeInTheDocument();
fireEvent.change(targetOfA, { target: { value: "release-2.1" } });
// A retargeted push carries no tags, as in the single-repository dialog.
expect(screen.queryByRole("checkbox", { name: "Push tags:" })).toBeNull();
// Only a repository with several remotes offers to pick one.
expect(screen.queryByRole("button", { name: "Remote of a" })).toBeNull();
fireEvent.click(screen.getByRole("button", { name: "Remote of b" }));
fireEvent.click(await screen.findByRole("option", { name: "fork" }));
fireEvent.click(screen.getByRole("button", { name: "Push" }));
await waitFor(() => expect(mocks.ops).toHaveLength(3));
expect(mocks.ops).toEqual([
{
repo: "/p/a",
op: {
op: "pushBranch",
branch: "feat-x",
revision: null,
force_with_lease: false,
target: "release-2.1",
remote: null,
set_upstream: false,
no_verify: false,
},
},
{
repo: "/p/b",
op: {
op: "pushBranch",
branch: "feat-x",
revision: null,
force_with_lease: false,
target: null,
remote: "fork",
set_upstream: false,
no_verify: false,
},
},
{
repo: "/p/c",
op: { op: "push", force_with_lease: false, set_upstream: false, tags: null, no_verify: false },
},
]);
await waitFor(() => expect(notes.map((n) => n.title)).toContain("Push partially failed"));
expect(notes.find((n) => n.title === "Push partially failed")?.body).toContain("Not pushed: b.");
});
+88
Переглянути файл
@@ -0,0 +1,88 @@
import { describe, expect, it } from "vitest";
import { pushOperation, type PushChoice } from "../pushTarget";
const tracked: PushChoice = {
head: "feat-x",
tracked: "origin/feat-x",
remote: "origin",
target: "feat-x",
forceWithLease: false,
setUpstream: false,
tags: null,
noVerify: false,
};
describe("the operation a push dialog sends", () => {
it("is the plain push of the tracked branch while remote and target are unchanged", () => {
expect(pushOperation({ ...tracked, tags: "all" })).toEqual({
op: "push",
force_with_lease: false,
set_upstream: false,
tags: "all",
no_verify: false,
});
// No remote picked yet, or the default name with stray spaces, or a cleared field.
expect(pushOperation({ ...tracked, remote: null }).op).toBe("push");
expect(pushOperation({ ...tracked, target: " feat-x " }).op).toBe("push");
expect(pushOperation({ ...tracked, target: "" }).op).toBe("push");
});
it("pushes to another branch of the tracked remote when the target changes", () => {
expect(pushOperation({ ...tracked, target: " release-2.1 " })).toEqual({
op: "pushBranch",
branch: "feat-x",
revision: null,
force_with_lease: false,
target: "release-2.1",
remote: null,
set_upstream: false,
no_verify: false,
});
});
it("pushes the tracked branch name to another remote when the remote changes", () => {
expect(pushOperation({ ...tracked, remote: "fork" })).toMatchObject({
op: "pushBranch",
branch: "feat-x",
target: null,
remote: "fork",
});
});
it("sets the upstream of a branch without one on the plain push", () => {
expect(pushOperation({ ...tracked, tracked: null, remote: null })).toMatchObject({
op: "push",
set_upstream: true,
});
expect(pushOperation({ ...tracked, tracked: null, remote: null, target: "feat-y" })).toMatchObject({
op: "pushBranch",
target: "feat-y",
remote: null,
});
});
it("keeps force-with-lease and the hook choice on both kinds", () => {
const force = { ...tracked, forceWithLease: true, noVerify: true };
expect(pushOperation(force)).toMatchObject({ op: "push", force_with_lease: true, no_verify: true });
expect(pushOperation({ ...force, target: "release-2.1" })).toMatchObject({
op: "pushBranch",
force_with_lease: true,
no_verify: true,
});
});
it("drops tags once the target changes: pushing a branch carries none", () => {
const op = pushOperation({ ...tracked, tags: "all", target: "release-2.1" });
expect(op.op).toBe("pushBranch");
expect(op).not.toHaveProperty("tags");
});
it("pushes another branch or a revision explicitly, without moving the upstream of a partial push", () => {
expect(pushOperation({ ...tracked, explicit: true })).toMatchObject({ op: "pushBranch", target: null });
expect(pushOperation({ ...tracked, explicit: true, revision: "abc123", setUpstream: true })).toMatchObject({
op: "pushBranch",
revision: "abc123",
set_upstream: false,
});
});
});
+8
Переглянути файл
@@ -69,6 +69,14 @@ describe("push result notification", () => {
expect(await pushTitle()).toMatch(/successful$/);
});
it("does not name the upstream when the push went to another remote", async () => {
// `ahead` counts against the upstream, so it says nothing about what another remote received.
branch = { upstream: "origin/main", ahead: 1 };
const op = { op: "pushBranch", branch: "main", remote: "fork", target: null } as never;
expect(await runRemote(op, undefined, ["/p"])).toBe(true);
expect(notes.at(-1)!.title).toMatch(/successful$/);
});
it("is translated as a whole, count included", async () => {
await setLocale("zh");
branch = { upstream: "origin/main", ahead: 3 };
+1 -1
Переглянути файл
@@ -313,8 +313,8 @@ export const viewerHighlight = HighlightStyle.define([
export const viewerTheme = EditorView.theme(
{
...overviewStyles,
"&.cm-editor": { height: "100%" },
"&": {
height: "100%",
backgroundColor: "var(--bg-app)",
color: "var(--fg)",
fontSize: "var(--openidea-editor-font-size, var(--fs-code))",
+23
Переглянути файл
@@ -275,6 +275,29 @@
width: 220px;
margin-left: 6px;
}
/* Fits the remote and target fields into a 22px tree row. */
.pushRowTarget {
--h-field: var(--h-control-small);
--h-control: var(--h-control-small);
display: inline-flex;
align-items: center;
gap: 2px;
min-width: 0;
font-size: var(--fs-small);
}
.pushRowTarget button {
font-size: var(--fs-small);
}
.pushRowSeparator {
color: var(--fg-faint);
}
.pushRowInput {
min-width: 0;
font-size: var(--fs-small);
}
.pushRowInput[data-changed]:not(:focus-visible) {
box-shadow: inset 0 0 0 1px var(--accent);
}
.choiceList {
max-height: 240px;
overflow: auto;
+30 -1
Переглянути файл
@@ -15,6 +15,26 @@ import { diffInput, diffTitle, type DiffData } from "./diffInput";
import { openDialog } from "./dialogs";
import { GitMergeDiff } from "./GitMergeDiff";
const SIZE_KEY = "openidea.vcs.diffDialogSize";
/** The diff window's last size (#2328); null on first run, clamped to the window by Dialog. */
export function loadDiffDialogSize(): { w: number; h: number } | null {
try {
const v = JSON.parse(localStorage.getItem(SIZE_KEY) ?? "null") as { w?: unknown; h?: unknown } | null;
return typeof v?.w === "number" && typeof v.h === "number" ? { w: v.w, h: v.h } : null;
} catch {
return null;
}
}
export function saveDiffDialogSize(size: { w: number; h: number }) {
try {
localStorage.setItem(SIZE_KEY, JSON.stringify(size));
} catch {
// Private mode etc. — the size just isn't remembered.
}
}
/** The open diff dialog's close function (one diff window at a time, as in IDEA). */
let shown: (() => void) | null = null;
@@ -52,6 +72,14 @@ export function openMergeDiffDialog(input: EditorInput): () => void {
function FrontWindow({ title, onClose, children }: { title: string; onClose: () => void; children: ReactNode }) {
const body = useRef<HTMLDivElement>(null);
// The size the user last resized the diff window to (#2328), else the usual default.
const [initialSize] = useState(
() =>
loadDiffDialogSize() ?? {
w: Math.min(1100, globalThis.innerWidth - 64),
h: Math.min(720, globalThis.innerHeight - 64),
},
);
useEffect(
() =>
registerKeyClaim((e, stroke) => {
@@ -74,7 +102,8 @@ function FrontWindow({ title, onClose, children }: { title: string; onClose: ()
resizable="both"
minWidth={480}
minHeight={280}
initialSize={{ w: Math.min(1100, globalThis.innerWidth - 64), h: Math.min(720, globalThis.innerHeight - 64) }}
initialSize={initialSize}
onResized={saveDiffDialogSize}
buttons={[{ label: "Close", role: "cancel" }]}
>
<div
+2 -1
Переглянути файл
@@ -211,7 +211,8 @@ export async function runRemote(
const before = isUpdate(op) ? await publishedTip(repo, op) : null;
// The push summary counts what the push carries: the commits the branch is
// ahead of its upstream before the push (pushing does not move the local head).
if (op.op === "push" || (op.op === "pushBranch" && !op.target)) {
// Another remote or target receives other commits than "ahead of the upstream".
if (op.op === "push" || (op.op === "pushBranch" && !op.target && !op.remote)) {
const info = await call(commands.vcsBranchInfo(repo)).catch(() => null);
if (info?.upstream && info.ahead > 0) pushed.push({ to: info.upstream, commits: info.ahead });
}
+62
Переглянути файл
@@ -0,0 +1,62 @@
/** Which push a Push dialog sends for one repository, from the remote and target picked in it. */
import type { PushTags, RemoteOp } from "@/bindings";
export type PushOp = Extract<RemoteOp, { op: "push" | "pushBranch" }>;
export interface PushChoice {
/** Local branch being pushed. */
head: string;
/** Its upstream as `remote/branch`, or null. */
tracked: string | null;
/** Remote picked in the dialog; null keeps the tracked one. */
remote: string | null;
/** Target branch field as typed; empty keeps the default. */
target: string;
/** Another branch than the checked-out one: always pushed by name. */
explicit?: boolean;
/** Push only up to this commit. */
revision?: string | null;
forceWithLease: boolean;
setUpstream: boolean;
/** Dropped once the push is retargeted: `pushBranch` carries no tags. */
tags: PushTags | null;
noVerify: boolean;
}
/** `remote/branch` split at the first slash. */
export function splitTracked(tracked: string): { remote: string; branch: string } {
const slash = tracked.indexOf("/");
return { remote: tracked.slice(0, slash), branch: tracked.slice(slash + 1) };
}
/**
* The plain push while remote and target are those of the upstream, which keeps tags
* and the update-and-retry of a rejected push; otherwise `git push <remote> <src>:<dst>`
* naming only what differs from the upstream.
*/
export function pushOperation(c: PushChoice): PushOp {
const upstream = c.tracked ? splitTracked(c.tracked) : null;
const defaultTarget = upstream?.branch ?? c.head;
const edited = c.target.trim();
const retarget = !!edited && edited !== defaultTarget;
const remoteChanged = !!c.remote && c.remote !== (upstream?.remote ?? null);
const revision = c.revision ?? null;
if (c.explicit || revision || retarget || remoteChanged)
return {
op: "pushBranch",
branch: c.head,
revision,
force_with_lease: c.forceWithLease,
target: retarget ? edited : null,
remote: remoteChanged ? c.remote : null,
set_upstream: c.setUpstream && !revision,
no_verify: c.noVerify,
};
return {
op: "push",
force_with_lease: c.forceWithLease,
set_upstream: c.setUpstream || !c.tracked,
tags: c.tags,
no_verify: c.noVerify,
};
}
+144 -57
Переглянути файл
@@ -25,6 +25,7 @@ import { openDialog } from "./dialogs";
import { formatTime } from "./model";
import { allRepos, lastRemoteFailure, runRemote, saveAll } from "./ops";
import { PushChanges, pushChangesKey } from "./PushChanges";
import { pushOperation, splitTracked, type PushChoice } from "./pushTarget";
import { currentRepo, refreshNow, repoName, useVcs } from "./store";
import styles from "./common.module.css";
@@ -242,6 +243,10 @@ function MultiPushDialog({ onClose }: { onClose: () => void }) {
const [tagsMode, setTagsMode] = useState<PushTags>("all");
const hasHook = usePrePushHook(roots);
const [runHooks, setRunHooks] = useState(true);
const [remotesOf, setRemotesOf] = useState<Record<string, string[]>>({});
const [edits, setEdits] = useState<Record<string, { remote?: string; target?: string }>>({});
const edit = (root: string, change: { remote?: string; target?: string }) =>
setEdits((prev) => ({ ...prev, [root]: { ...prev[root], ...change } }));
useEffect(() => {
let alive = true;
@@ -249,12 +254,16 @@ function MultiPushDialog({ onClose }: { onClose: () => void }) {
// branch falls back to recent history (pushRepoCommits) and stays pushable.
Promise.allSettled(
roots.map(async (root) => {
const remotes = call(commands.vcsRemotes(root)).catch(() => []);
const branch = await call(commands.vcsBranchInfo(root));
return { root, branch, commits: await pushRepoCommits(root, branch) };
const commits = await pushRepoCommits(root, branch);
return { repo: { root, branch, commits }, remotes: (await remotes).map((r) => r.name) };
}),
).then((results) => {
if (!alive) return;
const loaded = results.flatMap((r) => (r.status === "fulfilled" ? [r.value] : []));
const fulfilled = results.flatMap((r) => (r.status === "fulfilled" ? [r.value] : []));
const loaded = fulfilled.map((r) => r.repo);
setRemotesOf(Object.fromEntries(fulfilled.map((r) => [r.repo.root, r.remotes])));
const failed = results.find((r): r is PromiseRejectedResult => r.status === "rejected");
if (!loaded.length && failed) {
setError(failed.reason instanceof Error ? failed.reason.message : String(failed.reason));
@@ -275,9 +284,28 @@ function MultiPushDialog({ onClose }: { onClose: () => void }) {
if (!next.delete(root)) next.add(root);
return next;
});
const targetOf = (r: RepoPush) =>
r.branch.upstream ? r.branch.upstream.slice(r.branch.upstream.indexOf("/") + 1) : r.branch.head!;
const targetOf = (r: RepoPush) => (r.branch.upstream ? splitTracked(r.branch.upstream).branch : r.branch.head!);
const trackedRemoteOf = (r: RepoPush) => (r.branch.upstream ? splitTracked(r.branch.upstream).remote : null);
const shownRemoteOf = (r: RepoPush) => {
const remotes = remotesOf[r.root] ?? [];
return (
edits[r.root]?.remote ?? trackedRemoteOf(r) ?? (remotes.includes("origin") ? "origin" : (remotes[0] ?? null))
);
};
const targetNameOf = (r: RepoPush) => edits[r.root]?.target?.trim() || targetOf(r);
const choiceOf = (r: RepoPush, tags: PushTags | null): PushChoice => ({
head: r.branch.head!,
tracked: r.branch.upstream,
remote: edits[r.root]?.remote ?? null,
target: edits[r.root]?.target ?? "",
forceWithLease: force && !isProtectedBranch(targetNameOf(r)),
setUpstream: false,
tags,
noVerify: hasHook && !runHooks,
});
const picked = (repos ?? []).filter((r) => checked.has(r.root));
// Like the single-repository dialog: tags go only with plain pushes, so a retargeted repository hides them.
const retargeted = picked.some((r) => pushOperation(choiceOf(r, null)).op === "pushBranch");
const push = async () => {
onClose();
// Every picked repository is pushed even when another fails; the outcome is summed up.
@@ -285,19 +313,20 @@ function MultiPushDialog({ onClose }: { onClose: () => void }) {
const failed: string[] = [];
for (const r of picked) {
const upstream = r.branch.upstream;
const ok = await pushWithAutoUpdate(
{
op: "push",
force_with_lease: force && !isProtectedBranch(targetOf(r)),
set_upstream: !upstream,
tags: pushTags ? tagsMode : null,
no_verify: hasHook && !runHooks,
},
`${repoName(r.root)}: ${r.branch.head} → ${upstream ?? "new remote branch"}`,
r.root,
session,
);
if (!ok) failed.push(repoName(r.root));
const op = pushOperation(choiceOf(r, pushTags && !retargeted ? tagsMode : null));
const name = repoName(r.root);
const remote = shownRemoteOf(r);
// A retargeted push names a branch, so it has no tracked branch to update from when rejected.
const ok =
op.op === "pushBranch"
? await runRemote(op, `${name}: ${r.branch.head} → ${remote ? `${remote}/` : ""}${targetNameOf(r)}`, [r.root])
: await pushWithAutoUpdate(
op,
`${name}: ${r.branch.head} → ${upstream ?? "new remote branch"}`,
r.root,
session,
);
if (!ok) failed.push(name);
}
const notPushed = failed.join(", ");
if (failed.length && picked.length > 1)
@@ -331,17 +360,21 @@ function MultiPushDialog({ onClose }: { onClose: () => void }) {
<>
<Checkbox checked={force} onChange={setForce} label="Force (with lease)" />
{hasHook && <Checkbox checked={runHooks} onChange={setRunHooks} label="Run Git hooks" />}
<Checkbox checked={pushTags} onChange={setPushTags} label="Push tags:" />
<Select<PushTags>
value={tagsMode}
disabled={!pushTags}
aria-label="Tags to push"
onChange={setTagsMode}
options={[
{ value: "all", label: "All" },
{ value: "currentBranch", label: "Current Branch" },
]}
/>
{!retargeted && (
<>
<Checkbox checked={pushTags} onChange={setPushTags} label="Push tags:" />
<Select<PushTags>
value={tagsMode}
disabled={!pushTags}
aria-label="Tags to push"
onChange={setTagsMode}
options={[
{ value: "all", label: "All" },
{ value: "currentBranch", label: "Current Branch" },
]}
/>
</>
)}
</>
}
buttons={[
@@ -411,9 +444,20 @@ function MultiPushDialog({ onClose }: { onClose: () => void }) {
onChange={() => toggle(n.repo.root)}
label={repoName(n.repo.root)}
/>
<span className={styles.commitMeta}>
{n.repo.branch.head} → {n.repo.branch.upstream ?? tx("new remote branch")}
</span>
<span className={styles.commitMeta}>{n.repo.branch.head} →</span>
<PushRowTarget
name={repoName(n.repo.root)}
remotes={remotesOf[n.repo.root] ?? []}
remote={shownRemoteOf(n.repo)}
onRemote={(remote) => edit(n.repo.root, { remote })}
target={edits[n.repo.root]?.target ?? targetOf(n.repo)}
onTarget={(target) => edit(n.repo.root, { target })}
changed={pushOperation(choiceOf(n.repo, null)).op === "pushBranch"}
onEnter={() => {
if (picked.length) void push();
}}
/>
{!n.repo.branch.upstream && <span className={styles.commitMeta}>{tx("new remote branch")}</span>}
</span>
)
}
@@ -427,6 +471,59 @@ function MultiPushDialog({ onClose }: { onClose: () => void }) {
);
}
/** The remote and target branch of one repository's row in the multi-repository Push tree. */
function PushRowTarget(props: {
name: string;
remotes: string[];
remote: string | null;
onRemote: (remote: string) => void;
target: string;
onTarget: (target: string) => void;
/** Pushed elsewhere than to the upstream: the field is marked so the difference is not missed. */
changed: boolean;
onEnter: () => void;
}) {
return (
<span
className={styles.pushRowTarget}
// The tree would take typed keys for speed search and navigation, and a click for toggling the row.
onKeyDown={(e) => {
if (e.key !== "Escape" && e.key !== "Tab") e.stopPropagation();
}}
onClick={(e) => e.stopPropagation()}
onDoubleClick={(e) => e.stopPropagation()}
>
{props.remotes.length > 1 ? (
<Select<string>
variant="ghost"
value={props.remote ?? ""}
aria-label={tx`Remote of ${props.name}`}
onChange={props.onRemote}
options={props.remotes.map((r) => ({ value: r, label: r }))}
/>
) : (
props.remote && <span className={styles.commitMeta}>{props.remote}</span>
)}
{props.remote && <span className={styles.pushRowSeparator}>/</span>}
<Input
aria-label={tx`Target branch of ${props.name}`}
mono
value={props.target}
data-changed={props.changed || undefined}
// Mono, so `ch` is exact: the field follows the branch name instead of a fixed width.
style={{ width: `${Math.min(32, Math.max(10, props.target.length + 3))}ch` }}
onChange={(e) => props.onTarget(e.target.value)}
onKeyDown={(e) => {
if (e.key !== "Enter" || e.nativeEvent.isComposing) return;
e.preventDefault();
props.onEnter();
}}
className={styles.pushRowInput}
/>
</span>
);
}
function PushDialog({ target: pushTarget, onClose }: { target: PushTarget; onClose: () => void }) {
const [repo] = useState(currentRepo);
const [branch] = useState(() => useVcs.getState().branch);
@@ -515,34 +612,24 @@ function PushDialog({ target: pushTarget, onClose }: { target: PushTarget; onClo
const push = async () => {
if (force && !protectedTarget && !(await confirmForcePush(remote ? `${remote}/${target}` : (target ?? "")))) return;
onClose();
if ((explicit || retarget || remoteChanged) && head) {
await runRemote(
{
op: "pushBranch",
branch: head,
revision,
force_with_lease: force && !protectedTarget,
target: retarget ? edited : null,
remote: remoteChanged ? remote : null,
set_upstream: setUpstream && !revision,
no_verify: hasHook && !runHooks,
},
`${revision ? `${head} up to ${revision.slice(0, 8)}` : head} → ${targetLabel}`,
[repo],
);
if (!head) return;
const op = pushOperation({
head,
tracked,
remote,
target: targetName,
explicit,
revision,
forceWithLease: force && !protectedTarget,
setUpstream,
tags: pushTags ? tagsMode : null,
noVerify: hasHook && !runHooks,
});
if (op.op === "pushBranch") {
await runRemote(op, `${revision ? `${head} up to ${revision.slice(0, 8)}` : head} → ${targetLabel}`, [repo]);
return;
}
await pushWithAutoUpdate(
{
op: "push",
force_with_lease: force && !protectedTarget,
set_upstream: setUpstream || !upstream,
tags: pushTags ? tagsMode : null,
no_verify: hasHook && !runHooks,
},
upstream ? `${head} → ${upstream}` : `${head} → new remote branch`,
repo,
);
await pushWithAutoUpdate(op, upstream ? `${head} → ${upstream}` : `${head} → new remote branch`, repo);
};
const commitList = (
+76
Переглянути файл
@@ -156,6 +156,82 @@ describe("Vim engine", () => {
view.destroy();
});
it.each([
['let mapleader = " "', ["<Space>", "f", "f"]],
['let mapleader = ","', [",", "f", "f"]],
['let mapleader = "\\\\"', ["\\", "f", "f"]],
])("runs a <leader> mapping whose first key shadows a built-in (%s)", async (leader, keys) => {
const ran: string[] = [];
const d = registerAction({ id: "navigate.gotoFile", title: "x", run: () => void ran.push("navigate.gotoFile") });
const view = makeView();
const cm = getCM(view)!;
applyRcCommands(parseVimrc(`${leader}\nnmap <leader>ff <Action>(GotoFile)`).commands);
for (const k of keys) Vim.handleKey(cm as never, k, "user");
await tick();
expect(ran).toEqual(["navigate.gotoFile"]);
view.destroy();
d();
});
it.each([
["nmap dx <Action>(GotoFile)", ["d", "w"], "two\nthree"],
["nmap cs <Action>(GotoFile)", ["c", "w"], " two\nthree"],
["nnoremap yz yy", ["y", "y", "p"], "one two\none two\nthree"],
])("keeps built-in operators a mapping starts with (%s)", async (rc, keys, doc) => {
const view = makeView();
const cm = getCM(view)!;
applyRcCommands(parseVimrc(rc).commands);
for (const k of keys) Vim.handleKey(cm as never, k, "user");
await tick();
expect(view.state.doc.toString()).toBe(doc);
applyRcCommands([]);
view.destroy();
});
it("keeps built-ins and user mappings consistent across rc reloads that change the leader", async () => {
const ran: string[] = [];
const d = registerAction({ id: "navigate.gotoFile", title: "x", run: () => void ran.push("navigate.gotoFile") });
const view = makeView();
const cm = getCM(view)!;
const keys = (...ks: string[]) => ks.forEach((k) => Vim.handleKey(cm as never, k, "user"));
applyRcCommands(parseVimrc('let mapleader = " "\nnmap <leader>ff <Action>(GotoFile)').commands);
applyRcCommands(parseVimrc('let mapleader = ","\nnmap <leader>ff <Action>(GotoFile)').commands);
applyRcCommands(parseVimrc('let mapleader = " "\nnmap <leader>ff <Action>(GotoFile)\nnnoremap Q dd').commands);
keys("<Space>", "f", "f");
await tick();
expect(ran).toEqual(["navigate.gotoFile"]);
// noremap still reaches the built-ins with a stand-in in the default keymap.
keys("Q");
await tick();
expect(view.state.doc.toString()).toBe("three");
applyRcCommands([]);
applyRcCommands([]);
view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: "axbxcx" }, selection: { anchor: 0 } });
keys("<Space>");
await tick();
expect(view.state.selection.main.head).toBe(1);
keys("f", "x", ";", ",");
await tick();
expect(view.state.selection.main.head).toBe(3);
keys("<Space>", "f", "f");
await tick();
expect(ran).toEqual(["navigate.gotoFile"]);
view.destroy();
d();
});
it("restores the built-in key the leader shadowed once the rc stops using it (#2337)", async () => {
const view = makeView();
const cm = getCM(view)!;
applyRcCommands(parseVimrc('let mapleader = " "\nnmap <leader>ff <Action>(GotoFile)').commands);
// A later rc without the space leader puts <Space> → l back.
applyRcCommands(parseVimrc("nmap gd <Action>(GotoDeclaration)").commands);
Vim.handleKey(cm as never, "<Space>", "user");
await tick();
expect(view.state.selection.main.head).toBe(1);
view.destroy();
});
it("keeps an IME composition out of the document in Normal mode", async () => {
const transient: boolean[] = [];
const view = makeView([
Loaded 100 of 130 files, more files were not shown because too many files have changed in this diff. Show more