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

...
Автор SHA1 Повідомлення Дата
l0ng-ai 75d62c4961 feat(lsp): configure a language server from the status bar popup
Each server in the Language Servers popup gets a Configure button that opens Settings › Language Servers on that server's language with the server selected, where the interchangeable servers are chosen and additional ones turned off. tools.languageServers takes the server name and opens the page as languages.servers#<name>; the page selects that tool and scrolls its language into view.
2026-11-18 20:08:21 +08:00
Vladislav Kuzmin 0021a764c3 fix(database): connect to ClickHouse accounts with strict read-only settings (#4292)
A ClickHouse account with server-enforced readonly = 1 rejected the HTTP driver's own per-query settings (Code 164) on the connection probe. When the probe fails on one of those settings, the driver checks getSetting('readonly') in the same session and, only when it is 1, sends further requests without its own settings (the server then provides write protection; the client still caps the grid rows). A writable session that reports the error keeps failing as before.

Closes #4275

Co-authored-by: principalwater <[email protected]>
2026-11-18 20:01:45 +08:00
Mollo-i a30103d410 feat(nav): @property@ in YAML and properties resources jumps to its pom properties entry (#4243)
Go to Declaration on a Maven resource-filtering placeholder (`@profileActive@` in `application.yml` or `application.properties`) jumps to the `<properties>` entry that defines it: the nearest `pom.xml` above the resource, up through the project root, is searched along its parent chain with the lookup the pom's own `${property}` navigation uses (now exposed as `ide_build::maven::property_declaration`). Plugin definition providers still run, with the pom result first.

Closes #4241

Co-authored-by: Greenker <[email protected]>
2026-11-18 20:00:25 +08:00
Mollo-i 89798baa3c fix(lsp): a Maven resource-filtering placeholder no longer fails YAML parsing (#4242)
yaml-language-server reports "Plain value cannot start with reserved character @" for unquoted Maven placeholders such as `spring.profiles.active: @profileActive@`, which Maven replaces before the file is read as YAML. The diagnostic is dropped when its scalar is exactly an `@token@` placeholder; other parser errors (an unpaired `@`, a different message, a stale range) still show.

Co-authored-by: Greenker <[email protected]>
2026-11-18 20:00:10 +08:00
l0ng-ai c09c9b8aaf docs: describe the Linux DMA-BUF workaround for unresponsive windows (#4295)
The troubleshooting entry still said NVIDIA on Wayland gets WEBKIT_DISABLE_DMABUF_RENDERER=1; since #2179 the app turns the driver's explicit sync off instead. The entry now covers windows that stop reacting to input, notes the slower CPU drawing, and shows how to keep the variable for menu launches.
2026-11-18 19:50:24 +08:00
l0ng-ai 995a9563f7 feat(profiler): navigate and zoom the flame graph with the keyboard (#4294)
The flame graph had no keyboard focus target. It is now focusable with a current frame (outlined, announced via aria-activedescendant): Up/Down go to callee/caller, Left/Right to neighbours, Enter zooms, Escape resets, F4 opens the source. Fixes #4209.
2026-11-18 19:45:37 +08:00
l0ng-ai 893d9af6e6 fix(inspections): Rerun Inspection repeats the file its results are for (#4291)
A Current file inspection stored its unresolved scope, so Rerun resolved it to whichever file was active. The run now records the file it inspected and Rerun inspects that file again. Fixes #4234.
2026-11-18 19:42:27 +08:00
l0ng-ai 73496669e7 fix(web): the built-in preview reloads only for the page and web resources (#4290)
The HTML preview reloaded on any project file change or document save, so editing notes.txt cleared the page's inputs and scroll position. It now reloads when the page itself or a web resource changes. Fixes #4231.
2026-11-18 19:41:01 +08:00
l0ng-ai add914f7fb fix(markdown): a word double-clicked in the preview leaves out the space after it (#4288)
On Windows a double-click selects the word plus the following space, so the preview's selection highlights and Find used "Order ". A word selection's trailing whitespace is now dropped from the text and, when it ends in a text node, from the selection itself. Fixes #4230.
2026-11-18 19:37:24 +08:00
l0ng-ai 0fd0f08865 fix(search): Replace All saves open documents that had no unsaved changes (#4286)
Replace All saved only files it opened itself, so a file the search preview held open got the replacement in memory but not on disk. Documents without unsaved changes are now saved after the replacement; buffers the user is editing are left unsaved. Fixes #4202.
2026-11-18 19:35:26 +08:00
l0ng-ai 054d2ba517 fix(toolwindows): show Hide All Tool Windows as Restore Tool Windows when it restores (#4277)
With every window hidden, Hide All restores them but kept its Hide label. The actions registry gets retitleAction for titles that follow state; the action and its menu label read Restore Tool Windows while a hidden set can be restored. Fixes #4162.
2026-11-18 19:27:54 +08:00
l0ng-ai 738dc12ef7 fix(libraries): clear the previous project's External Libraries on switching (#4276)
The External Libraries node and last complete result were kept across a project switch until the new discovery answered, so the new project showed and filled in the old project's libraries. Refreshing for another project now clears them first. Fixes #4194.
2026-11-18 19:26:48 +08:00
l0ng-ai 6135a5326d fix(local-history): reverting to a label leaves files deleted before it absent (#4274)
A file whose last revision before a label is its Deleted snapshot was absent at the label, but Revert restored it and counted it. Folder reverts now skip such files; a file's own revert says it did not exist then. Part of #4199.
2026-11-18 19:22:37 +08:00
l0ng-ai 403bb28ca4 fix(local-history): keep snapshots as document text (no BOM, LF) (#4272)
Saves record the document's text but the watcher snapshotted the file with its BOM and CRLF, adding an External change revision per save; reverting that revision doubled the BOM. Disk snapshots and snapshot content are now normalized to document text. Fixes #4195.
2026-11-18 19:21:04 +08:00
l0ng-ai 3249d4ee90 fix(lsp): count a Rust error once when rust-analyzer and rustc both report it (#4270)
rust-analyzer publishes its own analysis next to cargo check's, so one type mismatch arrived as rust-analyzer(E0308) and rustc(E0308) and counted twice. Its own entry is dropped when rustc reports the same code and severity over an overlapping range. Fixes #4193.
2026-11-18 19:18:46 +08:00
l0ng-ai 79e41c85ff fix(build): resolve Build Module's Cargo diagnostics from the workspace root (#4269)
rustc names workspace members' files from the workspace root; Build Module runs cargo in the member, so its diagnostics doubled the member folder. Resolution now tries the manifest directory, then its ancestors, taking the first existing file. Fixes #4189.
2026-11-18 19:17:01 +08:00
l0ng-ai f0a7cca1b1 fix(project-view): say which view option hides a file Select Opened File can't reach (#4268)
With Show Excluded Files or Show Hidden Files off, Select Opened File silently selected the nearest shown ancestor. It now notifies which option hides the file, with an action that turns it on and selects the file. Fixes #4181.
2026-11-18 19:15:14 +08:00
l0ng-ai 21f1e2bbb4 fix(editor): don't carry untitled tabs to the Welcome screen (#4264)
Untitled tabs were carried when Close Project returned to Welcome, after the leave guard had asked about them, so a draft discarded with Don't Save reopened as an empty focused tab. Closing to Welcome now drops them; in-place switches still carry them. Fixes #4173.
2026-11-18 19:11:22 +08:00
l0ng-ai ffdb5d74f2 fix(navigation): Navigate to Test uses the top-level class at the caret (#4263)
Navigate to Test derived test names from the file name, so with the caret in a second top-level class it offered the file's test instead. For Java, Kotlin, Scala, Groovy and C# it now takes the outermost type around the caret from the document outline, falling back to the file name. Fixes #4171.
2026-11-18 19:08:21 +08:00
l0ng-ai d4d9e7d191 fix(editor): tab limit keeps VCS-changed tabs with Close non-modified files first (#4261)
The tab limit's closing policy only counted unsaved changes as modified, so a saved file with a Git change closed before clean tabs. It now shares Close Unmodified Tabs' check: unsaved changes or a VCS status. Fixes #4166.
2026-11-18 19:05:43 +08:00
l0ng-ai 6a41509fd2 fix(project-trust): list restricted projects in Project Trust settings (#4257)
A project with a restricted decision stays restricted inside a trusted location, but the settings page didn't list those decisions. The page now lists restricted projects with a Trust button, and the location hint says restricted projects are excluded. Fixes #4156.
2026-11-18 19:03:39 +08:00
l0ng-ai 6efece99a4 fix(project): ask about trust before leaving the current project (#4253)
Opening a folder in this window confirmed leaving the current project (which stops its running processes) before the trust prompt, so Don't Open left the original project without its processes. Trust is now asked first; the fallback open path follows the same order. Fixes #4160.
2026-11-18 19:00:24 +08:00
l0ng-ai 0fab45689f fix(vcs): expire the conflict notice once the merge or rebase is over (#4251)
"All conflicts resolved" kept its Commit… and Abort Merge actions after the
merge was committed, and Abort Merge then reported no merge in progress. The
conflict notices (key vcs.conflicts) now expire when the repository leaves
the merge, rebase, cherry-pick, revert or am they refer to, however it ended.

Fixes #4154
2026-11-18 18:53:43 +08:00
l0ng-ai 71090202b6 fix(debugger): Breakpoints dialog selects on click and keeps typed conditions (#4249)
A single click on a breakpoint jumped to its source and closed the dialog,
and a condition typed and confirmed with Enter (Done) was lost, as only
leaving the field saved it. A click now selects the breakpoint (double-click
or Enter goes to the source), and the shown breakpoint's typed fields are
saved when the dialog closes or another breakpoint is shown, for method and
field breakpoints too; unchanged fields are not written again.

Fixes #4150
2026-11-18 18:52:04 +08:00
l0ng-ai 8ed08510ed fix: Delete in a popup's search field edits the text before it removes the selection (#4248)
Open Recent removed the selected project on Delete wherever the caret was in
the search field, and the run configuration chooser deleted the selected
configuration without asking. Delete now acts on the selection only when it
has no text to delete (the caret at the end of the query, nothing selected;
⌘⌫ only with an empty query), and the chooser asks before deleting a
configuration, from Delete or its menu, as IDEA's popup does.

Fixes #4159
Fixes #4203
2026-11-18 18:48:03 +08:00
l0ng-ai 500df4ffc4 fix(vcs): Show Diff of a staged or unstaged row shows that side of the index (#4247)
The changes tree's Show Diff passed only the file's path to the action, which
opened HEAD against the working copy, so a partially staged file showed its
unstaged edit from the Staged group too. The menu item now opens the row's own
diff, as double-click does: HEAD ↔ Index under Staged, Index ↔ working copy under
Unstaged. Show Diff from the keyboard builds the tree the Commit window shows
(staging groups, no change lists, with the staging area) so the selected row is
found, and uses it with the non-modal interface too.

Fixes #4152
2026-11-18 18:45:05 +08:00
84 змінених файлів з 1607 додано та 129 видалено

No files matched your search

+19 -1
Переглянути файл
@@ -536,7 +536,9 @@ impl PathMap {
let abs = if p.is_absolute() {
p.to_path_buf()
} else {
let in_base = base.map(|b| Path::new(b).join(p)).filter(|c| c.exists());
// rustc prints workspace members' files relative to the workspace root, above
// the member's manifest directory (`base`) when a member is built on its own.
let in_base = base.and_then(|b| Path::new(b).ancestors().map(|a| a.join(p)).find(|c| c.exists()));
in_base.unwrap_or_else(|| cwd.join(p))
};
let abs = normalize(&abs);
@@ -1303,6 +1305,22 @@ mod tests {
assert_eq!(identifier_len("x é_1 c", 2), 3);
}
#[test]
fn resolves_a_member_build_s_workspace_relative_paths() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().to_path_buf();
write(&root, "client/src/main.rs", "fn main() {}\n");
write(&root, "client/src/lib.rs", "\n");
write(&root, "src/lib.rs", "\n");
let map = PathMap { root: root.clone(), canonical: None };
let member = root.join("client");
let base = member.to_str();
// Build Module runs in the member; rustc names its files from the workspace root.
assert_eq!(map.resolve("client/src/main.rs", &member, base), root.join("client/src/main.rs"));
// A crate built from its own directory names them from there.
assert_eq!(map.resolve("src/lib.rs", &member, base), member.join("src/lib.rs"));
}
// Uses Unix absolute paths for the canonical root.
#[cfg(unix)]
#[test]
+8
Переглянути файл
@@ -1875,6 +1875,14 @@ pub fn goto_declaration(text: &str, path: &Path, pos: Pos, local_repo: Option<Pa
goto_declaration_in(text, path, pos, local_repo, Vec::new)
}
/// The declaration of the property `name` in the pom at `path`, for files it configures
/// outside the pom itself (a YAML resource's `@name@`): the first `<properties>` entry
/// along the parent chain declaring it, `project.*` built-ins included.
pub fn property_declaration(pom: &Path, name: &str, local_repo: Option<PathBuf>) -> Option<PomGoto> {
let text = xml::read_text(pom)?;
property_target(&text, pom, name, local_repo)
}
/// [`goto_declaration`], where a `<parent>` and a dependency or plugin whose version no
/// management entry provides (or a management entry itself) go to the artifact's own
/// POM: the project module among `modules` with its coordinates, else the local
+117 -11
Переглянути файл
@@ -19,10 +19,16 @@ struct State {
settings: Vec<(String, String)>,
read_only: bool,
session_id: String,
session: Mutex<bool>,
session: Mutex<Session>,
closed: CancellationToken,
}
#[derive(Default)]
struct Session {
initialized: bool,
strict_read_only: bool,
}
/// The response format: a names line, a types line, then one JSON array per row, so rows past
/// the grid's limit are skipped without being parsed.
const FORMAT: &str = "JSONCompactEachRowWithNamesAndTypes";
@@ -109,12 +115,23 @@ impl ClickhousePool {
settings: setup.params,
read_only: source.read_only,
session_id: uuid::Uuid::new_v4().to_string(),
session: Mutex::new(false),
session: Mutex::new(Session::default()),
closed: CancellationToken::new(),
}));
let cancel = CancellationToken::new();
let initialize = async {
pool.execute("SELECT 1", 1, &cancel).await?;
if let Err(error) = pool.execute("SELECT 1", 1, &cancel).await {
if !rejects_driver_setting(&error) {
return Err(error);
}
// Retry only the connection probe. Keep relying on the server for write protection
// only after verifying strict read-only mode in this same session.
pool.0.session.lock().await.strict_read_only = true;
let result = pool.execute("SELECT getSetting('readonly')", 1, &cancel).await?;
if result.rows.first().and_then(|row| row.first()).and_then(Option::as_deref) != Some("1") {
return Err(error);
}
}
for sql in setup.statements {
pool.execute(&sql, 0, &cancel).await?;
}
@@ -151,7 +168,7 @@ impl ClickhousePool {
}
/// `max_rows`: the rows the server may send (the skipped ones included).
fn request(&self, client: &Client, query_id: &str, max_rows: usize, initialized: bool) -> RequestBuilder {
fn request(&self, client: &Client, query_id: &str, max_rows: usize, session: &Session) -> RequestBuilder {
let mut request = client
.post(self.0.endpoint.clone())
.basic_auth(&self.0.user, Some(&self.0.password))
@@ -162,16 +179,20 @@ impl ClickhousePool {
("session_timeout", "3600".into()),
("query_id", query_id.to_owned()),
("default_format", FORMAT.into()),
]);
if !session.strict_read_only {
request = request.query(&[
("output_format_json_quote_denormals", "1".into()),
("max_result_rows", max_rows.saturating_add(1).to_string()),
("result_overflow_mode", "break".into()),
]);
if initialized {
}
if session.initialized {
request = request.query(&[("session_check", "1")]);
} else {
request = request.query(&[("database", &self.0.database)]);
}
if self.0.read_only {
if self.0.read_only && !session.strict_read_only {
request = request.query(&[("readonly", "1")]);
}
request
@@ -200,7 +221,7 @@ impl ClickhousePool {
};
let client = self.client()?;
let query_id = uuid::Uuid::new_v4().to_string();
let request = self.request(&client, &query_id, skip.saturating_add(max_rows), *session).body(sql.to_owned());
let request = self.request(&client, &query_id, skip.saturating_add(max_rows), &session).body(sql.to_owned());
let started = Instant::now();
let fetch = async {
let mut response = request.send().await.map_err(http_error)?;
@@ -254,7 +275,7 @@ impl ClickhousePool {
match result {
Some(result) => {
if result.is_ok() {
*session = true;
session.initialized = true;
}
result
}
@@ -323,9 +344,9 @@ type DecodedResult = (Vec<ResultColumn>, Vec<Vec<Option<String>>>, bool);
/// Decodes a streamed [`FORMAT`] body. Reads past the first `skip` rows unparsed (a later
/// page), then keeps `max_rows` rows; later rows only set `has_more` and are read past
/// unparsed, so a grid limit bounds memory however large the block
/// `result_overflow_mode=break` lets the server send. A line that is not a JSON array
/// starts the exception ClickHouse writes when a query fails mid-stream.
/// unparsed, so a grid limit bounds memory even if a strict read-only server does not allow
/// per-query result limits. A line that is not a JSON array starts the exception ClickHouse
/// writes when a query fails mid-stream.
struct RowReader {
skip: usize,
max_rows: usize,
@@ -479,6 +500,20 @@ fn read_pem(path: &str, label: &str) -> IdeResult<Vec<u8>> {
.map_err(|error| IdeError::new(ErrorKind::Io, format!("cannot read ClickHouse {label}: {error}")))
}
fn rejects_driver_setting(error: &IdeError) -> bool {
error
.message
.split_once(": ")
.and_then(|(_, detail)| detail.strip_prefix("Code: 164. DB::Exception: Cannot modify '"))
.and_then(|detail| detail.split_once("' setting in readonly mode"))
.is_some_and(|(name, _)| {
matches!(
name,
"output_format_json_quote_denormals" | "max_result_rows" | "result_overflow_mode" | "readonly"
)
})
}
fn reserved_setting(name: &str) -> bool {
let name = name.to_ascii_lowercase();
name.starts_with("output_format_json_")
@@ -726,6 +761,77 @@ mod tests {
task.await.unwrap();
}
#[tokio::test]
async fn connects_when_server_forbids_settings_in_readonly_mode() {
let (port, requests) = server(vec![
(
"500 Internal Server Error",
"X-ClickHouse-Exception-Code: 164\r\n",
"Code: 164. DB::Exception: Cannot modify 'output_format_json_quote_denormals' setting in readonly mode. (READONLY)",
),
("200 OK", "", ONE),
("200 OK", "", "[\"n\"]\n[\"UInt64\"]\n[1]\n[2]\n"),
])
.await;
let source = DataSource {
read_only: true,
properties: vec![DbProperty { name: "max_threads".into(), value: "2".into() }],
..source(port)
};
let pool = Pool::connect(&source, None, None).await.unwrap();
let result = pool.execute("SELECT number FROM numbers(2)", 1, &CancellationToken::new()).await.unwrap();
assert_eq!(result.rows, vec![vec![Some("1".into())]]);
assert!(result.has_more);
let requests = requests.await.unwrap();
assert!(requests[0].ends_with("SELECT 1"));
assert!(requests[0].contains("output_format_json_quote_denormals=1"));
assert!(requests[1].ends_with("SELECT getSetting('readonly')"));
assert!(requests[2].contains("session_check=1"));
for request in &requests[1..] {
assert!(request.contains("default_format=JSONCompactEachRowWithNamesAndTypes"));
assert!(request.contains("max_threads=2"));
for setting in
["output_format_json_quote_denormals=", "max_result_rows=", "result_overflow_mode=", "readonly="]
{
assert!(!request.contains(setting), "{setting} is not allowed in a strict read-only session");
}
}
}
#[tokio::test]
async fn readonly_probe_does_not_disable_settings_on_a_writable_session() {
let (port, requests) = server(vec![
(
"500 Internal Server Error",
"X-ClickHouse-Exception-Code: 164\r\n",
"Code: 164. DB::Exception: Cannot modify 'max_result_rows' setting in readonly mode. (READONLY)",
),
("200 OK", "", "[\"readonly\"]\n[\"UInt64\"]\n[0]\n"),
])
.await;
let source = DataSource { read_only: true, ..source(port) };
let error = Pool::connect(&source, None, None).await.err().expect("writable session must stay rejected");
assert!(error.message.contains("Cannot modify 'max_result_rows'"));
assert!(requests.await.unwrap()[1].ends_with("SELECT getSetting('readonly')"));
}
#[test]
fn readonly_probe_matches_only_the_driver_settings() {
for (code, setting, expected) in [
(164, "max_result_rows", true),
(164, "result_overflow_mode", true),
(164, "readonly", true),
(164, "max_threads", false),
(516, "max_result_rows", false),
] {
let error = IdeError::invalid(format!(
"ClickHouse HTTP 500: Code: {code}. DB::Exception: Cannot modify '{setting}' setting in readonly mode. (READONLY)"
));
assert_eq!(rejects_driver_setting(&error), expected, "{setting}");
}
}
#[tokio::test]
async fn server_errors_keep_details_and_hide_passwords() {
let (port, requests) = server(vec![(
+15 -3
Переглянути файл
@@ -359,10 +359,22 @@ pub async fn lsp_goto(host: &Host, window: &str, doc: DocId, pos: Pos, kind: Got
if kind != GotoKind::Definition {
return result;
}
let Some((plugins, d)) = plugin_providers(host, window, doc, ProviderKind::Definition) else { return result };
// A Maven placeholder (`@profileActive@` in `application.yml` or `.properties`) navigates to its pom.
let maven = super::maven_placeholder::definition(host, window, doc, pos).await;
let Some((plugins, d)) = plugin_providers(host, window, doc, ProviderKind::Definition) else {
return match maven {
None => result,
Some(found) => {
let in_string = in_string_literal(host, window, doc, pos).await;
definition_targets(result, vec![found], in_string)
}
};
};
let found = plugin_call(move || plugins.provide_definition(&d, pos)).await.unwrap_or_default();
let found: Vec<Location> =
found.into_iter().map(|l| Location { path: l.path.into(), range: l.range, uri: None }).collect();
let found: Vec<Location> = maven
.into_iter()
.chain(found.into_iter().map(|l| Location { path: l.path.into(), range: l.range, uri: None }))
.collect();
let in_string = !found.is_empty() && in_string_literal(host, window, doc, pos).await;
definition_targets(result, found, in_string)
}
+154
Переглянути файл
@@ -0,0 +1,154 @@
//! ⌘B on a Maven resource-filtering placeholder: `@property@` in a YAML or properties
//! resource (Spring's `application.yml` / `application.properties`) jumps to the `<properties>` entry that defines it,
//! in the nearest `pom.xml` above the file, up through the project root. Parent
//! poms the nearest pom declares itself are followed from there; a parent outside
//! that walk that no pom declares is not.
use super::doc::blocking;
use crate::Host;
use ide_build::maven;
use ide_core::{DocId, Location, Pos};
use std::path::Path;
/// The definition location of the placeholder under `pos` in `doc`, when `doc` is a
/// YAML or properties file holding a `@token@` there and a pom above it defines that property.
pub(crate) async fn definition(host: &Host, window: &str, doc: DocId, pos: Pos) -> Option<Location> {
let project = host.project(window).ok()?;
blocking(move || {
let snap = project.documents.text_snapshot(doc)?;
if snap.large || !matches!(snap.language.as_str(), "yaml" | "properties") {
return Ok(None);
}
let path = project.documents.identity(doc)?.0;
let Some((name, _token_at)) = placeholder_at(&snap.text, pos) else { return Ok(None) };
Ok(pom_defining(&project.root, &path, &name))
})
.await
.ok()
.flatten()
}
/// The `@token@` enclosing `pos` on its line, with the token's range (UTF-16 columns).
fn placeholder_at(text: &str, pos: Pos) -> Option<(String, ide_core::Range)> {
let line = text.split_inclusive('\n').nth(pos.line as usize)?;
let line = line.trim_end_matches(['\n', '\r']);
let cursor = utf16_to_byte(line, pos.col)?;
let mut opener: Option<usize> = None;
for (i, b) in line.as_bytes().iter().enumerate() {
if *b != b'@' {
continue;
}
if let Some(start) = opener.replace(i) {
let token = &line[start + 1..i];
let valid =
!token.is_empty() && token.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '_'));
if valid && start <= cursor && cursor <= i {
let col = |byte: usize| line[..byte].encode_utf16().count() as u32;
return Some((
token.to_owned(),
ide_core::Range::new(Pos::new(pos.line, col(start)), Pos::new(pos.line, col(i + 1))),
));
}
opener = None;
}
}
None
}
/// The nearest `pom.xml` above `from` (up to and including `root`) defining `name`.
fn pom_defining(root: &Path, from: &Path, name: &str) -> Option<Location> {
let mut dir = from.parent()?.to_path_buf();
loop {
let pom = dir.join("pom.xml");
if pom.is_file()
&& let Some(found) = maven::property_declaration(&pom, name, maven::default_local_repo())
{
return Some(Location::file(found.path.into(), found.range));
}
if dir == root || !dir.starts_with(root) {
return None;
}
dir = dir.parent()?.to_path_buf();
}
}
/// UTF-16 column → byte offset within one line.
fn utf16_to_byte(line: &str, col: u32) -> Option<usize> {
let col = col as usize;
let mut units = 0usize;
for (byte, c) in line.char_indices() {
if units == col {
return Some(byte);
}
units += c.len_utf16();
if units > col {
return None;
}
}
(units == col).then_some(line.len())
}
#[cfg(test)]
mod tests {
use super::*;
use ide_core::Pos;
fn at(line: u32, col: u32) -> Pos {
Pos::new(line, col)
}
#[test]
fn finds_the_placeholder_under_the_cursor_and_its_range() {
let text = "spring:\n profiles:\n active: @profileActive@\n";
let (name, range) = placeholder_at(text, at(2, 20)).unwrap();
assert_eq!(name, "profileActive");
assert_eq!(range.start, at(2, 12));
assert_eq!(range.end, at(2, 27));
// The `@`s themselves and inside the token navigate; just past the token does not.
for col in [12u32, 13, 26] {
assert_eq!(placeholder_at(text, at(2, col)).unwrap().0, "profileActive");
}
// A second pair on the line and unrelated cursors stay unresolved.
let multi = "a: @one@ @two@\n";
assert_eq!(placeholder_at(multi, at(0, 4)).unwrap().0, "one");
assert_eq!(placeholder_at(multi, at(0, 10)).unwrap().0, "two");
assert!(placeholder_at(multi, at(0, 8)).is_none(), "between the pairs");
assert!(placeholder_at(multi, at(0, 9)).is_some(), "the opening @ of the next pair");
assert!(placeholder_at(multi, at(0, 14)).is_none(), "just past the last pair");
assert!(placeholder_at("value: plain\n", at(0, 7)).is_none());
}
#[test]
fn the_nearest_pom_wins_and_the_walk_stops_at_the_project_root() {
let tmp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(tmp.path()).unwrap();
let root = base.join("project");
let deep = root.join("core/src/main/resources");
std::fs::create_dir_all(&deep).unwrap();
std::fs::write(
root.join("pom.xml"),
"<project>\n <properties>\n <parentName>parent</parentName>\n </properties>\n</project>\n",
)
.unwrap();
std::fs::create_dir_all(root.join("core")).unwrap();
std::fs::write(
root.join("core/pom.xml"),
"<project>\n <properties>\n <name>module</name>\n </properties>\n</project>\n",
)
.unwrap();
let from = deep.join("application.yml");
// The module pom defines `name` first: its file wins, pointing at its `<name>` entry.
let found = pom_defining(&root, &from, "name").unwrap();
assert_eq!(found.path, root.join("core/pom.xml"));
assert_eq!(found.range.start.line, 2);
// A property only the parent defines resolves there; unknown ones resolve nowhere.
let parent = pom_defining(&root, &from, "parentName").unwrap();
assert_eq!(parent.path, root.join("pom.xml"));
assert_eq!(parent.range.start.line, 2);
assert!(pom_defining(&root, &from, "missing").is_none());
// A file outside the project root has no pom walk.
let outside = tmp.path().join("elsewhere/application.yml");
std::fs::create_dir_all(tmp.path().join("elsewhere")).unwrap();
assert!(pom_defining(&root, &outside, "name").is_none());
}
}
+1
Переглянути файл
@@ -21,6 +21,7 @@ pub mod history;
pub mod java;
pub mod jvm_icons;
pub mod lsp;
pub mod maven_placeholder;
pub mod nav;
pub mod notebook;
pub mod project;
+6 -3
Переглянути файл
@@ -15,6 +15,9 @@ impl ReplaceHost for DocumentsHost<'_> {
Some(doc) => (doc, false),
None => (docs.open(path)?.id, true),
};
// A buffer without unsaved changes (open only for the search preview, or a clean
// tab) is saved like a closed file; one the user is editing is left unsaved.
let save = transient || !docs.is_dirty(doc)?;
let result = (|| {
// Recompute if the user typed between reading the text and applying.
for _ in 0..3 {
@@ -27,7 +30,7 @@ impl ReplaceHost for DocumentsHost<'_> {
continue;
}
docs.apply_edits(doc, &edits)?;
if transient {
if save {
docs.save(doc)?;
}
return Ok(edits.len() as u32);
@@ -46,8 +49,8 @@ impl ReplaceHost for DocumentsHost<'_> {
///
/// Edits go through the document layer as one patch per file, so open editors
/// update live and undo the whole file's replacements in one step. Unsaved
/// editor buffers are replaced in place and left unsaved; files that were not
/// open are opened transiently, saved and closed.
/// editor buffers are replaced in place and left unsaved; other open documents
/// are saved, and files that were not open are opened transiently, saved and closed.
///
/// With `all_in_scope` (Replace All after the search hit its match limit) the
/// scope is searched again without the limit and every match in it is replaced,
+49
Переглянути файл
@@ -146,3 +146,52 @@ async fn replace_all_covers_matches_past_the_limit() {
host.close_project("main");
}
}
/// #4202: a file the search preview holds open (no unsaved changes) is saved like a closed
/// one; a buffer with unsaved edits is replaced in place and left for the editor to save.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn replace_all_saves_open_buffers_without_unsaved_changes() {
let temp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(temp.path()).unwrap();
let root = base.join("project");
std::fs::create_dir_all(&root).unwrap();
for name in ["previewed.txt", "edited.txt", "closed.txt"] {
std::fs::write(root.join(name), "TOKEN\n").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(&root, true, false).unwrap();
host.open_project("main", &root).unwrap();
let project = host.project("main").unwrap();
project.documents.open(&root.join("previewed.txt")).unwrap();
let edited = project.documents.open(&root.join("edited.txt")).unwrap().id;
project.documents.replace_all(edited, "TOKEN\nmore\n").unwrap();
ops::search::replace_in_files(
&host,
"main",
RequestId::next(),
query("TOKEN", false),
"DONE".into(),
false,
vec![],
true,
ops::Channel::new(|_| {}),
)
.await
.unwrap();
let disk = |name: &str| std::fs::read_to_string(root.join(name)).unwrap();
assert_eq!(disk("previewed.txt"), "DONE\n");
assert_eq!(disk("closed.txt"), "DONE\n");
assert_eq!(disk("edited.txt"), "TOKEN\n", "unsaved edits stay unsaved");
assert_eq!(project.documents.text_snapshot(edited).unwrap().text, "DONE\nmore\n");
host.close_project("main");
}
+53
Переглянути файл
@@ -65,6 +65,28 @@ pub(crate) fn lenient_diagnostics(server: &str, items: Value) -> Vec<lsp::Diagno
parsed
}
/// rust-analyzer publishes its own analysis next to `cargo check`'s (flycheck): one type
/// mismatch then arrives as `rust-analyzer(E0308)` and `rustc(E0308)`. Its own entry is
/// dropped when the compiler reports the same code and severity over an overlapping range.
fn drop_compiler_duplicates(diagnostics: &mut Vec<lsp::Diagnostic>) {
let overlaps = |a: &lsp::Range, b: &lsp::Range| a.start <= b.end && b.start <= a.end;
let compiler: Vec<(lsp::Range, Option<lsp::NumberOrString>, Option<lsp::DiagnosticSeverity>)> = diagnostics
.iter()
.filter(|d| d.source.as_deref() == Some("rustc") && d.code.is_some())
.map(|d| (d.range, d.code.clone(), d.severity))
.collect();
if compiler.is_empty() {
return;
}
diagnostics.retain(|d| {
d.source.as_deref() != Some("rust-analyzer")
|| d.code.is_none()
|| !compiler
.iter()
.any(|(range, code, severity)| code == &d.code && severity == &d.severity && overlaps(range, &d.range))
});
}
impl ClientHandler {
pub fn new(mgr: Weak<LspManager>, server: Arc<Server>, generation: u64) -> Self {
Self { mgr, server, generation }
@@ -293,11 +315,20 @@ impl ClientHandler {
}
};
params.diagnostics = lenient_diagnostics(&self.server.name, raw.unwrap_or(Value::Null));
drop_compiler_duplicates(&mut params.diagnostics);
let Some(path) = uri_to_path(params.uri.as_str())
.or_else(|| crate::notebook::is_cell_uri(params.uri.as_str()).then(|| PathBuf::from(params.uri.as_str())))
else {
return;
};
if self.server.name == crate::compose::SERVER {
// Maven resource-filtering placeholders (`@profileActive@`) parse as invalid
// YAML but are replaced before the file is ever read: their parser error is noise.
let text = mgr.docs.lock().values().find(|d| d.path == path).map(|d| d.text.as_str().to_owned());
if let Some(text) = text {
params.diagnostics.retain(|d| !crate::maven_placeholder::false_positive(&text, d));
}
}
if self.server.name == "jdtls"
&& let Some(failure) = crate::jdtls::build_plan_failure(&path, &self.server.root, &params.diagnostics)
{
@@ -701,6 +732,28 @@ mod tests {
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
#[test]
fn rust_analyzer_s_own_entry_yields_to_the_compiler_s_for_the_same_error() {
let diagnostic = |source: &str, code: &str, line: u32, severity| lsp::Diagnostic {
range: lsp::Range::new(lsp::Position::new(line, 21), lsp::Position::new(line, 27)),
severity: Some(severity),
code: Some(lsp::NumberOrString::String(code.into())),
source: Some(source.into()),
message: format!("{source} {code}"),
..Default::default()
};
let error = lsp::DiagnosticSeverity::ERROR;
let mut items = vec![
diagnostic("rust-analyzer", "E0308", 1, error),
diagnostic("rustc", "E0308", 1, error),
diagnostic("rust-analyzer", "E0308", 5, error),
diagnostic("rust-analyzer", "unused_variables", 1, lsp::DiagnosticSeverity::WARNING),
];
drop_compiler_duplicates(&mut items);
let left: Vec<_> = items.iter().map(|d| (d.message.as_str(), d.range.start.line)).collect();
assert_eq!(left, [("rustc E0308", 1), ("rust-analyzer E0308", 5), ("rust-analyzer unused_variables", 1)]);
}
#[test]
fn tsserver_aborts_are_out_of_memory() {
assert!(tsserver_ran_out_of_memory("TSServer exited. Code: 134. Signal: null"));
+1
Переглянути файл
@@ -25,6 +25,7 @@ mod kotlin_lsp;
mod launch;
mod library_source;
mod loading;
mod maven_placeholder;
mod message_requests;
mod notebook;
mod phoxite;
+113
Переглянути файл
@@ -0,0 +1,113 @@
//! `@property@` placeholders in YAML resources: Maven resource filtering replaces
//! them before the file is ever read as YAML, so Spring projects use them unquoted
//! (`spring.profiles.active: @profileActive@`). The YAML spec reserves `@` and the
//! `yaml` parser behind `yaml-language-server` therefore reports
//! "Plain value cannot start with reserved character @" for every one of them.
//! The diagnostic is dropped when the reported scalar is exactly a Maven
//! placeholder; anything else the parser flags keeps showing.
use lsp_types as lsp;
const RESERVED_AT: &str = "Plain value cannot start with reserved character @";
/// Whether `diagnostic` is the reserved-`@` parser error on a scalar whose text in
/// `text` is exactly a Maven placeholder (`@token@`).
pub(crate) fn false_positive(text: &str, diagnostic: &lsp::Diagnostic) -> bool {
diagnostic.message == RESERVED_AT && placeholder_at(text, &diagnostic.range).is_some()
}
/// The name between the `@`s of the diagnostic range, when it covers one whole placeholder.
fn placeholder_at(text: &str, range: &lsp::Range) -> Option<String> {
if range.start.line != range.end.line {
return None;
}
let line = text.split_inclusive('\n').nth(range.start.line as usize)?;
let line = line.trim_end_matches(['\n', '\r']);
let start = utf16_to_byte(line, range.start.character)?.min(line.len());
// The parser's scalar range ends one past the line (its newline), so the end clamps.
let end = utf16_to_byte(line, range.end.character).unwrap_or(line.len());
if end < start {
return None;
}
let inner = line[start..end].strip_prefix('@')?.strip_suffix('@')?;
(!inner.is_empty() && inner.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '_')))
.then(|| inner.to_owned())
}
/// UTF-16 column → byte offset within one line, `None` inside a surrogate pair or past the line.
fn utf16_to_byte(line: &str, col: u32) -> Option<usize> {
let col = col as usize;
let mut units = 0usize;
for (byte, c) in line.char_indices() {
if units == col {
return Some(byte);
}
units += c.len_utf16();
if units > col {
return None;
}
}
(units == col).then_some(line.len())
}
#[cfg(test)]
mod tests {
use super::*;
use lsp_types::{Position, Range};
fn at(line: u32, from: u32, to: u32) -> Range {
Range { start: Position::new(line, from), end: Position::new(line, to) }
}
fn across(from: (u32, u32), to: (u32, u32)) -> Range {
Range { start: Position::new(from.0, from.1), end: Position::new(to.0, to.1) }
}
fn diagnostic(range: Range) -> lsp::Diagnostic {
lsp::Diagnostic { range, message: RESERVED_AT.to_owned(), ..Default::default() }
}
#[test]
fn a_maven_placeholder_placeholder_is_a_false_positive() {
let text = "spring:\n profiles:\n active: @profileActive@\n";
assert!(false_positive(text, &diagnostic(at(2, 12, 27))));
// The parser ends the scalar's range one past the line (its newline): still caught.
assert!(false_positive(text, &diagnostic(at(2, 12, 28))));
// Columns also decode on a line with non-ASCII text before the scalar.
let text = "name: 项目\nvalue: @profileActive@\n";
assert!(false_positive(text, &diagnostic(at(1, 7, 22))));
}
#[test]
fn other_reserved_character_errors_and_shapes_still_show() {
let text = "active: @profileActive@\n";
// Not the parser's message (a backtick, a different wording).
assert!(!false_positive(
text,
&lsp::Diagnostic {
message: "Plain value cannot start with reserved character `".to_owned(),
..diagnostic(at(0, 8, 11))
}
));
// The error's range is stale and no longer covers a placeholder.
assert!(!false_positive(text, &diagnostic(at(0, 0, 10))));
// A single `@`, an unpaired one or a name with spaces is no placeholder.
assert!(!false_positive("active: @\n", &diagnostic(at(0, 8, 9))));
assert!(!false_positive("active: @profile\n", &diagnostic(at(0, 8, 16))));
assert!(!false_positive("active: @pro file@\n", &diagnostic(at(0, 8, 18))));
// A range crossing lines is kept.
assert!(!false_positive("a: @x@\nb: y\n", &diagnostic(across((0, 3), (1, 0)))));
}
#[test]
fn utf16_columns_decode_multi_byte_and_surrogate_pairs() {
// "é" is one UTF-16 unit; "😀" is two, and a column inside it is out of range.
let line = "é😀@token@";
assert_eq!(utf16_to_byte(line, 0), Some(0));
assert_eq!(utf16_to_byte(line, 1), Some(2));
assert_eq!(utf16_to_byte(line, 2), None);
assert_eq!(utf16_to_byte(line, 3), Some(6));
assert_eq!(utf16_to_byte(line, 4), Some(7));
assert_eq!(utf16_to_byte(line, 10), Some(line.len()));
}
}
+31 -2
Переглянути файл
@@ -121,7 +121,14 @@ fn read_snapshot_text(path: &Path) -> Option<String> {
if bytes.iter().take(8192).any(|b| *b == 0) {
return None;
}
String::from_utf8(bytes).ok()
String::from_utf8(bytes).ok().map(|text| document_text(&text).into_owned())
}
/// `text` as a document holds it: without the UTF-8 BOM and with `\n` line endings. Saves
/// record the document's text, so a file read from disk must match it to dedupe, and
/// Revert writes it back through the document, which adds the file's BOM and line endings.
fn document_text(text: &str) -> std::borrow::Cow<'_, str> {
ide_text::normalize_line_endings(text.strip_prefix('\u{feff}').unwrap_or(text))
}
impl LocalHistory {
@@ -338,7 +345,10 @@ impl LocalHistory {
return Err(IdeError::invalid(format!("invalid history id {id:?}")));
}
match fs::read(self.blob_path(id)) {
Ok(bytes) => Ok(String::from_utf8(bytes).unwrap_or_else(|e| String::from_utf8_lossy(e.as_bytes()).into())),
Ok(bytes) => {
let text = String::from_utf8(bytes).unwrap_or_else(|e| String::from_utf8_lossy(e.as_bytes()).into());
Ok(document_text(&text).into_owned())
}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
Err(IdeError::not_found(format!("history snapshot {id} not found")))
}
@@ -532,6 +542,25 @@ mod tests {
}
}
#[test]
fn a_file_read_from_disk_matches_the_saved_document_text() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().join("project");
fs::create_dir_all(&root).unwrap();
let h = LocalHistory::open(&tmp.path().join("history"), &root).unwrap();
let a = root.join("a.txt");
// A save records the document's text; the file on disk has a BOM and CRLF.
fs::write(&a, b"\xEF\xBB\xBFheader\r\nbody\r\n").unwrap();
h.record(&a, "header\nbody\n", "Saved").unwrap();
assert!(h.record_file(&a, "External change", false).unwrap());
let list = h.list(&a).unwrap();
assert_eq!(list.iter().map(|e| e.label.as_str()).collect::<Vec<_>>(), ["Saved"], "no second revision");
// A snapshot stored with its BOM before reads back as document text.
h.record(&a, "\u{feff}old\r\n", "External change").unwrap();
let old = &h.list(&a).unwrap()[0];
assert_eq!(h.content(&old.id).unwrap(), "old\n");
}
#[test]
fn events_labels_and_deletions() {
let tmp = tempfile::tempdir().unwrap();
+4 -2
Переглянути файл
@@ -45,14 +45,16 @@ If navigation, search or highlighting doesn't match the files, rebuild the cache
The Windows packages aren't code-signed yet, so Microsoft Defender SmartScreen may show an unknown-publisher warning. Choose **More info**, then **Run anyway**. See [Install](/en/guide/install#windows).
## The window stays blank on Linux
## The window stays blank or stops responding on Linux
WebKitGTK's DMA-BUF renderer fails on Wayland with the NVIDIA driver. OpenIDEA detects this combination and sets `WEBKIT_DISABLE_DMABUF_RENDERER=1` itself. If you see a blank or broken window in another setup, quit OpenIDEA and start it from a terminal with that variable set, for example:
WebKitGTK's DMA-BUF renderer fails on some Wayland setups. With the NVIDIA driver on Wayland, OpenIDEA turns the driver's explicit sync off for itself (`__NV_DISABLE_EXPLICIT_SYNC=1`), which avoids the failure and keeps the renderer. If the window stays blank, draws incorrectly, or stops reacting to the keyboard and mouse a few seconds after launch in another setup, quit OpenIDEA and start it from a terminal with the DMA-BUF renderer turned off, for example:
```sh
WEBKIT_DISABLE_DMABUF_RENDERER=1 ./OpenIDEA_<version>_amd64.AppImage
```
The page is then drawn without the GPU, so dragging large panels can be slower. To keep the setting for launches from the application menu with the deb or rpm package, copy `/usr/share/applications/OpenIDEA.desktop` to `~/.local/share/applications/` and change its `Exec=` line to `Exec=env WEBKIT_DISABLE_DMABUF_RENDERER=1 openidea`.
## OpenIDEA exits at startup with a data directory error
`OPENIDEA_LOCAL_DATA_DIR` is set to a relative path or to a folder that can't be written. Fix or remove the variable. See [Move the local data](/en/reference/data-directories#move-the-local-data).
+4 -2
Переглянути файл
@@ -45,14 +45,16 @@ Java 语言服务器(jdtls)会分析它导入的每个模块,所以大型
Windows 安装包目前还没有代码签名,Microsoft Defender SmartScreen 可能提示“未知发布者”。点击 **更多信息**,再点击 **仍要运行**。参见[安装](/zh/guide/install)。
## Linux 上窗口一片空白
## Linux 上窗口空白或无响应
在使用 NVIDIA 驱动的 Wayland 会话中,WebKitGTK 的 DMA-BUF 渲染器会出错。OpenIDEA 检测到这种组合时会自动设置 `WEBKIT_DISABLE_DMABUF_RENDERER=1`。如果在其他环境下也出现空白或显示异常的窗口,先退出 OpenIDEA,再在终端中带上这个变量启动,例如:
在部分 Wayland 环境中,WebKitGTK 的 DMA-BUF 渲染器会出错。在使用 NVIDIA 驱动的 Wayland 会话中,OpenIDEA 会为自身关闭驱动的显式同步(`__NV_DISABLE_EXPLICIT_SYNC=1`),这样既能避开问题,又能保留该渲染器。如果在其他环境下窗口一片空白、显示异常,或启动几秒后键盘和鼠标都没有反应,先退出 OpenIDEA,再在终端中关闭 DMA-BUF 渲染器启动,例如:
```sh
WEBKIT_DISABLE_DMABUF_RENDERER=1 ./OpenIDEA_<version>_amd64.AppImage
```
这样页面不再用 GPU 绘制,拖动较大的面板可能变慢。使用 deb 或 rpm 包时,如果希望从应用菜单启动也带上这个设置,把 `/usr/share/applications/OpenIDEA.desktop` 复制到 `~/.local/share/applications/`,并把其中的 `Exec=` 一行改成 `Exec=env WEBKIT_DISABLE_DMABUF_RENDERER=1 openidea`。
## 启动时提示数据目录错误并退出
`OPENIDEA_LOCAL_DATA_DIR` 被设成了相对路径或不可写的文件夹。修正或删除这个变量即可。参见[数据目录与日志](/zh/reference/data-directories)。
+2 -2
Переглянути файл
@@ -1295,8 +1295,8 @@ export const commands = {
*
* Edits go through the document layer as one patch per file, so open editors
* update live and undo the whole file's replacements in one step. Unsaved
* editor buffers are replaced in place and left unsaved; files that were not
* open are opened transiently, saved and closed.
* editor buffers are replaced in place and left unsaved; other open documents
* are saved, and files that were not open are opened transiently, saved and closed.
*
* With `all_in_scope` (Replace All after the search hit its match limit) the
* scope is searched again without the limit and every match in it is replaced,
+16 -1
Переглянути файл
@@ -1,5 +1,5 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { registerEditorKind, type EditorKindContribution } from "@/workbench/contributions";
import { registerEditorKind, setFileDecorations, type EditorKindContribution } from "@/workbench/contributions";
import { t } from "@/platform/i18n";
import { useProject } from "@/platform/project";
import { confirm } from "@/workbench/messages";
@@ -166,3 +166,18 @@ describe("editor kinds' isBusy on tab-limit eviction", () => {
}
});
});
describe("Close non-modified files first", () => {
it("keeps a tab with a VCS change, as Close Unmodified Tabs does", async () => {
controller = new EditorController(createMemoryBackend({ "/p/a.ts": "a", "/p/b.ts": "b", "/p/c.ts": "c" }));
controller.start();
useProject.setState({ settings: { editor: { tabs: { tabLimit: 2, closingPolicy: "unchanged" } } } as never });
setFileDecorations("vcs", new Map([["/p/a.ts", { color: "modified" }]]));
try {
for (const path of ["/p/a.ts", "/p/b.ts", "/p/c.ts"]) await controller.openFile(path);
expect(pane().tabs.map((tab) => tab.input.path)).toEqual(["/p/a.ts", "/p/c.ts"]);
} finally {
setFileDecorations("vcs", new Map());
}
});
});
+14 -9
Переглянути файл
@@ -272,6 +272,14 @@ export function tabTrailing(input: EditorInput, kinds: EditorKinds): ReactNode {
}
}
/** Unsaved changes or a VCS status: what Close Unmodified Tabs and the tab limit's policy keep. */
function tabModified(tab: Tab): boolean {
return (
(inputDirty(tab.input, useContributions.getState().editorKinds) ?? false) ||
!!(tab.input.path && (useDocMeta.getState()[tab.input.path]?.dirty || getFileDecoration(tab.input.path)?.color))
);
}
export class EditorController implements SlotHost {
manager: DocumentManager;
readonly slots = new Map<string, EditorSlot>();
@@ -387,10 +395,11 @@ export class EditorController implements SlotHost {
// Untitled buffers belong to the window, not a project: their tabs
// survive the switch (the backend carries them into the new
// registry) and their slots rebuild against the carried documents.
// Closing to Welcome drops them; the leave guard already asked about them.
const carriedUntitled: Tab[] = [];
let carriedActive: string | null = null;
const cs = useTabs.getState();
for (const pane of Object.values(cs.panes)) {
for (const pane of root || s.lightEdit ? Object.values(cs.panes) : []) {
for (const tab of pane.tabs) {
if (isUntitledUri(tab.input.path ?? "")) {
carriedUntitled.push(tab);
@@ -1440,8 +1449,7 @@ export class EditorController implements SlotHost {
paneId,
prefs.tabLimit,
prefs.closingPolicy,
(tab) =>
inputDirty(tab.input, kinds) ?? !!(tab.input.path && useDocMeta.getState()[tab.input.path]?.dirty),
tabModified,
keep ?? current.panes[paneId]?.active ?? undefined,
protect,
)
@@ -1725,13 +1733,10 @@ export class EditorController implements SlotHost {
protect: (tab) => tab.pinned,
});
}
/** Keeps tabs with unsaved changes or a VCS status (IDEA: tabs shown as modified). */
/** Keeps tabs with unsaved changes or a VCS status (tabs shown as modified). */
closeUnmodified(paneId: string): Promise<boolean> {
const modified = (tab: Tab) =>
(inputDirty(tab.input, useContributions.getState().editorKinds) ?? false) ||
!!(tab.input.path && (useDocMeta.getState()[tab.input.path]?.dirty || getFileDecoration(tab.input.path)?.color));
return this.removeGuarded((s) => (s.panes[paneId] ? closeUnmodified(s, paneId, modified) : s), {
protect: (tab) => tab.pinned || modified(tab),
return this.removeGuarded((s) => (s.panes[paneId] ? closeUnmodified(s, paneId, tabModified) : s), {
protect: (tab) => tab.pinned || tabModified(tab),
});
}
closeReadOnly(paneId: string): Promise<boolean> {
+14
Переглянути файл
@@ -15,6 +15,7 @@ const { serializeSession } = await import("./model/session");
const { useDocMeta } = await import("./model/document");
const { save } = await import("@/platform/dialog");
const editorKinds = await import("@/workbench/contributions");
const { useProject } = await import("@/platform/project");
let ctrl: InstanceType<typeof EditorController> | null = null;
let backend: MemoryBackend;
@@ -158,6 +159,19 @@ describe("untitled editor input", () => {
expect([...backend.files.keys()]).toEqual(["/p/main.rs"]);
});
it("follows the window into another project but not to the Welcome screen", async () => {
const project = (root: string) => ({ root, name: root, trusted: true, isGit: false, settings: {} }) as never;
try {
await ctrl!.openUntitled({ focus: false });
useProject.setState({ project: project("/a") });
expect(activeTab().input.kind).toBe("untitled");
useProject.setState({ project: null });
expect(Object.values(useTabs.getState().panes).flatMap((p) => p.tabs)).toEqual([]);
} finally {
useProject.setState({ project: null });
}
});
it("reuses the buffer for a re-opened untitled name and shares it across tabs", async () => {
const info = await backend.openUntitled(null);
const twice = await backend.openUntitled("untitled:Untitled-1");
+14
Переглянути файл
@@ -36,6 +36,20 @@ describe("Go to Test / Test Subject", () => {
expect(d.open).toHaveBeenCalledWith("/p/src/test/java/a/FooTest.java");
});
it("uses the top-level class at the caret when a file declares several", async () => {
const files = [
"/p/src/main/java/a/Widget.java",
"/p/src/test/java/a/WidgetTest.java",
"/p/src/test/java/a/HelperTest.java",
];
const d = { ...deps(files), classAtCaret: async () => "Helper" };
await gotoTestOrSubject("/p/src/main/java/a/Widget.java", "", d);
expect(d.open).toHaveBeenCalledWith("/p/src/test/java/a/HelperTest.java");
const other = { ...deps(files), classAtCaret: async () => null };
await gotoTestOrSubject("/p/src/main/java/a/Widget.java", "", other);
expect(other.open).toHaveBeenCalledWith("/p/src/test/java/a/WidgetTest.java");
});
it("goes back from a test to its subject", async () => {
const d = deps(["/p/src/main/java/a/Foo.java", "/p/src/test/java/a/FooTest.java"]);
await gotoTestOrSubject("/p/src/test/java/a/FooTest.java", "", d);
+14 -1
Переглянути файл
@@ -36,6 +36,19 @@ export interface TestNavDeps {
/** Create New Test… in `directory` (file templates), or a Rust test module in the file itself. */
createTest: (req: { directory: string; name: string; extension: string; subject: string }) => void;
createRustTestModule: () => void;
/** Name of the top-level class, interface, enum or object around the caret, if any. */
classAtCaret?: () => Promise<string | null>;
}
/** Languages whose files are named after a class but may declare several top-level ones. */
const CLASS_FILE = /\.(java|kt|scala|groovy|cs)$/;
/** The file name as the class at the caret would have it (`Helper.java` inside `Widget.java`), else the file's own. */
async function subjectFileName(path: string, deps: TestNavDeps): Promise<string> {
const name = basename(path);
if (!CLASS_FILE.test(name) || !deps.classAtCaret) return name;
const cls = await deps.classAtCaret().catch(() => null);
return cls ? cls + splitName(name).ext : name;
}
const isRustIntegrationTest = (path: string) => path.endsWith(".rs") && /\/tests\/[^/]+\.rs$/.test(path);
@@ -88,7 +101,7 @@ function relLabel(root: string | null, path: string) {
export async function gotoTestOrSubject(path: string, text: string, deps: TestNavDeps): Promise<void> {
const roots = deps.roots();
const root = deps.projectRoot();
const name = basename(path);
const name = await subjectFileName(path, deps);
const rank = (paths: string[]) => rankCandidates(path, paths, belowRoot(root, roots));
if (isTestSide(path, roots)) {
+5 -1
Переглянути файл
@@ -22,7 +22,7 @@ import { registerRelatedProvider, relatedItems } from "@/editor/relatedProviders
import { gotoTestOrSubject, type TestNavDeps } from "./gotoTest";
import { headerSourceItems } from "./headerSource";
import { projectPythonHierarchy, pythonSuperDeps } from "./pythonHierarchy";
import { baseName, memberAt, methodStop, superMethods, type SuperDeps } from "./structureNav";
import { baseName, memberAt, methodStop, superMethods, topLevelTypeAt, type SuperDeps } from "./structureNav";
import { tx } from "@/platform/i18n";
const EDITOR_WHEN = "textEditorActive && (editorFocus || !toolWindowFocus)";
@@ -150,6 +150,10 @@ function testDeps(view: EditorView, ctx: EditorDocContext): TestNavDeps {
})),
}),
hint: (text) => showHint(view, text),
classAtCaret: async () => {
const outline = await call(commands.docOutline(ctx.doc));
return topLevelTypeAt(outline, offsetToPos(view.state.doc, view.state.selection.main.head))?.name ?? null;
},
createTest: ({ directory, name, extension }) =>
void executeAction("templates.newFromTemplate", { directory, name, extension, kindId: "test" }),
createRustTestModule: () => {
+10 -1
Переглянути файл
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
import type { HierarchyItem, OutlineItem, SymbolKind } from "@/platform/ipc";
import { memberAt, methodStop, methodStops, superMethods } from "./structureNav";
import { memberAt, methodStop, methodStops, superMethods, topLevelTypeAt } from "./structureNav";
const r = (l1: number, l2: number) => ({ start: { line: l1, col: 0 }, end: { line: l2, col: 1 } });
function item(name: string, kind: SymbolKind, from: number, to: number, children: OutlineItem[] = []): OutlineItem {
@@ -100,3 +100,12 @@ describe("Super Method", () => {
expect(await lines("eat")).toEqual([2, 4]);
});
});
describe("topLevelTypeAt", () => {
it("answers the outermost type, through namespaces, and nothing outside a type", () => {
expect(topLevelTypeAt(OUTLINE, { line: 13, col: 2 })?.name).toBe("Foo");
expect(topLevelTypeAt(OUTLINE, { line: 23, col: 0 })).toBeNull();
const ns = [item("App", "namespace", 0, 30, [item("Widget", "class", 1, 10), item("Helper", "class", 12, 20)])];
expect(topLevelTypeAt(ns, { line: 15, col: 0 })?.name).toBe("Helper");
});
});
+11
Переглянути файл
@@ -36,6 +36,17 @@ export function methodStop(outline: readonly OutlineItem[], caret: Pos, dir: 1 |
return null;
}
/** The outermost type around `caret`, looking through namespaces and packages (C#, Kotlin scripts). */
export function topLevelTypeAt(outline: readonly OutlineItem[], caret: Pos): OutlineItem | null {
let level: readonly OutlineItem[] = outline;
for (;;) {
const hit = level.find((i) => inside(i, caret));
if (!hit) return null;
if (hit.kind !== "namespace" && hit.kind !== "package") return TYPES.has(hit.kind) ? hit : null;
level = hit.children;
}
}
export interface CaretMember {
/** Innermost method at the caret. */
method: OutlineItem | null;
+32 -3
Переглянути файл
@@ -1,9 +1,23 @@
import { afterEach, expect, it, vi } from "vitest";
import type { Diagnostic, InspectEvent } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { installInspectionProfileSync, resetInspection, runInspection, useInspection } from "./inspect";
import {
installInspectionProfileSync,
rerunInspection,
resetInspection,
runInspection,
useInspection,
} from "./inspect";
const mock = vi.hoisted(() => ({ channel: null as null | { onmessage: (event: InspectEvent) => void } }));
const mock = vi.hoisted(() => ({
channel: null as null | { onmessage: (event: InspectEvent) => void },
scopes: [] as unknown[],
active: "/p/a.ts",
}));
vi.mock("@/editor/api", async (original) => ({
...(await original<object>()),
activeEditor: () => ({ ctx: { path: mock.active, virtual: false } }),
}));
vi.mock("@tauri-apps/api/core", () => ({
Channel: class {
onmessage = () => {};
@@ -14,7 +28,8 @@ vi.mock("@/platform/ipc", async (original) => ({
isTauri: () => true,
call: (value: unknown) => value,
commands: {
inspectCode: (_id: unknown, _scope: unknown, channel: typeof mock.channel) => {
inspectCode: (_id: unknown, scope: unknown, channel: typeof mock.channel) => {
mock.scopes.push(scope);
mock.channel = channel;
return Promise.resolve();
},
@@ -97,3 +112,17 @@ it("retains initially disabled diagnostics and uses edits made during streaming"
dispose();
}
});
it("reruns the file the results are for, not the file now active", async () => {
mock.scopes = [];
mock.active = "/p/a.ts";
await runInspection({ kind: "file", directory: "" }, "default");
mock.active = "/p/b.ts";
rerunInspection();
await vi.waitFor(() => expect(mock.scopes).toHaveLength(2));
expect(mock.scopes).toEqual([
{ kind: "files", paths: ["/p/a.ts"] },
{ kind: "files", paths: ["/p/a.ts"] },
]);
expect(useInspection.getState().scopeLabel).toBe("File /p/a.ts");
});
+2 -1
Переглянути файл
@@ -200,7 +200,8 @@ export async function runInspection(choice: ScopeChoice, profileId: ProfileId =
summary: null,
error: null,
scopeLabel: describeScope(choice, scope),
last: choice,
// Rerun repeats this run's scope: "Current file" stays the file inspected now.
last: choice.kind === "file" && scope.kind === "files" ? { ...choice, file: scope.paths[0] } : choice,
profile: profileId,
excluded: new Set(),
});
+3 -1
Переглянути файл
@@ -15,6 +15,8 @@ export interface ScopeChoice {
directory: string;
/** Name of the custom scope for `custom` (`@/platform/search`). */
custom?: string;
/** The file `file` resolved to, so a rerun inspects it again rather than the file now active. */
file?: string;
}
export const SCOPE_LABELS: Record<ScopeKind, string> = {
@@ -58,7 +60,7 @@ export async function resolveScope(choice: ScopeChoice): Promise<SearchScope | s
case "directory":
return choice.directory.trim() ? { kind: "directory", path: choice.directory.trim() } : "Choose a directory";
case "file": {
const file = currentFile();
const file = choice.file ?? currentFile();
return file ? { kind: "files", paths: [file] } : "No file is open";
}
case "changed": {
+19 -2
Переглянути файл
@@ -192,6 +192,20 @@ describe("replacing a project in this window", () => {
expect(useProject.getState().project?.root).toBe("/local");
});
it("asks about trust before leaving, so Don't Open keeps the current project running", async () => {
useProject.setState({
...projectState("/a"),
settings: { general: { openProjectIn: "same" } },
} as never);
windowOpenProject.mockResolvedValue(ok({ kind: "current" }));
vi.mocked(confirmProjectTrust).mockRejectedValueOnce(new IpcError({ kind: "cancelled", message: "Cancelled" }));
await openProjectWithPolicy("/b");
expect(confirmProjectTrust).toHaveBeenCalledWith("/b", "local");
expect(confirmLeaveProject).not.toHaveBeenCalled();
expect(openProject).not.toHaveBeenCalled();
expect(notify).not.toHaveBeenCalled();
});
it("opens the local project when its path matches the remote root", async () => {
useProject.setState({
...projectState("/same"),
@@ -792,11 +806,14 @@ describe("trust is asked before a new project window opens", () => {
expect(windowOpenProject).toHaveBeenCalled();
});
it("asks only once, from openProject, when the project opens in this window", async () => {
it("asks once this window takes the project, before leaving its current one", async () => {
windowOpenProject.mockResolvedValue(ok({ kind: "current" }));
await openProjectInWindow("/p/b", false);
expect(windowOpenProject).toHaveBeenCalledWith("/p/b", false, []);
expect(confirmProjectTrust).not.toHaveBeenCalled();
expect(confirmProjectTrust).toHaveBeenCalledOnce();
expect(vi.mocked(confirmProjectTrust).mock.invocationCallOrder[0]).toBeLessThan(
vi.mocked(confirmLeaveProject).mock.invocationCallOrder[0]!,
);
expect(openProject).toHaveBeenCalledWith("/p/b");
});
});
+10 -1
Переглянути файл
@@ -25,6 +25,7 @@ import { isDistractionFree, useDistractionFree } from "@/workbench/distractionFr
import { orderStatusItems } from "@/workbench/StatusBar";
import { statusWidgetRows } from "@/workbench/statusBarWidgets";
import { useToolWindowLayouts } from "@/workbench/toolwindows/layouts";
import { toolWindowsRestorable, useToolWindowLayout } from "@/workbench/toolwindows/store";
import { hostOs, type HostOs } from "./host";
export const MENU_EVENT = "openidea://menu";
@@ -100,7 +101,11 @@ export function menuAccelerator(binding: string): string | undefined {
export function buildMenuConfig(os: HostOs): MenuConfig {
const labels: Record<string, string> = {};
// Per-window state some labels follow (View › Appearance › Enter / Exit Distraction Free Mode).
const params = { os, distractionFree: isDistractionFree() ? "on" : "off" };
const params = {
os,
distractionFree: isDistractionFree() ? "on" : "off",
toolWindows: toolWindowsRestorable() ? "hidden" : "shown",
};
for (const key of keysWithPrefix("menu.")) labels[key] = t(key, params);
const accelerators: Record<string, string> = {};
const seen = new Set<string>();
@@ -265,6 +270,10 @@ export function installMenuBridge(): () => void {
useDistractionFree.subscribe((s, prev) => {
if (s.active !== prev.active) push();
}),
// Window › Hide All Tool Windows reads "Restore Tool Windows" while it would restore them.
useToolWindowLayout.subscribe((s, prev) => {
if (toolWindowsRestorable(s) !== toolWindowsRestorable(prev)) push();
}),
useContributions.subscribe((s, prev) => {
if (s.toolWindows !== prev.toolWindows || s.statusItems !== prev.statusItems) push();
}),
+7
Переглянути файл
@@ -57,6 +57,13 @@ async function openHere(path: string): Promise<boolean> {
if (!isRemoteWindow() && useProject.getState().project?.root === path) return true;
// A folder of a WSL distro runs there, not as a network folder; the window then drops untitled buffers.
const wsl = await commands.wslResolve(path).catch(() => null);
try {
// Asked before leaving, so Don't Open keeps the current project and its processes running.
if (!wsl) await confirmProjectTrust(path, "local");
} catch (e) {
openFailed(path, e);
return false;
}
if (!(await confirmLeaveProject(!wsl))) return false;
try {
if (wsl) await connectRemote(wsl.target, wsl.path);
+12
Переглянути файл
@@ -24,6 +24,18 @@ describe("Language server status popup", () => {
off();
});
it("opens a server's settings from its row", () => {
const run = vi.fn();
const off = registerAction({ id: "tools.languageServers", title: "Language Servers…", run: ({ arg }) => run(arg) });
useServers.setState({ servers: new Map([[1 as never, server("ready", null)]]) });
render(<ServerStatus />);
fireEvent.click(screen.getByRole("button", { name: /Language servers/ }));
fireEvent.click(screen.getByRole("button", { name: "Configure jdtls…" }));
expect(run).toHaveBeenCalledWith("jdtls");
expect(screen.queryByRole("button", { name: "Configure jdtls…" })).toBeNull();
off();
});
it("keeps Restart for other failures", () => {
useServers.setState({ servers: new Map([[1 as never, server("crashed", "exit code 1")]]) });
render(<ServerStatus />);
+13 -1
Переглянути файл
@@ -1,4 +1,4 @@
/** Status bar widget listing language servers, with a popup to restart them. */
/** Status bar widget listing language servers, with a popup to restart or configure them. */
import { useMemo, useRef, useState } from "react";
import clsx from "clsx";
import { getAction, executeAction } from "@/platform/actions";
@@ -18,6 +18,7 @@ export function ServerStatus() {
const summary = serversSummary(servers);
// features/tools owns installing; without it, fall back to the manual hint text.
const canInstall = !!getAction("tools.install");
const canConfigure = !!getAction("tools.languageServers");
if (!summary) return null;
return (
<>
@@ -92,6 +93,17 @@ export function ServerStatus() {
/>
</>
)}
{canConfigure && (
<IconButton
icon="settings"
size="small"
title={tx`Configure ${serverLabel(s)}…`}
onClick={() => {
setOpen(false);
void executeAction("tools.languageServers", s.name);
}}
/>
)}
</div>
{(s.languages.length > 0 || s.root) && (
<div className={styles.meta}>
+57
Переглянути файл
@@ -0,0 +1,57 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { act, cleanup, fireEvent, render, screen, within } from "@testing-library/react";
import { provideEditorService } from "@/workbench/contributions";
import { addBreakpoint, useBreakpoints } from "../breakpoints/store";
import { DebuggerOverlays } from "../ui/Overlays";
import { useOverlays } from "../ui/popoverStore";
const openFile = vi.fn(async () => undefined);
provideEditorService({ openFile } as never);
const path = "/p/main.py";
describe("the Breakpoints dialog", () => {
beforeEach(() => {
openFile.mockClear();
useBreakpoints.setState({ byFile: {}, status: {}, muted: false });
const first = addBreakpoint(path, 2, { condition: "value == 2" });
addBreakpoint(path, 6);
useOverlays.setState({ breakpoints: { id: first.id } } as never);
});
afterEach(() => {
cleanup();
act(() => useOverlays.setState({ breakpoints: null } as never));
});
const dialog = () => screen.getByRole("dialog", { name: "Breakpoints" });
const row = (name: string) => within(within(dialog()).getByLabelText("All breakpoints")).getByText(name);
const condition = () => within(dialog()).getByLabelText("Condition") as HTMLInputElement;
/** A row's mouse click as the list sees it: mousedown selects, click (with its count) activates. */
const clickRow = (name: string, detail: number) => {
fireEvent.mouseDown(row(name), { button: 0 });
fireEvent.click(row(name), { detail });
};
const breakpointAt = (line: number) => useBreakpoints.getState().byFile[path]!.find((b) => b.line === line)!;
it("selects a breakpoint on click and goes to its source on double-click", () => {
render(<DebuggerOverlays />);
clickRow("main.py:7", 1);
expect(openFile).not.toHaveBeenCalled();
// Its details show beside the list.
expect(within(dialog()).getAllByText("main.py:7")).toHaveLength(2);
clickRow("main.py:3", 2);
expect(openFile).toHaveBeenCalledWith(path, { selection: { line: 2, col: 0 } });
});
it("saves the condition being typed when the dialog closes or another breakpoint is shown", () => {
render(<DebuggerOverlays />);
fireEvent.change(condition(), { target: { value: "value == 1" } });
fireEvent.click(within(dialog()).getByRole("button", { name: "Done" }));
expect(breakpointAt(2).condition).toBe("value == 1");
act(() => useOverlays.setState({ breakpoints: { id: breakpointAt(2).id } } as never));
fireEvent.change(condition(), { target: { value: "value == 3" } });
clickRow("main.py:7", 1);
expect(breakpointAt(2).condition).toBe("value == 3");
});
});
+58 -10
Переглянути файл
@@ -179,12 +179,19 @@ function BreakpointFields({
const commitText = () => {
const d = draft.current;
const cond = d.condition.trim() || null;
if (cond) pushHistory("condition", cond);
updateBreakpoint(path, bp.id, {
const changes = {
condition: cond,
hitCondition: d.hitCondition.trim() || null,
logMessage: d.logEval ? d.logMessage.trim() || null : null,
});
};
if (
changes.condition === (bp.condition ?? null) &&
changes.hitCondition === (bp.hitCondition ?? null) &&
changes.logMessage === (bp.logMessage ?? null)
)
return;
if (cond) pushHistory("condition", cond);
updateBreakpoint(path, bp.id, changes);
};
useEffect(() => {
if (!commitRef) return;
@@ -396,9 +403,13 @@ function BreakpointsDialog() {
}, [byFile, methods, fields]);
const items = rows.filter((r) => r.type !== "section");
const [selected, setSelected] = useState<string | null>(null);
// The shown breakpoint's typed fields, saved before it is closed or another one is shown:
// Enter on Done and a click on a row don't blur them.
const commitRef = useRef<(() => void) | null>(null);
const open = !!state;
const current = items.find((r) => r.key === (selected ?? state?.id)) ?? items[0];
const close = () => {
commitRef.current?.();
setSelected(null);
useOverlays.setState({ breakpoints: null });
};
@@ -448,8 +459,14 @@ function BreakpointsDialog() {
isSection={(r) => r.type === "section"}
renderSection={(r) => <div className={styles.exceptionAdapter}>{r.type === "section" ? r.label : ""}</div>}
activeIndex={current ? rows.indexOf(current) : -1}
onActiveChange={(i) => setSelected(rows[i]?.key ?? null)}
onActivate={(r) => goTo(r)}
onActiveChange={(i) => {
commitRef.current?.();
setSelected(rows[i]?.key ?? null);
}}
// A click selects; double-click or Enter goes to the source.
onActivate={(r, _i, e) => {
if (e.type === "keydown" || e.detail > 1) goTo(r);
}}
aria-label="All breakpoints"
className={styles.bpList}
empty={
@@ -522,9 +539,9 @@ function BreakpointsDialog() {
</div>
<div className={styles.bpDetail}>
{current?.type === "line" ? (
<BreakpointDetail key={current.key} row={current} onGo={() => goTo(current)} />
<BreakpointDetail key={current.key} row={current} onGo={() => goTo(current)} commitRef={commitRef} />
) : current?.type === "special" ? (
<SpecialDetail key={current.key} bp={current.bp} onGo={() => goTo(current)} />
<SpecialDetail key={current.key} bp={current.bp} onGo={() => goTo(current)} commitRef={commitRef} />
) : null}
</div>
</div>
@@ -579,7 +596,15 @@ function ExceptionBreakpoints({ open }: { open: boolean }) {
);
}
function BreakpointDetail({ row, onGo }: { row: BpRow; onGo: () => void }) {
function BreakpointDetail({
row,
onGo,
commitRef,
}: {
row: BpRow;
onGo: () => void;
commitRef: MutableRefObject<(() => void) | null>;
}) {
const { path, bp } = row;
const st = useBreakpoints((s) => s.status[bp.id]);
return (
@@ -597,7 +622,7 @@ function BreakpointDetail({ row, onGo }: { row: BpRow; onGo: () => void }) {
</Button>
</div>
{st && <div className={styles.statusLine}>{st.verified ? tx("Verified") : (st.message ?? "Not verified")}</div>}
<BreakpointFields path={path} bp={bp} />
<BreakpointFields path={path} bp={bp} commitRef={commitRef} />
<Checkbox
checked={!!bp.temporary}
onChange={(temporary) => updateBreakpoint(path, bp.id, { temporary })}
@@ -607,11 +632,34 @@ function BreakpointDetail({ row, onGo }: { row: BpRow; onGo: () => void }) {
);
}
function SpecialDetail({ bp, onGo }: { bp: SpecialBreakpoint; onGo: () => void }) {
function SpecialDetail({
bp,
onGo,
commitRef,
}: {
bp: SpecialBreakpoint;
onGo: () => void;
commitRef: MutableRefObject<(() => void) | null>;
}) {
const st = useSpecialBreakpoints((s) => s.status[bp.id]);
const [name, setName] = useState(bp.kind === "method" ? bp.name : bp.label);
const [condition, setCondition] = useState(bp.condition ?? "");
const [hitCondition, setHitCondition] = useState(bp.hitCondition ?? "");
const draft = useRef({ name, condition, hitCondition });
useEffect(() => {
draft.current = { name, condition, hitCondition };
commitRef.current = () => {
const d = draft.current;
updateSpecial(bp.id, {
name: d.name.trim(),
condition: d.condition.trim() || null,
hitCondition: d.hitCondition.trim() || null,
});
};
return () => {
commitRef.current = null;
};
});
return (
<div className={styles.detail}>
<div className={styles.bpTitle}>
+10 -2
Переглянути файл
@@ -149,19 +149,27 @@ export function activate(): () => void {
/** The last complete result: what a refresh shows for ecosystems that haven't reported yet. */
let settled: LibraryGroup[] = [];
let request: RequestId | undefined;
/** The project whose libraries are shown (and `settled`). */
let shownFor: string | null = null;
const clear = () => {
disposeRoot();
disposeReadOnly();
disposeRoot = disposeReadOnly = () => {};
shown = "";
settled = [];
shownFor = null;
};
const refresh = () => {
const id = ++seq;
if (request !== undefined) void commands.cancelRequest(request).catch(() => {});
request = undefined;
if (!useProject.getState().project || useProject.getState().project?.trusted === false || !isTauri())
return clear();
const project = useProject.getState().project;
if (!project || project.trusted === false || !isTauri()) return clear();
// Another project's libraries must not show (or fill in) while this one's are discovered.
if (shownFor !== project.root) {
clear();
shownFor = project.root;
}
let collected: LibraryGroup[] = [];
const show = (groups: LibraryGroup[]) => {
if (id !== seq) return;
+19
Переглянути файл
@@ -4,6 +4,8 @@ import type { LibraryGroup } from "@/bindings";
const results: LibraryGroup[][] = [];
/** Batches the next request streams before it answers. */
const streamed: LibraryGroup[][] = [];
/** The next request never answers (discovery still running). */
let hang = false;
vi.mock("@tauri-apps/api/core", () => ({
Channel: class {
@@ -19,6 +21,7 @@ vi.mock("@/bindings", () => ({
vi.mock("@/platform/ipc", () => ({
call: (request: [string, { onmessage: (v: unknown) => void }]) => {
for (const batch of streamed.splice(0)) request[1].onmessage(batch);
if (hang) return new Promise(() => {});
return Promise.resolve(results.shift() ?? []);
},
isCancelled: () => false,
@@ -67,4 +70,20 @@ describe("External Libraries refresh", () => {
dispose();
expect(useProjectViewRoots.getState().roots.has("externalLibraries")).toBe(false);
});
it("drops the previous project's libraries while the next project's are discovered", async () => {
const project = (root: string) => ({ root, trusted: true }) as ReturnType<typeof useProject.getState>["project"];
useProject.setState({ project: project("/p") });
results.push([rust("1.0.19")]);
const dispose = activate();
await vi.waitFor(() => expect(useProjectViewRoots.getState().roots.has("externalLibraries")).toBe(true));
hang = true;
try {
useProject.setState({ project: project("/q") });
expect(useProjectViewRoots.getState().roots.has("externalLibraries")).toBe(false);
} finally {
hang = false;
dispose();
}
});
});
+7
Переглянути файл
@@ -91,6 +91,13 @@
outline: 1px solid var(--fg-muted);
outline-offset: -1px;
}
.flame:focus {
outline: none;
}
.flame:focus .current {
outline: 2px solid var(--accent);
outline-offset: -2px;
}
.c1 {
background: var(--flame-1);
}
+21 -1
Переглянути файл
@@ -1,5 +1,5 @@
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { render, screen, within } from "@testing-library/react";
import { fireEvent, render, screen, within } from "@testing-library/react";
import type { Profile, ProfileMode } from "@/platform/ipc";
import { useI18n } from "@/platform/i18n";
import { ProfilerTabs, ProfilerView } from "./ProfilerView";
@@ -48,6 +48,26 @@ describe("ProfilerView", () => {
expect(screen.getByText("async-profiler · 610.4 MB allocated")).toBeInTheDocument();
});
it("moves through the flame graph and zooms with the keyboard", () => {
addSnapshot("App", profile("cpu", 100));
render(<ProfilerView />);
const graph = screen.getByRole("tree", { name: "Flame graph" });
expect(graph.tabIndex).toBe(0);
const current = () =>
document.getElementById(graph.getAttribute("aria-activedescendant")!)?.getAttribute("aria-label");
expect(current()).toBe("all (100 ms)");
fireEvent.keyDown(graph, { key: "ArrowUp" });
expect(current()).toBe("Main.run");
fireEvent.keyDown(graph, { key: "Enter" });
expect(screen.getByText("Zoomed into Main.run")).toBeInTheDocument();
fireEvent.keyDown(graph, { key: "ArrowUp" });
expect(current()).toBe("Main.work");
fireEvent.keyDown(graph, { key: "ArrowDown" });
expect(current()).toBe("Main.run");
fireEvent.keyDown(graph, { key: "Escape" });
expect(screen.queryByText("Zoomed into Main.run")).toBeNull();
});
it("marks the allocated type in the flame graph and the method list", () => {
addSnapshot("App", profile("allocations", 640_000_000));
const flame = render(<ProfilerView />);
+41 -4
Переглянути файл
@@ -3,12 +3,12 @@
* (click to zoom, search highlights), the call tree (top-down) and the method
* list (self / total). Double-click opens a frame's source when known.
*/
import { useLayoutEffect, useMemo, useRef, useState } from "react";
import { useEffect, useLayoutEffect, useMemo, useRef, useState, type KeyboardEvent } from "react";
import clsx from "clsx";
import type { Profile } from "@/platform/ipc";
import { EmptyState, Icon, IconButton, Input, Tabs, Tree, T } from "@/ui";
import { editorService } from "@/workbench/contributions";
import { colorSlot, flameLayout, formatWeight, frameLocation, matchingFrames, share } from "./model";
import { colorSlot, flameLayout, flameStep, formatWeight, frameLocation, matchingFrames, share } from "./model";
import { activeSnapshot, closeSnapshot, useProfiler, type ProfilerTab } from "./store";
import styles from "./Profiler.module.css";
import { useTx } from "@/platform/i18n";
@@ -96,6 +96,28 @@ function FlameGraph({ profile, query }: { profile: Profile; query: string }) {
return () => ro.disconnect();
}, []);
const layout = useMemo(() => flameLayout(profile, focus, width > 0 ? 1 / width : 0.002), [profile, focus, width]);
// The frame the keyboard is on: arrows move it, Enter zooms into it, F4 opens its source.
const [current, setCurrent] = useState(0);
const shown = layout.rects.some((r) => r.node === current) ? current : focus;
const onKeyDown = (e: KeyboardEvent<HTMLDivElement>) => {
const moves: Record<string, Parameters<typeof flameStep>[2]> = {
ArrowUp: "deeper",
ArrowDown: "shallower",
ArrowLeft: "previous",
ArrowRight: "next",
};
const move = moves[e.key];
if (move) setCurrent(flameStep(layout.rects, shown, move));
else if (e.key === "Enter") setFocus(shown);
else if (e.key === "Escape" && focus !== 0) setFocus(0);
else if (e.key === "F4") openFrame(profile, profile.nodes[shown]!.frame);
else return;
e.preventDefault();
e.stopPropagation();
};
useEffect(() => {
ref.current?.querySelector(`[data-node="${shown}"]`)?.scrollIntoView?.({ block: "nearest" });
}, [shown]);
const matches = useMemo(() => matchingFrames(profile, query), [profile, query]);
const unit = profile.unit;
const total = profile.total ?? 0;
@@ -109,7 +131,15 @@ function FlameGraph({ profile, query }: { profile: Profile; query: string }) {
</div>
)}
<div className={styles.flameScroll} ref={ref}>
<div className={styles.flame} style={{ height: layout.depth * ROW }} role="tree" aria-label={tx("Flame graph")}>
<div
className={styles.flame}
style={{ height: layout.depth * ROW }}
role="tree"
aria-label={tx("Flame graph")}
tabIndex={0}
aria-activedescendant={`flame-frame-${shown}`}
onKeyDown={onKeyDown}
>
{width > 0 &&
layout.rects.map((r) => {
const node = profile.nodes[r.node]!;
@@ -120,17 +150,24 @@ function FlameGraph({ profile, query }: { profile: Profile; query: string }) {
return (
<div
key={r.node}
id={`flame-frame-${r.node}`}
data-node={r.node}
role="treeitem"
aria-label={label}
aria-selected={r.node === shown}
className={clsx(
styles.frame,
r.node === shown && styles.current,
styles[`c${colorSlot(frame.name)}`],
frame.kind === "allocatedType" && styles.typeFrame,
matches && (matches.has(node.frame) ? styles.match : styles.dim),
)}
style={{ left: r.x * width, width: Math.max(w - 1, 1), bottom: r.depth * ROW }}
title={`${frame.kind === "allocatedType" ? `${tx("Allocated type")}\n` : ""}${frame.name}${location ? ` (${location})` : ""}\nTotal: ${formatWeight(node.total ?? 0, unit)} (${share(node.total ?? 0, total)})\nSelf: ${formatWeight(node.selfWeight ?? 0, unit)}`}
onClick={() => setFocus(r.node)}
onClick={() => {
setCurrent(r.node);
setFocus(r.node);
}}
onDoubleClick={() => openFrame(profile, node.frame)}
>
{w > 28 && <span className={styles.frameText}>{label}</span>}
+28
Переглянути файл
@@ -110,6 +110,34 @@ export function flameLayout(profile: Profile, focus = 0, minWidth = 0.002): { re
return { rects, depth: maxDepth + 1 };
}
/**
* Keyboard moves in the flame graph from the frame `node`: `deeper` to its widest callee,
* `shallower` to its caller, `previous` / `next` to the neighbouring frame on its row.
*/
export function flameStep(
rects: readonly FlameRect[],
node: number,
move: "deeper" | "shallower" | "previous" | "next",
): number {
const at = rects.find((r) => r.node === node);
if (!at) return rects[0]?.node ?? node;
switch (move) {
case "deeper": {
const inside = rects.filter((r) => r.depth === at.depth + 1 && r.x >= at.x && r.x < at.x + at.width);
return inside.reduce<FlameRect | undefined>((a, r) => (!a || r.width > a.width ? r : a), undefined)?.node ?? node;
}
case "shallower":
// A callee starts inside its caller's span.
return rects.find((r) => r.depth === at.depth - 1 && r.x <= at.x && at.x < r.x + r.width)?.node ?? node;
case "previous":
case "next": {
const row = rects.filter((r) => r.depth === at.depth).sort((a, b) => a.x - b.x);
const i = row.indexOf(at) + (move === "next" ? 1 : -1);
return row[i]?.node ?? node;
}
}
}
const parentCache = new WeakMap<Profile, Int32Array>();
/** Parent node of every node (-1 for the root). */
+20
Переглянути файл
@@ -4,6 +4,7 @@ import {
allocationProfilerSupports,
colorSlot,
flameLayout,
flameStep,
formatWeight,
frameLocation,
matchingFrames,
@@ -108,3 +109,22 @@ describe("profiler model", () => {
expect(colorSlot("main")).toBeGreaterThanOrEqual(1);
});
});
describe("flameStep", () => {
// root (0) → a (1, 60%) and b (2, 40%); a → c (3)
const rects = [
{ node: 0, depth: 0, x: 0, width: 1 },
{ node: 1, depth: 1, x: 0, width: 0.6 },
{ node: 2, depth: 1, x: 0.6, width: 0.4 },
{ node: 3, depth: 2, x: 0, width: 0.5 },
];
it("goes to the widest callee, the caller and the neighbours on a row", () => {
expect(flameStep(rects, 0, "deeper")).toBe(1);
expect(flameStep(rects, 1, "next")).toBe(2);
expect(flameStep(rects, 2, "next")).toBe(2);
expect(flameStep(rects, 2, "previous")).toBe(1);
expect(flameStep(rects, 2, "deeper")).toBe(2);
expect(flameStep(rects, 3, "shallower")).toBe(1);
expect(flameStep(rects, 2, "shallower")).toBe(0);
});
});
+4 -1
Переглянути файл
@@ -86,6 +86,7 @@ import {
VIEW_MODES,
autoExpand,
clearRevealRequest,
explainHiddenPath,
loadDir,
loadOutline,
revealPath,
@@ -517,7 +518,7 @@ export function ProjectView() {
// Select a revealed path once its row exists.
useEffect(() => {
if (!revealRequest) return;
const { path, focus, seq } = revealRequest;
const { path, focus, seq, explain } = revealRequest;
const exact = model.keyOfPath.get(path);
const loadingAncestors = info.pending.some((p) => p === path || isInside(path, p));
if (!exact && loadingAncestors) return;
@@ -528,6 +529,8 @@ export function ProjectView() {
handle.current?.reveal(key);
revealing.current = false;
if (focus) handle.current?.focus();
const shown = model.byKey.get(key)?.path;
if (explain && !exact && shown) explainHiddenPath(path, shown);
}, [revealRequest, model, info]);
// Autoscroll from source: follow the active editor.
+1 -1
Переглянути файл
@@ -108,7 +108,7 @@ export function selectInProjectView(path?: string | null, focus = true) {
if (!target) return false;
if (!modeShows(target)) setViewMode("project");
showProjectView(focus);
return revealPath(target, focus);
return revealPath(target, focus, true);
}
/**
+28
Переглянути файл
@@ -7,6 +7,8 @@ import {
reloadLoadedDirs,
currentModel,
expandAll,
explainHiddenPath,
hidingOption,
initProjectTree,
loadDir,
revealPath,
@@ -18,6 +20,7 @@ import {
} from "./store";
import { beginNew, commitEditing, copySelection, paste, transfer } from "./operations";
import { closeFileRefactorDialog, pendingFileRefactorDialog } from "./FileRefactorDialogs";
import { provideNotificationService } from "@/workbench/contributions";
const ROOT = "/p";
let fs: MemoryFs;
@@ -319,3 +322,28 @@ it("keeps the primary first and sorts attachments by name", () => {
initProjectTree("/ws", "Workspace", ["/z", "/c", "/a"]);
expect(currentModel().roots.map((n) => n.path)).toEqual(["/a", "/c", "/z"]);
});
describe("a file the view options hide", () => {
const entry = (name: string, ignored = false) => ({ name, path: `/p/${name}`, isDir: true, ignored }) as never;
it("names the option that hides it below the shown ancestor, and offers to turn it on", () => {
useProjectTree.setState({ listings: new Map([["/p", [entry("build", true), entry("src")]]]) });
setViewOption("showExcluded", false);
expect(hidingOption("/p/build/out.txt", "/p")).toBe("showExcluded");
expect(hidingOption("/p/.git/config", "/p")).toBe(
useProjectTree.getState().options.showHidden ? null : "showHidden",
);
expect(hidingOption("/p/src/a.ts", "/p")).toBeNull();
const notify = vi.fn();
provideNotificationService({ notify } as never);
explainHiddenPath("/p/build/out.txt", "/p");
expect(notify).toHaveBeenCalledWith(
expect.objectContaining({ title: "out.txt is hidden because Show Excluded Files is off" }),
);
notify.mock.calls[0]![0].actions[0].run();
expect(useProjectTree.getState().options.showExcluded).toBe(true);
expect(useProjectTree.getState().revealRequest?.path).toBe("/p/build/out.txt");
expect(hidingOption("/p/build/out.txt", "/p")).toBeNull();
});
});
+46 -3
Переглянути файл
@@ -10,6 +10,9 @@ import { commands, type FileEntry, type OutlineItem } from "@/bindings";
import { withDocument } from "@/editor/lsp/files";
import { IpcError } from "@/platform/ipc";
import { libraryEntryPaths } from "@/platform/virtualDocs";
import { isIgnoredName } from "@/platform/ignoredNames";
import { tx } from "@/platform/i18n";
import { notifications } from "@/workbench/contributions";
import { ipcPath } from "@/platform/paths";
import {
DEFAULT_TREE_OPTIONS,
@@ -122,7 +125,8 @@ interface ProjectTreeState {
editing: Editing | null;
clipboard: Clipboard | null;
/** A path to select (and scroll to) once its row is visible. */
revealRequest: { path: string; focus: boolean; seq: number } | null;
/** `explain`: say which view option hides the path when only an ancestor can be selected. */
revealRequest: { path: string; focus: boolean; seq: number; explain?: boolean } | null;
/** Folder key highlighted as drop target. */
dropTarget: string | null;
mode: ViewMode;
@@ -635,7 +639,7 @@ export function dropOutlines(paths: readonly string[]) {
let revealSeq = 0;
/** Expands the ancestors of `path` and selects it once visible. */
export function revealPath(requested: string, focus = false) {
export function revealPath(requested: string, focus = false, explain = false) {
const { expanded } = get();
const project = get().root;
if (!project) return false;
@@ -668,7 +672,7 @@ export function revealPath(requested: string, focus = false) {
changed = true;
}
if (changed) setExpanded(next);
set({ revealRequest: { path, focus, seq: ++revealSeq } });
set({ revealRequest: { path, focus, seq: ++revealSeq, ...(explain ? { explain } : {}) } });
for (const a of folders) void loadDir(a);
return true;
}
@@ -734,6 +738,45 @@ function groupAncestors(model: TreeModel, key: string): string[] {
}
}
/**
* The view option that hides `path` below its shown ancestor `shown`: a hidden name
* (Show Hidden Files) or an ignored entry (Show Excluded Files). Null when no option does.
*/
export function hidingOption(path: string, shown: string): "showHidden" | "showExcluded" | null {
const { listings, options } = get();
if (!isSameOrInside(path, shown) || path === shown) return null;
let dir = shown;
for (const name of path.slice(shown.length + 1).split("/")) {
if (isIgnoredName(name)) return options.showHidden ? null : "showHidden";
if (listings.get(dir)?.find((e) => e.name === name)?.ignored) return options.showExcluded ? null : "showExcluded";
dir = `${dir}/${name}`;
}
return null;
}
const OPTION_TITLES = { showHidden: "Show Hidden Files", showExcluded: "Show Excluded Files" } as const;
/** Select Opened File reached only `shown`: say which option hides `path`, offering to turn it on. */
export function explainHiddenPath(path: string, shown: string) {
const option = hidingOption(path, shown);
if (!option) return;
const title = OPTION_TITLES[option];
notifications().notify({
level: "info",
key: "project.hiddenPath",
title: tx`${nameOf(path)} is hidden because ${title} is off`,
actions: [
{
label: tx(title),
run: () => {
setViewOption(option, true);
revealPath(path, true);
},
},
],
});
}
export function clearRevealRequest(seq: number) {
if (get().revealRequest?.seq === seq) set({ revealRequest: null });
}
+27 -1
Переглянути файл
@@ -140,6 +140,14 @@ function TrustSettings() {
setError(String(e));
}
};
const trust = async (path: string) => {
try {
await call(commands.projectTrustSet(path, true, false));
await refresh();
} catch (e) {
setError(String(e));
}
};
const addLocation = async () => {
try {
const { open } = await import("@/platform/dialog");
@@ -169,6 +177,24 @@ function TrustSettings() {
</Button>
</div>
))}
{decisions?.restricted.length ? (
<>
<h3>
<T>Restricted projects</T>
</h3>
<p className={styles.hint}>
<T>These projects open in Restricted Mode, even inside a trusted location.</T>
</p>
{decisions.restricted.map((path) => (
<div className={styles.row} key={path}>
<span className={styles.path}>{path}</span>
<Button onClick={() => void trust(path)}>
<T>Trust</T>
</Button>
</div>
))}
</>
) : null}
<div className={styles.sectionHead}>
<h3>
<T>Trusted locations</T>
@@ -178,7 +204,7 @@ function TrustSettings() {
</Button>
</div>
<p className={styles.hint}>
<T>Every project inside a trusted location is trusted without asking.</T>
<T>Every project inside a trusted location is trusted without asking, unless it is a restricted project.</T>
</p>
{decisions?.locations.map((path) => (
<div className={styles.row} key={path}>
+5 -1
Переглянути файл
@@ -58,9 +58,13 @@
justify-content: space-between;
gap: var(--space-3);
}
.sectionHead h3 {
.content h3 {
margin: 0;
}
.content > h3,
.sectionHead {
margin-top: var(--space-3);
}
.hint {
color: var(--fg-secondary);
}
+19 -1
Переглянути файл
@@ -1,5 +1,5 @@
import { afterEach, beforeEach, expect, it, vi } from "vitest";
import { act, fireEvent, render, screen } from "@testing-library/react";
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { confirmProjectTrust } from "@/platform/projectTrust";
import { executeAction } from "@/platform/actions";
import { emitLocalIdeEvent } from "@/platform/ipc";
@@ -165,6 +165,24 @@ it("adds a picked folder as a trusted location from settings", async () => {
expect(addLocation).toHaveBeenCalledTimes(1);
});
it("lists restricted projects, which a trusted location doesn't cover, and trusts one from settings", async () => {
const Page = useSettingsPages.getState().pages.get("projectTrust")!.component!;
listDecisions.mockResolvedValue({
status: "ok",
data: { projects: [], locations: ["/projects"], restricted: ["/projects/app"] },
});
render(<Page />);
expect(await screen.findByRole("heading", { name: "Restricted projects" })).toBeTruthy();
listDecisions.mockResolvedValue({
status: "ok",
data: { projects: ["/projects/app"], locations: ["/projects"], restricted: [] },
});
fireEvent.click(screen.getByRole("button", { name: "Trust" }));
await waitFor(() => expect(screen.queryByRole("heading", { name: "Restricted projects" })).toBeNull());
expect(decide).toHaveBeenCalledWith("/projects/app", true, false);
expect(screen.getByText("/projects/app")).toBeTruthy();
});
it.each(["Trust Project", "Preview in Restricted Mode"])(
"keeps a local opening's trust decision on the client: %s",
async (button) => {
+15 -3
Переглянути файл
@@ -36,6 +36,7 @@ import {
import { selectedTarget } from "./sessionTargets";
import styles from "./Run.module.css";
import { tx } from "@/platform/i18n";
import { confirm } from "@/workbench/messages";
type Row =
/** A labelled group, or a thin separator when `label` is empty. */
@@ -111,6 +112,16 @@ function anchorElement(): Element | { x: number; y: number } {
}
/** Run/Debug configuration chooser popup (⌃⌥R), anchored to the title bar widget. */
/** Deletes a configuration from the chooser once the user confirms, as IDEA's popup asks first. */
async function askDeleteConfig(config: RunConfig) {
const ok = await confirm({
title: "Confirmation",
message: tx`Are you sure you want to delete ${config.name}?`,
ok: "Delete",
});
if (ok) await deleteConfig(config.id);
}
export function ConfigChooserOverlay() {
const open = useRun((s) => s.chooserOpen);
if (!open) return null;
@@ -250,10 +261,11 @@ function ConfigChooser() {
e.key === "Delete" &&
row?.type === "config" &&
canDeleteConfig(row.config.id) &&
input().selectionStart === query.length
input().selectionStart === query.length &&
input().selectionEnd === query.length
) {
e.preventDefault();
void deleteConfig(row.config.id);
void askDeleteConfig(row.config);
return;
}
if (numbers.size && !e.altKey && !e.ctrlKey && !e.metaKey && /^Digit[1-9]$|^Numpad[1-9]$/.test(e.code)) {
@@ -286,7 +298,7 @@ function ConfigChooser() {
{ kind: "header", label: "Configuration" },
{ label: "Edit…", icon: "edit", run: () => activate(row, "edit") },
{ label: pinned.includes(c.id) ? "Unpin" : "Pin", icon: "pin", run: () => togglePinned(c.id) },
...(canDeleteConfig(c.id) ? [{ label: "Delete", danger: true, run: () => void deleteConfig(c.id) }] : []),
...(canDeleteConfig(c.id) ? [{ label: "Delete", danger: true, run: () => void askDeleteConfig(c) }] : []),
];
};
const openMenu = (c: RunConfig, at: Element) => setMenu({ name: c.name, anchor: at, items: menuItems(c) });
+29 -3
Переглянути файл
@@ -1,5 +1,5 @@
import { afterEach, beforeEach, expect, it, vi } from "vitest";
import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { act, cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
const ipc = vi.hoisted(() => ({
runSaveConfigs: vi.fn(),
@@ -17,6 +17,7 @@ vi.mock("@/platform/ipc", async (importOriginal) => ({
import type { RunConfig } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { MessagesHost } from "@/workbench/messages";
import { EditConfigsOverlay } from "./EditConfigsDialog";
import { ConfigChooserOverlay } from "./ConfigChooser";
import {
@@ -141,14 +142,39 @@ it("keeps other temporary and non-temporary configurations on removal", async ()
expect(useRun.getState().configs.map((c) => c.id)).toEqual(expect.arrayContaining(["npm:app", other.id]));
});
it("chooser popup Delete removes the selected detection", async () => {
it("chooser popup Delete removes the selected detection once confirmed", async () => {
useRun.setState({ chooserOpen: true, editorOpen: false });
render(<ConfigChooserOverlay />);
render(
<>
<ConfigChooserOverlay />
<MessagesHost />
</>,
);
fireEvent.keyDown(document.querySelector("input[data-autofocus]")!, { key: "Delete" });
const ask = await screen.findByRole("dialog", { name: "Confirmation" });
expect(ipc.runSaveConfigs).not.toHaveBeenCalled();
fireEvent.click(within(ask).getByRole("button", { name: "Delete" }));
await waitFor(() => expect(ipc.runSaveConfigs).toHaveBeenCalledWith([], ["npm:app"]));
await waitFor(() => expect(useRun.getState().configs).toEqual([]));
});
it("chooser popup Delete edits the search text when the caret is not at its end", async () => {
useRun.setState({ chooserOpen: true, editorOpen: false });
render(
<>
<ConfigChooserOverlay />
<MessagesHost />
</>,
);
const input = document.querySelector<HTMLInputElement>("input[data-autofocus]")!;
fireEvent.change(input, { target: { value: "app" } });
input.setSelectionRange(1, 1);
fireEvent.keyDown(input, { key: "Delete" });
await act(async () => {});
expect(screen.queryByRole("dialog", { name: "Confirmation" })).toBeNull();
expect(ipc.runSaveConfigs).not.toHaveBeenCalled();
});
it("Cancel discards a pending detected removal", () => {
render(<EditConfigsOverlay />);
fireEvent.click(screen.getByRole("button", { name: "Remove Configuration" }));
+26 -2
Переглянути файл
@@ -26,7 +26,7 @@ import { sampleFileName } from "@/platform/fileTypes";
import type { LanguageChoice } from "./backend";
import { onIdeEvent } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { useSettingsForm } from "@/workbench/contributions";
import { useSettingsForm, useSettingsPageFocus } from "@/workbench/contributions";
import {
languageNames,
NewServerDialog,
@@ -644,6 +644,7 @@ export function LanguageServersPage() {
const [selectedLanguage, setSelectedLanguage] = useState<string | null>(null);
const [selectedTool, setSelectedTool] = useState<string | null>(null);
const [adding, setAdding] = useState(false);
const list = useRef<HTMLUListElement>(null);
const known = useLanguageChoices();
const staged = form.useValue("languageServers") as Record<string, ServerEntry> | undefined;
const servers = useMemo(() => staged ?? {}, [staged]);
@@ -690,6 +691,29 @@ export function LanguageServersPage() {
setSelectedTool(null);
};
// Opened as `languages.servers#<tool>` (the status bar's Language Servers popup): that tool's
// language and details.
const { focus, consume } = useSettingsPageFocus();
useEffect(() => {
if (!focus) return;
const frame = requestAnimationFrame(() => {
setNeedsSetup(false);
setQuery("");
setSelectedLanguage(null);
setSelectedTool(focus);
consume();
});
return () => cancelAnimationFrame(frame);
}, [focus, consume]);
const selectedName = selected?.name;
useEffect(() => {
if (!selectedName) return;
list.current?.querySelector<HTMLElement>(`[data-language="${CSS.escape(selectedName)}"]`)?.scrollIntoView?.({
block: "nearest",
});
}, [selectedName]);
const onListKey = (e: KeyboardEvent<HTMLUListElement>) => {
if (e.key !== "ArrowDown" && e.key !== "ArrowUp") return;
e.preventDefault();
@@ -752,7 +776,7 @@ export function LanguageServersPage() {
placeholder="Language or tool"
aria-label="Filter languages"
/>
<ul className={styles.list} aria-label={tx("Languages")} onKeyDown={onListKey}>
<ul ref={list} className={styles.list} aria-label={tx("Languages")} onKeyDown={onListKey}>
{shown.map((l) => (
<li key={l.name} className={clsx(styles.row, l === selected && styles.rowSelected)}>
<button
+20 -1
Переглянути файл
@@ -2,7 +2,11 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { act, render, screen, waitFor, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { emitLocalIdeEvent } from "@/platform/ipc";
import { provideNotificationService, type NotificationService } from "@/workbench/contributions";
import {
provideNotificationService,
SettingsPageFocusContext,
type NotificationService,
} from "@/workbench/contributions";
import { useTasks } from "@/workbench/tasks";
import { MemoryToolsBackend, sampleTools, setToolsBackend } from "../backend";
import { cancelInstall, installTool, refreshTools, uninstallTool, useTools } from "../store";
@@ -450,6 +454,21 @@ describe("LanguageServersPage", () => {
expect(within(screen.getByLabelText("ty (Python) details")).queryByRole("radio")).toBeNull();
});
it("opens on the tool it was asked to show (languages.servers#<tool>)", async () => {
const consume = vi.fn();
render(
<SettingsPageFocusContext.Provider value={{ focus: "pyrefly", consume }}>
<TestSettingsForm>
<LanguageServersPage />
</TestSettingsForm>
</SettingsPageFocusContext.Provider>,
);
await waitFor(() => expect(toolItem("pyrefly")).toHaveAttribute("aria-current", "true"));
expect(language("Python")).toHaveAttribute("aria-current", "true");
expect(screen.getByLabelText("Python tools")).toContainElement(toolItem("pyrefly"));
expect(consume).toHaveBeenCalled();
});
it("jumps to a missing tool from the language's banner", async () => {
const user = userEvent.setup();
renderPage();
+6 -2
Переглянути файл
@@ -2,7 +2,7 @@
* Tools installer: Settings › Languages & Frameworks › Language Servers, plus
* install prompts for missing language servers.
*
* Actions: `tools.languageServers` (open the page), `tools.install` (arg: tool name),
* Actions: `tools.languageServers` (open the page; arg: a tool name to show), `tools.install` (arg: tool name),
* `java.downloadJdk` (arg: `DownloadJdkArgs`).
*/
import { executeAction, registerActions } from "@/platform/actions";
@@ -42,7 +42,11 @@ export function activate(): () => void {
category: "Tools",
icon: "package",
keywords: ["lsp", "install", "debugger", "adapter"],
run: () => void executeAction("file.settings", SETTINGS_PAGE_ID),
run: ({ arg }) =>
void executeAction(
"file.settings",
typeof arg === "string" ? `${SETTINGS_PAGE_ID}#${arg}` : SETTINGS_PAGE_ID,
),
},
{
id: "tools.install",
+2 -2
Переглянути файл
@@ -357,8 +357,8 @@ export function nodeMenu(
},
{ kind: "separator" as const },
]),
// Under the modal interface the node itself, like double-click, in the front window.
vcsDiffInFront() && opts?.roots && first
// The node itself, like double-click: under Staged or Unstaged its side of the index.
opts?.roots && first
? {
label: "Show Diff",
icon: "diff",
+14 -1
Переглянути файл
@@ -23,6 +23,9 @@ const isLabel = (e: HistoryEntry) => e.kind === "label";
const time = (e: HistoryEntry) => e.timestampMs ?? 0;
/** Per file, the newest snapshot recorded before `at` (the state at a label). */
/** The backend's label of the snapshot taken when a file is deleted (`ide-workspace::history::DELETED`). */
const DELETED = "Deleted";
export function snapshotsBefore(entries: readonly HistoryEntry[], at: number): Map<string, HistoryEntry> {
const out = new Map<string, HistoryEntry>();
for (const e of entries) {
@@ -113,7 +116,17 @@ export function LocalHistoryEditor({ input }: { input: EditorInput }) {
);
return;
}
const targets = view.folder ? [...(atLabel?.values() ?? [])] : fileAtLabel ? [fileAtLabel] : [];
// A file whose last revision before the label is its deletion was absent then: nothing to restore.
const recorded = view.folder ? [...(atLabel?.values() ?? [])] : fileAtLabel ? [fileAtLabel] : [];
const targets = recorded.filter((e) => e.label !== DELETED);
if (!view.folder && fileAtLabel?.label === DELETED) {
notifications().notify({
level: "info",
title: tx`${baseName(path)} did not exist at label '${current.label}'`,
key: "localHistory.revert",
});
return;
}
if (!targets.length) {
notifications().notify({
level: "info",
+6 -2
Переглянути файл
@@ -294,10 +294,14 @@ describe("Changes tree diffs follow the commit interface setting (#1863)", () =>
expect(openFile).not.toHaveBeenCalled();
});
it("keeps the Show Diff action item with the non-modal interface", () => {
// The row's own diff (under Staged or Unstaged, its side of the index), in an editor tab.
it("opens the node's diff in an editor tab with the non-modal interface", async () => {
modal(false);
const menu = nodeMenu([node], ["/p"], { roots: [node] });
expect(menu).toContainEqual({ kind: "action", action: "vcs.showDiff", arg: "/p/src/a.ts" });
const show = menu.find((m) => m.kind !== "separator" && "label" in m && m.label === "Show Diff");
(show as { run: () => void }).run();
await vi.waitFor(() => expect(openInput).toHaveBeenCalledTimes(1));
expect(openDiffDialog).not.toHaveBeenCalled();
});
});
+5 -6
Переглянути файл
@@ -95,15 +95,14 @@ describe("Local History", () => {
expect(list).toHaveTextContent("src/gone.ts");
expect(screen.getByText(/Label 'Before Git checkout' · 2 files recorded before it/)).toBeInTheDocument();
// Revert at the label restores every file's last revision before it.
// Revert at the label restores every file's last revision before it; a file
// deleted before the label was absent then and stays absent.
fireEvent.click(screen.getByRole("button", { name: "Revert" }));
const confirm = await screen.findByRole("dialog", { name: "Revert" });
expect(confirm).toHaveTextContent("Revert 1 files under src to label 'Before Git checkout'?");
fireEvent.click(within(confirm).getByRole("button", { name: "Revert" }));
await waitFor(() => expect(historyRestore).toHaveBeenCalledTimes(2));
expect(historyRestore.mock.calls.map((c) => c.join(" ")).sort()).toEqual([
`/p/src/a.ts ${id("e")}`,
`/p/src/gone.ts ${id("d")}`,
]);
await waitFor(() => expect(historyRestore).toHaveBeenCalledTimes(1));
expect(historyRestore).toHaveBeenCalledWith("/p/src/a.ts", id("e"));
// A deleted file's row offers Restore.
fireEvent.click(within(list).getAllByRole("option")[1]!);
+32
Переглянути файл
@@ -0,0 +1,32 @@
import { afterEach, beforeEach, expect, it, vi } from "vitest";
import type { BranchInfo } from "@/bindings";
import { installOperationNoticeExpiry } from "../operations";
import { useVcs } from "../store";
const { expire } = vi.hoisted(() => ({ expire: vi.fn() }));
vi.mock("@/workbench/contributions", async (original) => ({
...(await original<typeof import("@/workbench/contributions")>()),
notifications: () => ({ notify: vi.fn(), expire }),
}));
const branch = (operation: string | null) => ({ head: "main", operation }) as unknown as BranchInfo;
let dispose: () => void;
beforeEach(() => {
expire.mockClear();
useVcs.setState({ branch: branch("merge") });
dispose = installOperationNoticeExpiry();
});
afterEach(() => dispose());
it("expires the conflict notice once the merge it offers to commit or abort is over", () => {
useVcs.setState({ branch: branch("merge") });
expect(expire).not.toHaveBeenCalled();
useVcs.setState({ branch: branch(null) });
expect(expire).toHaveBeenCalledWith("vcs.conflicts");
});
it("keeps it while an operation is still in progress", () => {
useVcs.setState({ branch: branch("rebase") });
expect(expire).not.toHaveBeenCalled();
});
+24
Переглянути файл
@@ -18,6 +18,7 @@ import { useChangelists } from "../changelists";
import { useCommit } from "../commitStore";
import { inclusionChecks, isCommitAll, stagingChecks } from "../staging";
import { useVcs } from "../store";
import { provideEditorService } from "@/workbench/contributions";
const file = (rel: string, staged: FileStatus["staged"], unstaged: FileStatus["unstaged"]): FileStatus => ({
path: `/p/${rel}`,
@@ -130,6 +131,29 @@ describe("staging operations of the tree's nodes", () => {
]).toEqual([true, false]);
});
it("shows a row's side of the index from Show Diff: HEAD ↔ Index under Staged, Index ↔ working copy under Unstaged", async () => {
useSettings(true);
const openInput = vi.fn(async () => undefined);
provideEditorService({ openInput } as never);
const show = (node: (typeof roots)[number]) => {
const menu = nodeMenu([node], [], { roots });
(menu.find((m) => "label" in m && m.label === "Show Diff") as { run: () => void }).run();
};
const sides = () => {
const data = (openInput.mock.calls.at(-1) as unknown as [{ data: { left: unknown; right: unknown } }])[0].data;
return [data.left, data.right];
};
show(group("staged").children!.find((n) => n.label === "Partial.kt")!);
await vi.waitFor(() => expect(openInput).toHaveBeenCalledTimes(1));
expect(sides()).toEqual([
{ type: "rev", rev: "HEAD" },
{ type: "rev", rev: ":0", label: "Index" },
]);
show(group("unstaged").children!.find((n) => n.label === "Partial.kt")!);
await vi.waitFor(() => expect(openInput).toHaveBeenCalledTimes(2));
expect(sides()).toEqual([{ type: "rev", rev: ":0", label: "Index" }, { type: "worktree" }]);
});
it("has no Commit File…: a commit takes the whole index", () => {
useSettings(true);
const labels = (items: MenuItem[]) => items.map((i) => ("label" in i ? i.label : null));
+10 -5
Переглянути файл
@@ -60,6 +60,7 @@ import {
showWorktrees,
} from "./gitMenuDialogs";
import { currentRepo, refreshNow, repoName, repoOf, statusOf, useVcs } from "./store";
import { stagingAreaOn } from "./staging";
import { showSyncCommitsForCurrent } from "./SyncCommitsPopup";
import { tx } from "@/platform/i18n";
@@ -433,21 +434,24 @@ export function registerVcsActions(): () => void {
}
if (await showDirectoryWorkingDiff(paths)) return;
const state = useVcs.getState();
// The tree the Commit tool window shows: with the staging area, Staged / Unstaged and no lists.
const staging = stagingAreaOn();
const tree = buildChangeTree(
state.status,
state.root ?? "",
useCommit.getState().groupByDir,
useChangelists.getState().state,
staging ? undefined : useChangelists.getState().state,
state.roots,
useCommit.getState().groupByStaging,
useCommit.getState().groupByStaging || staging,
undefined,
useCommit.getState().groupByRepo,
useCommit.getState().showUnversionedSeparately,
);
// The selected rows while the tree has focus: a file under Staged or Unstaged diffs that side.
const targets = showDiffTargets(tree, paths, !argPaths(arg)?.length && commitWindowFocused());
// The modal interface has one front diff window (#1863): a file with its group
// as the F7 chain, or several selected files as the chain.
if (isModalCommit()) {
const targets = showDiffTargets(tree, paths, !argPaths(arg)?.length && commitWindowFocused());
const [first] = targets;
const data =
targets.length > 1
@@ -461,8 +465,9 @@ export function registerVcsActions(): () => void {
await openVcsDiff({ ...data, line });
return;
}
for (const path of paths.slice(0, 5)) {
await openDiff({ ...groupDiffData(tree, path), line }, { preview: paths.length === 1 });
for (const target of targets.slice(0, 5)) {
const data = typeof target === "string" ? groupDiffData(tree, target) : changeNodeDiffData(tree, target);
await openDiff({ ...data, line }, { preview: targets.length === 1 });
}
},
},
+2 -1
Переглянути файл
@@ -20,7 +20,7 @@ import { registerVcsActions } from "./actions";
import { installChangelists } from "./changelists";
import { registerHistoryActions, trackOperationContext } from "./historyActions";
import { registerLogPaneActions } from "./logPaneActions";
import { controlLabel, controlOperation, inProgress } from "./operations";
import { controlLabel, controlOperation, inProgress, installOperationNoticeExpiry } from "./operations";
import { annotationsShown, blameSlot } from "./blame";
import { activateRevisionAnnotations } from "./annotateRevisionProvider";
import { inlineBlame } from "./inlineBlame";
@@ -195,6 +195,7 @@ export function activate(): () => void {
useCommit.setState({ signOff: workflowSettings().vcs.git.signOff });
const disposers = [
installVcsStore(),
installOperationNoticeExpiry(),
installRootSync(),
installGitLog(),
installDiagnosticsTracking(),
+11
Переглянути файл
@@ -56,6 +56,17 @@ export function inProgress(op: string | null | undefined = useVcs.getState().bra
return op === "rebase" || op === "merge" || op === "cherry-pick" || op === "revert" || op === "am" ? op : null;
}
/**
* Expires the conflict notices (key `vcs.conflicts`: Merge conflicts, All conflicts resolved) once
* the merge / rebase / cherry-pick they offer to continue or abort is over, however it ended.
*/
export function installOperationNoticeExpiry(): () => void {
return useVcs.subscribe((s, prev) => {
if (inProgress(prev.branch?.operation) && !inProgress(s.branch?.operation))
notifications().expire?.("vcs.conflicts");
});
}
/** "Rebasing main", "Merging", "Cherry-picking"… for the branch widget and banner. */
export function operationTitle(op: InProgress, head: string | null): string {
if (!head)
+23 -1
Переглянути файл
@@ -7,7 +7,7 @@ import { _addEditor, _removeEditor, editorContributions, type EditorDocContext }
import { findExtension, findNext, findPrevious, makeQuery, setFindOpen, type FindOptions } from "@/editor/core/cm/find";
import { fontZoom } from "@/editor/core/cm/prefs";
import { seedFind, useFindOptions, useFindSessions, type FindTarget } from "@/editor/core/view/FindBar";
import { FIND_CURRENT_HIGHLIGHT, FIND_HIGHLIGHT, SELECTION_MATCH_HIGHLIGHT } from "./highlight";
import { FIND_CURRENT_HIGHLIGHT, FIND_HIGHLIGHT, SELECTION_MATCH_HIGHLIGHT, previewSelectionOf } from "./highlight";
import { registerMarkdownLiveSource, useLiveMarkdown } from "./live";
import { MarkdownEditor } from "./MarkdownEditor";
import { useMarkdownModes } from "./modes";
@@ -306,3 +306,25 @@ describe("Markdown preview search & selection highlights", () => {
expect(view.state.sliceDoc(view.state.selection.main.from, view.state.selection.main.to)).toBe("second");
});
});
describe("a word selected in the preview", () => {
it("drops the space a Windows double-click adds after the word", () => {
const root = document.createElement("div");
root.innerHTML = "<p>Manage <strong>Order</strong> items</p>";
document.body.append(root);
try {
const strong = root.querySelector("strong")!.firstChild!;
const after = root.querySelector("strong")!.nextSibling!;
const range = document.createRange();
range.setStart(strong, 0);
range.setEnd(after, 1);
const sel = window.getSelection()!;
sel.removeAllRanges();
sel.addRange(range);
expect(previewSelectionOf(root)?.text).toBe("Order");
expect(sel.toString()).toBe("Order");
} finally {
root.remove();
}
});
});
+17 -2
Переглянути файл
@@ -276,9 +276,24 @@ export function previewSelectionOf(root: HTMLElement): { text: string; range: Ra
if (typeof window === "undefined") return null;
const sel = window.getSelection();
if (!sel || sel.isCollapsed || sel.rangeCount !== 1) return null;
const range = sel.getRangeAt(0);
let range = sel.getRangeAt(0);
if (!root.contains(range.commonAncestorContainer)) return null;
const text = sel.toString();
let text = sel.toString();
// Double-clicking a word on Windows selects the space after it too; the word is what was meant.
const trailing = /^\S+(\s+)$/.exec(text)?.[1];
if (trailing) {
text = text.slice(0, -trailing.length);
const end = range.endContainer;
if (end.nodeType === Node.TEXT_NODE && range.endOffset >= trailing.length) {
const trimmed = range.cloneRange();
trimmed.setEnd(end, range.endOffset - trailing.length);
if (trimmed.toString() === text) {
sel.removeAllRanges();
sel.addRange(trimmed);
range = trimmed;
}
}
}
if (text.length < MIN_SELECTION_LENGTH || text.length > MAX_SELECTION_LENGTH || text.includes("\n") || !text.trim())
return null;
return { text, range: range.cloneRange() };
+9 -4
Переглянути файл
@@ -5,10 +5,11 @@
*/
import { useEffect, useRef, useState, type ReactNode } from "react";
import clsx from "clsx";
import { useEditorRegistry } from "@/editor/api";
import { onIdeEvent } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { FloatingToolbar, IconButton } from "@/ui";
import { browserIcon, openInBrowser, useBrowsers, useWebPreview, webUrl } from "./browsers";
import { browserIcon, isWebResource, openInBrowser, useBrowsers, useWebPreview, webUrl } from "./browsers";
import styles from "./Web.module.css";
import { tx } from "@/platform/i18n";
@@ -68,19 +69,23 @@ function WebPreview({ path }: { path: string }) {
};
}, [path]);
// Saved edits anywhere in the project (scripts, styles) reload the page.
// Saved edits to the page or the project's web resources (scripts, styles, images) reload it;
// other files (notes, sources the page doesn't load) leave its state alone.
useEffect(() => {
const scope = root ?? path.slice(0, path.lastIndexOf("/"));
const affects = (p: string) => p === path || ((p.startsWith(scope + "/") || p === scope) && isWebResource(p));
let timer: ReturnType<typeof setTimeout> | undefined;
const reload = () => {
clearTimeout(timer);
timer = setTimeout(() => setSeq((n) => n + 1), RELOAD_DELAY);
};
const offFs = onIdeEvent("fsChanged", (e) => {
if ([...e.created, ...e.modified, ...e.removed].some((p) => p === scope || p.startsWith(scope + "/"))) reload();
if ([...e.created, ...e.modified, ...e.removed].some(affects)) reload();
});
const offDirty = onIdeEvent("docDirty", (e) => {
if (!e.dirty) reload();
if (e.dirty) return;
const saved = [...useEditorRegistry.getState().editors].find((ed) => ed.ctx.doc === e.doc)?.ctx.path;
if (!saved || affects(saved)) reload();
});
return () => {
clearTimeout(timer);
+10 -1
Переглянути файл
@@ -2,7 +2,7 @@ import { afterEach, describe, expect, it } from "vitest";
import type { ProjectInfo, Settings } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { textEditorWrapperFor, useTextEditorWrappers } from "@/workbench/contributions";
import { isHtmlPath, isWebPath } from "./browsers";
import { isHtmlPath, isWebPath, isWebResource } from "./browsers";
import { activate } from "./index";
const types = (patterns: string[], removedPatterns: string[] = []) => ({ patterns, removedPatterns, hashbangs: [] });
@@ -69,3 +69,12 @@ describe("HTML files follow File Types", () => {
}
});
});
describe("web resources", () => {
it("are what a page loads, so the built-in preview reloads for them only", () => {
for (const path of ["/p/index.html", "/p/app.css", "/p/main.js", "/p/data.json", "/p/logo.svg", "/p/a.woff2"])
expect(isWebResource(path), path).toBe(true);
for (const path of ["/p/notes.txt", "/p/README.md", "/p/src/Main.java"])
expect(isWebResource(path), path).toBe(false);
});
});
+9
Переглянути файл
@@ -59,3 +59,12 @@ export async function openInBrowser(path: string, browser: string | null = null)
});
}
}
/** Files a page can load besides markup: styles, scripts, data, images, fonts, media. */
const WEB_RESOURCE =
/\.(css|m?js|cjs|jsx|tsx?|json|map|svg|png|jpe?g|gif|webp|avif|ico|bmp|woff2?|ttf|otf|eot|wasm|mp3|mp4|webm|ogg|wav)$/i;
/** A change to it can change what the built-in preview shows (it reloads for these only). */
export function isWebResource(path: string): boolean {
return isHtmlPath(path) || WEB_RESOURCE.test(path);
}
+56
Переглянути файл
@@ -0,0 +1,56 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { act, cleanup, render } from "@testing-library/react";
type Handler = (e: unknown) => void;
const handlers = new Map<string, Handler[]>();
vi.mock("@/platform/ipc", async (original) => ({
...(await original<typeof import("@/platform/ipc")>()),
onIdeEvent: (kind: string, h: Handler) => {
handlers.set(kind, [...(handlers.get(kind) ?? []), h]);
return () =>
handlers.set(
kind,
(handlers.get(kind) ?? []).filter((x) => x !== h),
);
},
}));
vi.mock("./browsers", async (original) => ({
...(await original<typeof import("./browsers")>()),
webUrl: async () => "http://127.0.0.1/p/page.html",
}));
const { WebEditor } = await import("./WebEditor");
const { useWebPreview } = await import("./browsers");
const { useProject } = await import("@/platform/project");
const emit = (kind: string, e: unknown) => act(() => handlers.get(kind)?.forEach((h) => h(e)));
const fsChanged = (modified: string[]) => emit("fsChanged", { created: [], modified, removed: [] });
describe("the built-in HTML preview", () => {
afterEach(cleanup);
it("reloads for the page and its web resources, not for unrelated files", async () => {
vi.useFakeTimers();
try {
useProject.setState({ project: { root: "/p" } as never });
useWebPreview.setState({ "/p/page.html": true });
const { container } = render(
<WebEditor path="/p/page.html" tabId="t">
<div />
</WebEditor>,
);
await act(async () => {});
const frame = () => container.querySelector("iframe");
const first = frame();
expect(first).toBeTruthy();
fsChanged(["/p/notes.txt", "/p/README.md"]);
act(() => vi.advanceTimersByTime(1000));
expect(frame()).toBe(first);
fsChanged(["/p/style.css"]);
act(() => vi.advanceTimersByTime(1000));
expect(frame()).not.toBe(first);
} finally {
vi.useRealTimers();
}
});
});
+5 -1
Переглянути файл
@@ -274,7 +274,11 @@ export function RecentList({ exclude, compact, autoFocus, onOpened, className, t
open(items[current]);
return;
}
if ((e.key === "Delete" || (e.key === "Backspace" && e.metaKey)) && items[current]) {
// Delete removes the selected project only when it has no text to delete: the caret is at the end
// of the query (⌘⌫: the query is empty). Otherwise it edits the query.
const field = e.currentTarget;
const atEnd = field.selectionStart === field.value.length && field.selectionEnd === field.value.length;
if (((e.key === "Delete" && atEnd) || (e.key === "Backspace" && e.metaKey && !field.value)) && items[current]) {
e.preventDefault();
void askRemoveRecent(items[current]!.project);
return;
+12
Переглянути файл
@@ -137,6 +137,18 @@ describe("Welcome › Projects", () => {
expect(selectedName()).toBe("py-demo");
});
it("leaves Delete to the search text while the caret has text after it", async () => {
await renderWelcome();
const search = screen.getByLabelText("Search projects") as HTMLInputElement;
fireEvent.change(search, { target: { value: "acme" } });
search.setSelectionRange(1, 1);
fireEvent.keyDown(search, { key: "Delete" });
expect(screen.queryByRole("dialog", { name: "Remove Recent Project" })).toBeNull();
search.setSelectionRange(4, 4);
fireEvent.keyDown(search, { key: "Delete" });
expect(screen.getByRole("dialog", { name: "Remove Recent Project" })).toBeTruthy();
});
it("offers Open in New Window in the row menu when the action exists", async () => {
const dispose = registerActions([{ id: "file.openInNewWindow", title: "Open in New Window", run: () => {} }]);
await renderWelcome();
+23 -4
Переглянути файл
@@ -93,14 +93,20 @@ function translated(key: string): string | undefined {
}
/** Catalog key, else the source-text catalog; `undefined` when untranslated. */
function localized(key: string, text: string | undefined): string | undefined {
function localized(key: string | null, text: string | undefined): string | undefined {
if (!text) return undefined;
const v = translated(key) ?? tx(text);
const v = (key === null ? undefined : translated(key)) ?? tx(text);
return v === text ? undefined : v;
}
function localize(action: Action): Action {
const title = action.verbatim ? undefined : localized(`action.${action.id}`, action.title);
/** Titles that follow state ({@link retitleAction}), as written (English). */
const titleOverrides = new Map<string, string>();
function localize(source: Action): Action {
const override = titleOverrides.get(source.id);
const action = override ? { ...source, title: override } : source;
// An override is text, not the id's catalog entry (which names the registered title).
const title = action.verbatim ? undefined : localized(override ? null : `action.${action.id}`, action.title);
const description = localized(`action.${action.id}.description`, action.description);
const category = localized(`action.category.${action.category}`, action.category);
if (!title && !description && !category) return action;
@@ -118,6 +124,19 @@ useI18n.subscribe((s, prev) => {
useActions.setState({ actions: new Map([...sources].map(([id, a]) => [id, localize(a)])) });
});
/**
* Shows action `id` as `title` (English, translated through the text catalog) while its
* state calls for it, e.g. Hide All Tool Windows as "Restore Tool Windows"; `undefined`
* returns to the registered title.
*/
export function retitleAction(id: string, title: string | undefined) {
if (titleOverrides.get(id) === title) return;
if (title) titleOverrides.set(id, title);
else titleOverrides.delete(id);
const source = sources.get(id);
if (source) useActions.setState((s) => ({ actions: new Map(s.actions).set(id, localize(source)) }));
}
/** Adds `action` to the written sources; returns a disposer that removes it. */
function addSource(action: Action): () => void {
sources.set(action.id, action);
+1 -1
Переглянути файл
@@ -331,7 +331,7 @@
"menu.toolwindow.debug": "Debug",
"menu.toolwindow.find": "Find",
"menu.toolwindow.git": "Git",
"menu.toolwindow.hideAll": "Hide All Tool Windows",
"menu.toolwindow.hideAll": "{toolWindows, select, hidden {Restore Tool Windows} other {Hide All Tool Windows}}",
"menu.toolwindow.problems": "Problems",
"menu.toolwindow.project": "Project",
"menu.toolwindow.run": "Run",
+1 -1
Переглянути файл
@@ -269,7 +269,7 @@
"menu.toolwindow.debug": "Depuración",
"menu.toolwindow.find": "Buscar",
"menu.toolwindow.git": "Git",
"menu.toolwindow.hideAll": "Ocultar todas las ventanas de herramientas",
"menu.toolwindow.hideAll": "{toolWindows, select, hidden {Restaurar ventanas de herramientas} other {Ocultar todas las ventanas de herramientas}}",
"menu.toolwindow.problems": "Problemas",
"menu.toolwindow.project": "Proyecto",
"menu.toolwindow.run": "Ejecución",
+1 -1
Переглянути файл
@@ -268,7 +268,7 @@
"menu.toolwindow.debug": "Débogage",
"menu.toolwindow.find": "Recherche",
"menu.toolwindow.git": "Git",
"menu.toolwindow.hideAll": "Masquer toutes les fenêtres d'outils",
"menu.toolwindow.hideAll": "{toolWindows, select, hidden {Restaurer les fenêtres d'outils} other {Masquer toutes les fenêtres d'outils}}",
"menu.toolwindow.problems": "Problèmes",
"menu.toolwindow.project": "Projet",
"menu.toolwindow.run": "Exécution",
+1 -1
Переглянути файл
@@ -275,7 +275,7 @@
"menu.toolwindow.debug": "디버그",
"menu.toolwindow.find": "찾기",
"menu.toolwindow.git": "Git",
"menu.toolwindow.hideAll": "모든 도구 창 숨기기",
"menu.toolwindow.hideAll": "{toolWindows, select, hidden {도구 창 복원} other {모든 도구 창 숨기기}}",
"menu.toolwindow.problems": "문제",
"menu.toolwindow.project": "프로젝트",
"menu.toolwindow.run": "실행",
+1 -1
Переглянути файл
@@ -269,7 +269,7 @@
"menu.toolwindow.debug": "Debug",
"menu.toolwindow.find": "Znajdź",
"menu.toolwindow.git": "Git",
"menu.toolwindow.hideAll": "Ukryj wszystkie okna narzędziowe",
"menu.toolwindow.hideAll": "{toolWindows, select, hidden {Przywróć okna narzędziowe} other {Ukryj wszystkie okna narzędziowe}}",
"menu.toolwindow.problems": "Problemy",
"menu.toolwindow.project": "Projekt",
"menu.toolwindow.run": "Uruchom",
+1 -1
Переглянути файл
@@ -267,7 +267,7 @@
"menu.toolwindow.debug": "Depurar",
"menu.toolwindow.find": "Localizar",
"menu.toolwindow.git": "Git",
"menu.toolwindow.hideAll": "Ocultar todas as janelas de ferramentas",
"menu.toolwindow.hideAll": "{toolWindows, select, hidden {Restaurar janelas de ferramentas} other {Ocultar todas as janelas de ferramentas}}",
"menu.toolwindow.problems": "Problemas",
"menu.toolwindow.project": "Projeto",
"menu.toolwindow.run": "Executar",
+10 -1
Переглянути файл
@@ -2478,5 +2478,14 @@
"Alignment": "Alignment",
"Align key-value pairs": "Align key-value pairs",
"Align consecutive assignments": "Align consecutive assignments",
"Lines up => in multi-line arrays and = in consecutive assignments after the language server or PHP-CS-Fixer formats the file; for a selection, only its lines.": "Lines up => in multi-line arrays and = in consecutive assignments after the language server or PHP-CS-Fixer formats the file; for a selection, only its lines."
"Lines up => in multi-line arrays and = in consecutive assignments after the language server or PHP-CS-Fixer formats the file; for a selection, only its lines.": "Lines up => in multi-line arrays and = in consecutive assignments after the language server or PHP-CS-Fixer formats the file; for a selection, only its lines.",
"Are you sure you want to delete {name}?": "Are you sure you want to delete {name}?",
"Every project inside a trusted location is trusted without asking, unless it is a restricted project.": "Every project inside a trusted location is trusted without asking, unless it is a restricted project.",
"Restricted projects": "Restricted projects",
"These projects open in Restricted Mode, even inside a trusted location.": "These projects open in Restricted Mode, even inside a trusted location.",
"Trust": "Trust",
"{name} is hidden because {title} is off": "{name} is hidden because {title} is off",
"{name} did not exist at label '{label}'": "{name} did not exist at label '{label}'",
"Restore Tool Windows": "Restore Tool Windows",
"Configure {name}…": "Configure {name}…"
}
+10 -2
Переглянути файл
@@ -3793,7 +3793,6 @@
"(empty line)": "(空行)",
"Name cannot be empty": "名称不能为空",
"Every scope needs a name": "每个范围都需要名称",
"Every project inside a trusted location is trusted without asking.": "受信任的位置内的每个项目都会被信任,不再询问。",
"Scopes": "范围",
"Add Scope": "添加范围",
"Remove Scope": "移除范围",
@@ -8853,5 +8852,14 @@
"Alignment": "对齐",
"Align key-value pairs": "对齐键值对",
"Align consecutive assignments": "对齐连续赋值",
"Lines up => in multi-line arrays and = in consecutive assignments after the language server or PHP-CS-Fixer formats the file; for a selection, only its lines.": "在语言服务器或 PHP-CS-Fixer 格式化文件后,对齐多行数组中的 => 和连续赋值语句中的 =;格式化选区时只对齐选中的行。"
"Lines up => in multi-line arrays and = in consecutive assignments after the language server or PHP-CS-Fixer formats the file; for a selection, only its lines.": "在语言服务器或 PHP-CS-Fixer 格式化文件后,对齐多行数组中的 => 和连续赋值语句中的 =;格式化选区时只对齐选中的行。",
"Are you sure you want to delete {name}?": "确定要删除 {name} 吗?",
"Every project inside a trusted location is trusted without asking, unless it is a restricted project.": "受信任的位置内的每个项目都会被信任,不再询问;受限项目除外。",
"Restricted projects": "受限项目",
"These projects open in Restricted Mode, even inside a trusted location.": "这些项目即使位于受信任的位置内,也以受限模式打开。",
"Trust": "信任",
"{name} is hidden because {title} is off": "{name} 已隐藏,因为“{title}”已关闭",
"{name} did not exist at label '{label}'": "标签“{label}”时 {name} 尚不存在",
"Restore Tool Windows": "恢复工具窗口",
"Configure {name}…": "配置 {name}…"
}
+1 -1
Переглянути файл
@@ -331,7 +331,7 @@
"menu.toolwindow.debug": "调试",
"menu.toolwindow.find": "查找",
"menu.toolwindow.git": "Git",
"menu.toolwindow.hideAll": "隐藏所有工具窗口",
"menu.toolwindow.hideAll": "{toolWindows, select, hidden {恢复工具窗口} other {隐藏所有工具窗口}}",
"menu.toolwindow.problems": "问题",
"menu.toolwindow.project": "项目",
"menu.toolwindow.run": "运行",
+6 -1
Переглянути файл
@@ -8,12 +8,17 @@ import { usePlatform } from "@/platform/platformInfo";
import { Icon, MenuList, Popup, type MenuItem } from "@/ui";
import menuStyles from "@/ui/Menu.module.css";
import { isDistractionFree } from "./distractionFree";
import { toolWindowsRestorable } from "./toolwindows/store";
import styles from "./TitleBar.module.css";
function label(id: string, fallback: string): string {
const key = `menu.${id}`;
if (lookup(key) === undefined) return fallback;
return t(key, { os: usePlatform.getState().os, distractionFree: isDistractionFree() ? "on" : "off" });
return t(key, {
os: usePlatform.getState().os,
distractionFree: isDistractionFree() ? "on" : "off",
toolWindows: toolWindowsRestorable() ? "hidden" : "shown",
});
}
type Submenu = Extract<MenuNode, { kind: "submenu" }>;
+5 -2
Переглянути файл
@@ -1,6 +1,7 @@
import { showBackgroundTasks } from "./StatusBar";
import { executeAction, getAction, registerActions } from "@/platform/actions";
import { isTauri } from "@/platform/ipc";
import { isCancelled, isTauri } from "@/platform/ipc";
import { confirmProjectTrust } from "@/platform/projectTrust";
import { closeProject, confirmLeaveProject, openProject, useProject } from "@/platform/project";
import { runSearchFieldCommand, showContextMenu } from "@/ui";
import { showCustomizeToolbar } from "./MainToolbarDialog";
@@ -32,10 +33,12 @@ export async function openProjectDialog() {
await executeAction("file.openProjectPath", path);
return;
}
if (!(await confirmLeaveProject())) return;
try {
await confirmProjectTrust(path, "local");
if (!(await confirmLeaveProject())) return;
await openProject(path);
} catch (e) {
if (isCancelled(e)) return;
notify({ level: "error", title: "Could not open project", body: e instanceof Error ? e.message : String(e) });
}
}
+17 -2
Переглянути файл
@@ -1,4 +1,4 @@
import { registerAction, registerActions, type Action } from "@/platform/actions";
import { registerAction, registerActions, retitleAction, type Action } from "@/platform/actions";
import { setContext } from "@/platform/context";
import { formatMessage, tx } from "@/platform/i18n";
import { occurrenceNavigator, showStatusInfo, useContributions } from "../contributions";
@@ -27,6 +27,7 @@ import {
lastUsedToolWindow,
resizeActiveToolWindow,
setToolWindowViewMode,
toolWindowsRestorable,
useToolWindowLayout,
toggleMaximizeToolWindow,
viewModeOf,
@@ -213,7 +214,13 @@ export function installToolWindowActions(): () => void {
};
const disposeStatic = registerActions([
{ id: "toolwindow.hideAll", title: "Hide All Tool Windows", category: "Window", run: hideAllToolWindows },
{
id: "toolwindow.hideAll",
title: "Hide All Tool Windows",
category: "Window",
keywords: ["restore tool windows"],
run: hideAllToolWindows,
},
{
id: "toolwindow.jumpToLast",
title: "Jump to Last Tool Window",
@@ -312,9 +319,17 @@ export function installToolWindowActions(): () => void {
})),
]);
// Pressed again with every window hidden, Hide All restores them: its title says so.
const retitleHideAll = () =>
retitleAction("toolwindow.hideAll", toolWindowsRestorable() ? "Restore Tool Windows" : undefined);
retitleHideAll();
const unsubscribeHideAll = useToolWindowLayout.subscribe(retitleHideAll);
return () => {
unsubscribe();
unsubscribeLayouts();
unsubscribeHideAll();
retitleAction("toolwindow.hideAll", undefined);
disposeStatic();
perWindow.forEach((e) => e.dispose());
perWindow.clear();
+15
Переглянути файл
@@ -243,6 +243,21 @@ describe("tool window persistence", () => {
});
describe("tool window actions", () => {
it("titles Hide All Tool Windows 'Restore Tool Windows' while it would restore them", async () => {
const dispose = installToolWindowActions();
try {
showToolWindow("terminal");
expect(getAction("toolwindow.hideAll")?.title).toBe("Hide All Tool Windows");
await executeAction("toolwindow.hideAll");
expect(getAction("toolwindow.hideAll")?.title).toBe("Restore Tool Windows");
await executeAction("toolwindow.hideAll");
expect(isToolWindowVisible("terminal")).toBe(true);
expect(getAction("toolwindow.hideAll")?.title).toBe("Hide All Tool Windows");
} finally {
dispose();
}
});
it("registers toolwindow.<id> and generic actions", async () => {
const dispose = installToolWindowActions();
expect(getAction("toolwindow.terminal")?.title).toBe("Terminal");
+7
Переглянути файл
@@ -557,6 +557,13 @@ export function focusToolWindow(id: string) {
update({ focusRequest: { id, seq: ++focusSeq }, lastActive: id }, false);
}
/** Whether Hide All Tool Windows would now restore the windows it hid (nothing visible, a stash kept). */
export function toolWindowsRestorable(
s: Pick<ToolWindowLayoutState, "visible" | "stashed"> = useToolWindowLayout.getState(),
) {
return !!s.stashed && !SLOTS.some((slot) => s.visible[slot]);
}
/** Hides every visible window; called again with nothing visible, restores them. */
export function hideAllToolWindows() {
const s = useToolWindowLayout.getState();