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

...
Автор SHA1 Повідомлення Дата
l0ng-ai 069e587746 fix(debugger): enable Stop in the Debug tool window for the selected session only
Stop was enabled while any session was live, so a finished session's tab
showed an active Stop that did nothing. It now follows the selected tab like
the other toolbar buttons.
2026-11-20 18:33:20 +08:00
eclix-del 9c12cacbdb fix(database): 自定义 JDBC 源按 URL 方言加引号,修复 Oracle 混合大小写表名 (#4765)
fix(database): quote completions of custom JDBC sources by their URL's dialect

A custom JDBC source has driver "jdbc", so completion quoted only names that aren't plain words. On Oracle (and other case-folding servers) a mixed-case table such as BAS_MeterUnit was inserted bare and folded to BAS_METERUNIT (ORA-00942).

Completion now takes the dialect from the source's URL scheme (jdbc:oracle:thin:@…, jdbc:postgresql://…), using the vendor scheme table Data Source from URL already uses, and quotes table, column and JOIN candidates the way that dialect needs. Unknown schemes keep the previous behaviour.

Co-authored-by: eclix-del <[email protected]>
2026-11-20 18:27:18 +08:00
eclix-del d773621276 fix(database): 补全只遍历数据源选中的 schema,避免 Oracle 大实例下阻塞查询 (#4766)
JDBC completion read the columns of every schema on the server. The JDBC bridge runs one command at a time, so on a large Oracle instance (dozens of system schemas, minutes of metadata) the user's statements queued behind it.

Completion now reads only the schemas the data source's Schemas tab picks, matched the way the database tree matches them (exact names, `*` / `?` patterns); sources that show all schemas behave as before.

Co-authored-by: eclix-del <[email protected]>
2026-11-20 18:25:54 +08:00
akshathayadav378-boopтаakshathayadav378-boop 7ec5080047 fix(database): preserve table horizontal scroll position (#4779)
Database table tabs remember their horizontal scroll offset when the tab is mounted again (more than five kept table tabs, or the table opened in a split pane), alongside the page, sort and filter they already remembered.

The offset lives in a ref and is written straight into the remembered view state, so scrolling sideways doesn't re-render the editor; the grid restores it once on mount, retrying as the columns are measured.

Co-authored-by: akshathayadav378-boop <[email protected]>
2026-11-20 18:21:33 +08:00
akshathayadav378-boopтаakshathayadav378-boop 06d7487913 perf(events): coalesce diagnostics within a frame (#4767)
Diagnostics events are full replacements for one (path, source), but the desktop sink serialized and emitted each one immediately. Repeated diagnostics now collapse to the latest within a 16 ms window, any other event flushes pending diagnostics first so ordering is kept, and the buffer flushes at 4,096 keys instead of dropping. Installed on the global and per-window sinks; part of #3937.

Co-authored-by: akshathayadav378-boop <[email protected]>
2026-11-20 18:13:40 +08:00
zhzhsxтаzhzhsx e676138956 fix(editor): go to implementation falls back to the declaration (#4768)
Go to Implementation on a reference to a symbol with no implementations now navigates to the symbol's declaration instead of stopping on No implementations found, including servers that fail the request rather than answer empty (gopls). On the declaration itself it still reports nothing found.

Co-authored-by: zhzhsx <[email protected]>
2026-11-20 18:02:00 +08:00
Muuтаmuutot 1a1ea14b9c fix(vcs): allow Add to .gitignore for attached projects' repositories (#4751)
In a window with an attached project, Add to .gitignore / .git/info/exclude on an untracked file of the attached repository failed with Ignore selection is outside the project: the guard checked the project folder only. It now also accepts any path in one of the window's repositories, the set the Changes view lists; paths inside the project folder stay accepted before that set is discovered.

Co-authored-by: muutot <[email protected]>
2026-11-20 17:59:44 +08:00
l0ng-ai 5c0917b849 feat(vcs): ⌘/Ctrl-click a repository in the log filter to see only it (#4774)
Cmd-click (macOS) or Ctrl-click on a repository in the Git Log's Repository filter now shows only that repository; a plain click still adds or removes it, and each row's tooltip says so. Menu items gain an optional modifier-click action and a row tooltip.
2026-11-20 17:55:52 +08:00
l0ng-ai 19f2c0ef5d feat(http-client): Reformat Code formats JSON request bodies (#4771)
Reformat Code in an .http file reported No language server available. The HTTP Client now contributes a formatter that re-indents each request's JSON body, keeping {{variables}} and number literals as written and leaving headers, response handlers, references and file inputs alone.
2026-11-20 17:50:24 +08:00
l0ng-ai 8c696b8fe7 test(e2e): follow the split panes of the Inspections and Plugins settings (#4769)
#4629 and #4636 moved the Inspections and Plugins settings into resizable split panels; the shared settings layout specs now select the details section and profile label through the new structure.
2026-11-20 17:44:36 +08:00
l0ng-ai deecdbbf4f test(e2e): fix the Python highlighting and Recent Locations specs (#4752)
pythonHighlight: the fixture's Darcula-based scheme doesn't name NOT_USED_ELEMENT_ATTRIBUTES, which since #4737 comes from Darcula (#72737A). recentNavigationLayout: the snippet height check allows a fractional pixel (89.94px vs 90px).
2026-11-20 17:29:09 +08:00
Muuтаmuutot 802400c324 fix(editor): keep long blame tooltips inside a scroll container (#4741)
Hovering the inline blame label of a commit with a long message spilled the tooltip over the workbench: it had only a max-width, and the shared editor theme never made the hover host a column flex container, so CodeMirror's height cap near the window edge did not clip it. The blame tooltip now caps its height and scrolls inside, and the base editor theme lets hover sections shrink inside the squeezed host (the rules LSP hovers already had).

Co-authored-by: muutot <[email protected]>
2026-11-20 17:24:40 +08:00
Ziop edc6a522ee fix(search): find a pasted Windows absolute path by its project-relative path (#4739)
On Windows, pasting a plain absolute path such as E:\work\project\pkg\Config.go into Search Everywhere found nothing: backslashes were converted only when the paste had no forward slash, the project-root prefix was compared case-sensitively although drive-letter paths are not, and a \\?\ prefix was kept. The query parser and the index now reduce an absolute path below the project root to its project-relative form (case-insensitively for drive-letter roots), with mixed separators and verbatim prefixes handled.

Co-authored-by: wangpi26 <[email protected]>
2026-11-20 17:14:43 +08:00
Vladislav Kuzmin 0c7a278ca6 fix(database): execute SQL from read-only editor files (#4608)
Running SQL with Cmd+Enter in a read-only SQL file left Results stuck on Executing: the file lock removes the SQL editor's run-state field, so setting up the progress marks threw before execution. The marks are now skipped when the field is absent, and a failure while setting them up still clears the running request.

Co-authored-by: principalwater <[email protected]>
2026-11-20 17:12:51 +08:00
l0ng-ai 8c93136063 feat(remote): Download to… in a remote project's Project view (#4748)
In an SSH project window, the Project view's context menu and the action Download to… copy the selection into a local folder over the window's SSH session (new desktop command remote_download_local), with a cancellable progress task and a failure report. The download loop of Remote Host › Download to… is shared, including its guard against writing outside the chosen folder.
2026-11-20 17:11:40 +08:00
l0ng-ai e20e7b04bc feat(run): Diagnose with Agent on a failed test (#4744)
A failed test's context menu in the test tree gets Diagnose with Agent while the agents feature is active. It appends the failure (test name, source location reference, expected/actual when the framework names them, first 60 output lines) to the agent message typed last and opens it for review.
2026-11-20 16:54:20 +08:00
l0ng-ai f325e8c9d6 Align Inspection Results panes and actions (#4734)
Inspection Results aligns its result tree, detail pane and action toolbar: the panes keep usable widths and the actions stay grouped and labelled for assistive technology.
2026-11-20 16:41:33 +08:00
persicaTaoтаpersicaTao 84edcc03a4 fix(run): pass the tool search path to script launches (#4732)
On Windows an auto-detected npm run start found npm.cmd on the login-shell and user PATH and started it by full path, but the script it ran only inherited the IDE process PATH, so 'node' was not recognized. A run now passes the same search path it used to resolve its program to the child, unless the configuration sets PATH itself or turns off the system environment.

Co-authored-by: persicaTao <[email protected]>
2026-11-20 16:40:37 +08:00
youngledoтаyoungledo 4146ca2041 fix(app): list open projects in the macOS Window menu (#4736)
On macOS the Window menu did not list open project windows: the submenu was registered as the application's windows menu while the menu was still being built, before set_menu attached it to NSApp, so muda skipped it. It is now registered after the menu bar is installed, and AppKit lists each window by its title (project or workspace name, plus the current file).

Co-authored-by: youngledo <[email protected]>
2026-11-20 16:39:02 +08:00
l0ng-ai 105c37360b fix(editor): give Darcula-based imported schemes Darcula's colours (#4737)
An exported IntelliJ scheme lists only what differs from its parent. One based on Darcula that left TEXT out got Islands Dark's editor background (#191a1c) instead of Darcula's #2b2b2b, and likewise for every attribute it left out. Attributes a Darcula-based scheme doesn't name now come from Darcula, in both Color Scheme import and IntelliJ theme plugin import; exports write an empty value for an attribute they have nothing for so the parent can't show through on re-import; and an imported scheme's gutter follows its editor background unless it sets its own.
2026-11-20 16:26:23 +08:00
74 змінених файлів з 2466 додано та 179 видалено

No files matched your search

+7 -1
Переглянути файл
@@ -602,7 +602,13 @@ impl DbManager {
pub(crate) async fn jdbc_completion(&self, id: &str, pool: &JdbcPool) -> IdeResult<crate::CompletionModel> {
let mut tables = vec![];
let mut column_count = 0;
let schemas = self.schemas(id).await?;
// Read the schemas the source's Schemas tab picks, like the database tree does. It also
// keeps large instances usable: an Oracle server exposes dozens of system schemas, and
// dumping the columns of all of them takes minutes, during which the bridge (a single
// Java process that runs one command at a time) executes none of the user's statements.
let introspection = self.source(id)?.introspection;
let schemas: Vec<String> =
self.schemas(id).await?.into_iter().filter(|s| introspection.shows_schema(s)).collect();
for schema in &schemas {
// Columns of the whole namespace in one call; a driver that refuses it still completes tables.
let mut columns = if column_count < crate::MAX_META_ROWS {
+59
Переглянути файл
@@ -124,6 +124,45 @@ impl Default for DbIntrospection {
}
}
impl DbIntrospection {
/// Whether the tree shows this schema: every one with `all_schemas`, otherwise it has to
/// match one of the `schemas` patterns. The completion model uses the same test, so it
/// offers exactly the tables the tree lists (and does not read the ones it never shows).
pub fn shows_schema(&self, name: &str) -> bool {
self.all_schemas
|| self.schemas.iter().map(|p| p.trim()).filter(|p| !p.is_empty()).any(|p| schema_matches(p, name))
}
}
/// `*` matches any run of characters, `?` a single one; a pattern without wildcards matches the
/// name as typed (the dialog fills names from the list the server returned, so case is settled).
fn schema_matches(pattern: &str, name: &str) -> bool {
if !pattern.contains('*') && !pattern.contains('?') {
return pattern == name;
}
let p: Vec<char> = pattern.chars().collect();
let n: Vec<char> = name.chars().collect();
let (mut pi, mut ni) = (0, 0);
// Position of the last `*` and how much of the name it has already swallowed.
let mut star: Option<(usize, usize)> = None;
while ni < n.len() {
if pi < p.len() && (p[pi] == '?' || p[pi] == n[ni]) {
pi += 1;
ni += 1;
} else if pi < p.len() && p[pi] == '*' {
star = Some((pi, ni));
pi += 1;
} else if let Some((at, taken)) = star {
pi = at + 1;
ni = taken + 1;
star = Some((at, taken + 1));
} else {
return false;
}
}
p[pi..].iter().all(|&c| c == '*')
}
/// Advanced tab: a driver property. PostgreSQL: run-time parameters (and
/// `application_name`); MySQL: session variables (and `charset`, `collation`);
/// SQLite: pragmas. See [`crate::conn`].
@@ -765,4 +804,24 @@ mod tests {
assert_eq!(r.snowflake().auth, DbSnowflakeAuth::Browser);
assert_eq!(scheme_driver("snowflake"), Some(DbDriver::Snowflake));
}
#[test]
fn introspection_shows_only_the_picked_schemas() {
let mut i = DbIntrospection::default();
assert!(i.shows_schema("SYS"), "the default reads every schema");
i.all_schemas = false;
assert!(!i.shows_schema("SYS"), "nothing picked: the tree lists nothing either");
i.schemas = vec!["XMCB".into(), " APP_* ".into()];
assert!(i.shows_schema("XMCB"));
assert!(i.shows_schema("APP_INFO"));
assert!(!i.shows_schema("APP"), "`*` needs the text that follows it");
assert!(!i.shows_schema("SYS"));
assert!(!i.shows_schema("xmcb"), "patterns match the names the server returned");
i.schemas = vec!["?".into()];
assert!(i.shows_schema("A"));
assert!(!i.shows_schema("AB"));
}
}
+7 -1
Переглянути файл
@@ -633,8 +633,14 @@ pub async fn vcs_add_to_ignore(
host.require_trust(window)?;
let project = host.project(window)?;
blocking(move || {
// The Changes view lists every repository of the window (the project's and the
// attached ones'): a path inside the project folder, or in any of those repositories.
// The folder check stays so a request right after opening, before the repositories
// are discovered, still works.
let repos = project.repos();
for path in &paths {
if path == &project.root || !path.starts_with(&project.root) {
let in_project = path != &project.root && path.starts_with(&project.root);
if !in_project && repos.for_path(path).is_none() {
return Err(ide_core::IdeError::invalid("Ignore selection is outside the project"));
}
}
+73
Переглянути файл
@@ -21,6 +21,7 @@ async fn patches_read_and_write_the_requested_repository() {
git(root, &["init", "-b", "main"]);
git(root, &["config", "user.name", "Test"]);
git(root, &["config", "user.email", "[email protected]"]);
git(root, &["config", "core.autocrlf", "false"]);
std::fs::write(root.join("same.txt"), format!("root {i}\n")).unwrap();
git(root, &["add", "."]);
git(root, &["commit", "-m", "initial"]);
@@ -65,3 +66,75 @@ async fn patches_read_and_write_the_requested_repository() {
assert!(vcs::vcs_apply_patch(&host, "main", Some(base.join("outside")), String::new()).await.is_err());
host.close_project("main");
}
/// The Changes view also lists attached projects' repositories, and their untracked files
/// offer Add to .gitignore / .git/info/exclude: the guard must follow the window's
/// repository set, not the project folder alone.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn add_to_ignore_accepts_the_repositories_of_attached_projects() {
let temp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(temp.path()).unwrap();
let project_root = base.join("project");
let attached_root = base.join("attached");
for root in [&project_root, &attached_root] {
std::fs::create_dir_all(root).unwrap();
git(root, &["init", "-b", "main"]);
git(root, &["config", "user.name", "Test"]);
git(root, &["config", "user.email", "[email protected]"]);
git(root, &["config", "core.autocrlf", "false"]);
std::fs::write(root.join("tracked.txt"), "x\n").unwrap();
git(root, &["add", "."]);
git(root, &["commit", "-m", "initial"]);
}
// Untracked files, one per repository; the attached one is what failed.
let own = project_root.join("own.ignore-me");
let attached = attached_root.join("attached.ignore-me");
std::fs::write(&own, "x").unwrap();
std::fs::write(&attached, "x").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(&project_root, true, false).unwrap();
host.trust.decide(&attached_root, true, false).unwrap();
let project = host.open_project("main", &project_root).unwrap();
ide_host::ops::project::attach_workspace(&host, "main", &attached_root).unwrap();
for _ in 0..500 {
if project.repos().all().len() == 2 {
break;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
assert_eq!(project.repos().all().len(), 2);
vcs::vcs_add_to_ignore(&host, "main", vec![attached.clone()], ide_vcs::IgnoreDestination::Gitignore).await.unwrap();
assert!(
std::fs::read_to_string(attached_root.join(".gitignore")).unwrap().contains("/attached.ignore-me"),
"the attached repository's .gitignore did not receive the rule"
);
vcs::vcs_add_to_ignore(&host, "main", vec![own.clone()], ide_vcs::IgnoreDestination::LocalExclude).await.unwrap();
assert!(
std::fs::read_to_string(project_root.join(".git/info/exclude")).unwrap().contains("/own.ignore-me"),
"the project repository's exclude did not receive the rule"
);
// A repository of an unattached sibling folder stays outside.
let sibling_root = base.join("sibling");
std::fs::create_dir_all(&sibling_root).unwrap();
git(&sibling_root, &["init", "-b", "main"]);
let sibling = sibling_root.join("sibling.ignore-me");
std::fs::write(&sibling, "x").unwrap();
let error =
vcs::vcs_add_to_ignore(&host, "main", vec![sibling], ide_vcs::IgnoreDestination::Gitignore).await.unwrap_err();
assert!(error.message.contains("outside the project"), "{error:?}");
assert!(!sibling_root.join(".gitignore").exists());
host.close_project("main");
}
+4 -4
Переглянути файл
@@ -265,7 +265,7 @@ impl ProjectIndex {
pub fn find_files(&self, query: &str, limit: usize) -> Vec<FileMatch> {
let recent = self.shared.recent.lock().clone();
let d = self.shared.data.read();
matching::find_files(&d, &matching::Recents::new(&recent), query, limit)
matching::find_files(&d, &matching::Recents::new(&recent), query, Some(&self.root), limit)
}
/// All indexed files with this exact basename, for resolving printed source locations.
@@ -301,7 +301,7 @@ impl ProjectIndex {
/// Fuzzy search for folders that hold indexed files; `rel_path` ends in `/`.
pub fn find_dirs(&self, query: &str, limit: usize) -> Vec<FileMatch> {
matching::find_dirs(&self.shared.data.read(), query, limit)
matching::find_dirs(&self.shared.data.read(), query, Some(&self.root), limit)
}
/// Fuzzy symbol search; CamelHump aware (`OCo` → `OrderController`).
@@ -574,11 +574,11 @@ pub mod bench_support {
}
pub fn find_files(&self, query: &str, limit: usize) -> Vec<FileMatch> {
matching::find_files(&self.data, &matching::Recents::new(&self.recent), query, limit)
matching::find_files(&self.data, &matching::Recents::new(&self.recent), query, None, limit)
}
pub fn find_dirs(&self, query: &str, limit: usize) -> Vec<FileMatch> {
matching::find_dirs(&self.data, query, limit)
matching::find_dirs(&self.data, query, None, limit)
}
pub fn find_symbols(&self, query: &str, filter: SymbolFilter, limit: usize) -> Vec<SymbolMatch> {
+56 -8
Переглянути файл
@@ -205,29 +205,67 @@ impl<'a> Recents<'a> {
}
}
/// `Foo.kt:12:3` -> `Foo.kt`; `\` -> `/`; strips leading `./` and `/`.
fn normalize_file_query(q: &str) -> String {
/// `Foo.kt:12:3` -> `Foo.kt`; `\` -> `/`; a pasted absolute path under `root` -> its project-relative
/// form; strips leading `./` and `/`.
fn normalize_file_query(q: &str, root: Option<&Path>) -> String {
let mut q = q.trim().replace('\\', "/");
// `\\?\C:\a` (verbatim) and `\\.\C:\a` name `C:/a`.
if let Some(rest) = verbatim_target(&q) {
q = rest.to_owned();
}
while let Some((head, tail)) = q.rsplit_once(':')
&& !tail.is_empty()
&& tail.bytes().all(|b| b.is_ascii_digit())
{
q = head.to_owned();
}
if let Some(root) = root
&& let Some(rel) = strip_root(&q, root)
{
q = rel;
}
let q = q.trim_start_matches("./").trim_start_matches('/');
q.chars().filter(|c| !c.is_whitespace()).collect()
}
/// Path a `\\?\` / `\\.\` verbatim prefix points at, for a `/`-separated path.
fn verbatim_target(q: &str) -> Option<&str> {
q.strip_prefix("//?/").or_else(|| q.strip_prefix("//./"))
}
/// `q` (already `/`-separated) below `root`, without the separating slash. A drive-letter root
/// compares like Windows, where case does not matter.
fn strip_root(q: &str, root: &Path) -> Option<String> {
let root = root.to_string_lossy().replace('\\', "/");
let root = verbatim_target(&root).unwrap_or(&root);
let root = root.trim_end_matches('/');
let windows = root.as_bytes().get(1) == Some(&b':');
let head = q.get(..root.len())?;
if head != root && !(windows && head.eq_ignore_ascii_case(root)) {
return None;
}
match q.get(root.len()..)? {
"" => Some(String::new()),
tail => tail.strip_prefix('/').map(str::to_owned),
}
}
enum FileQuery {
Name(Needle),
Path { dir: Needle, name: Needle },
}
pub(crate) fn find_files(data: &IndexData, recents: &Recents, query: &str, limit: usize) -> Vec<FileMatch> {
pub(crate) fn find_files(
data: &IndexData,
recents: &Recents,
query: &str,
root: Option<&Path>,
limit: usize,
) -> Vec<FileMatch> {
if limit == 0 {
return Vec::new();
}
let q = normalize_file_query(query);
let q = normalize_file_query(query, root);
if q.is_empty() {
return recents
.paths
@@ -306,8 +344,8 @@ pub(crate) fn find_files(data: &IndexData, recents: &Recents, query: &str, limit
/// Fuzzy folder search over the folders holding indexed files: folder-name matches beat
/// path matches; `/` in the query matches the whole path. `rel_path` ends in `/`.
pub(crate) fn find_dirs(data: &IndexData, query: &str, limit: usize) -> Vec<FileMatch> {
let q = normalize_file_query(query);
pub(crate) fn find_dirs(data: &IndexData, query: &str, root: Option<&Path>, limit: usize) -> Vec<FileMatch> {
let q = normalize_file_query(query, root);
if limit == 0 || q.is_empty() {
return Vec::new();
}
@@ -673,8 +711,18 @@ mod tests {
#[test]
fn normalizes_queries() {
assert_eq!(normalize_file_query(" ./src\\main.rs:12:4 "), "src/main.rs");
assert_eq!(normalize_file_query("/a b"), "ab");
let root = Path::new("E:/work/sample");
assert_eq!(normalize_file_query(" ./src\\main.rs:12:4 ", None), "src/main.rs");
assert_eq!(normalize_file_query("/a b", None), "ab");
// A pasted absolute path names an indexed file (#4079 follow-up).
assert_eq!(normalize_file_query(r"E:\work\sample\pkg\Config.go", Some(root)), "pkg/Config.go");
assert_eq!(normalize_file_query(r"e:/WORK/sample\pkg/Config.go", Some(root)), "pkg/Config.go");
assert_eq!(normalize_file_query(r"\\?\E:\work\sample\src\App.kt", Some(root)), "src/App.kt");
assert_eq!(normalize_file_query(r"E:\work\sample\pkg\Config.go:12:4", Some(root)), "pkg/Config.go");
// Outside the project, and a POSIX root, keep the path as given.
assert_eq!(normalize_file_query(r"E:\elsewhere\x.go", Some(root)), "E:/elsewhere/x.go");
assert_eq!(normalize_file_query("/home/me/Src/a.rs", Some(Path::new("/home/me/src"))), "home/me/Src/a.rs");
assert_eq!(normalize_file_query("/home/me/src/a.rs", Some(Path::new("/home/me/src"))), "a.rs");
assert_eq!(split_symbol_query("Order.save"), (Some("Order"), "save"));
assert_eq!(split_symbol_query("a::b::C::new"), (Some("C"), "new"));
assert_eq!(split_symbol_query("save"), (None, "save"));
+13
Переглянути файл
@@ -190,6 +190,19 @@ fn file_ranking_is_idea_like() {
assert_eq!(shown.to_lowercase(), "uibtn");
}
#[test]
fn a_pasted_absolute_path_finds_the_indexed_file() {
let fx = sample();
let idx = fx.open();
let abs = fx.root.join("src/ui/Button.tsx");
let abs = abs.to_string_lossy().into_owned();
assert_eq!(files(&idx, &abs)[0], "src/ui/Button.tsx");
// A trailing `:line:col`, and a path outside the project that names no file.
assert_eq!(files(&idx, &format!("{abs}:12:4"))[0], "src/ui/Button.tsx");
let outside = fx.root.parent().unwrap().join("elsewhere/Button.tsx");
assert!(files(&idx, &outside.to_string_lossy()).is_empty());
}
#[test]
fn find_dirs_ranks_folder_names() {
let f = sample();
+71 -57
Переглянути файл
@@ -349,64 +349,9 @@ impl RemoteService {
progress: &mut (dyn FnMut(&str, usize, usize) + Send),
) -> IdeResult<TransferReport> {
let fs = self.fs(connection).await?;
let mut report = TransferReport::default();
let mut folders = Vec::new();
let mut jobs = Vec::new();
for remote in remotes {
let Some(top) = download_target(dir, remote, remote) else {
report.skipped += 1;
continue;
};
match fs.stat(remote).await {
Ok(Some(e)) if e.is_dir => {
folders.push(top);
let mut entries = Vec::new();
if let Err(e) = remote_tree(&fs, remote, cancel, &mut entries).await {
report.fail(remote.clone(), e);
}
for entry in entries {
match download_target(dir, remote, &entry.path) {
Some(local) if entry.is_dir => folders.push(local),
Some(local) => jobs.push((entry.path, local)),
None => report.skipped += 1,
}
}
}
Ok(Some(_)) => jobs.push((remote.clone(), top)),
Ok(None) => report.fail(remote.clone(), IdeError::not_found(format!("{remote} does not exist"))),
Err(e) => report.fail(remote.clone(), e),
}
}
let root = tokio::fs::canonicalize(dir).await?;
for folder in &folders {
if !stays_inside(&root, folder).await {
report.fail(folder.display().to_string(), outside(folder));
} else if let Err(e) = tokio::fs::create_dir_all(folder).await {
report.fail(folder.display().to_string(), e.into());
}
}
for (i, (remote, local)) in jobs.iter().enumerate() {
if cancel.is_cancelled() {
break;
}
progress(remote, i, jobs.len());
if !stays_inside(&root, local).await {
report.fail(remote.clone(), outside(local));
continue;
}
if let Some(parent) = local.parent()
&& let Err(e) = tokio::fs::create_dir_all(parent).await
{
report.fail(remote.clone(), e.into());
continue;
}
match fs.download(remote, local).await {
Ok(()) => report.files += 1,
Err(e) => report.fail(remote.clone(), e),
}
}
let r = download_into(&fs, remotes, dir, cancel, progress).await;
fs.close().await;
Ok(report)
r
}
// --- save hook -----------------------------------------------------------------
@@ -656,6 +601,75 @@ fn cache_key(connection: &FsConnection) -> String {
}
/// Files and folders under remote folder `dir` (symlinked folders are not followed).
/// `remotes` (folders recursively) into the local folder `dir`, each under its own name, without
/// the remote path above it; existing files are replaced. Remote Host › Download to…, and the
/// project view's Download to… in a remote project.
pub async fn download_into(
fs: &RemoteFs,
remotes: &[String],
dir: &Path,
cancel: &CancellationToken,
progress: &mut (dyn FnMut(&str, usize, usize) + Send),
) -> IdeResult<TransferReport> {
let mut report = TransferReport::default();
let mut folders = Vec::new();
let mut jobs = Vec::new();
for remote in remotes {
let Some(top) = download_target(dir, remote, remote) else {
report.skipped += 1;
continue;
};
match fs.stat(remote).await {
Ok(Some(e)) if e.is_dir => {
folders.push(top);
let mut entries = Vec::new();
if let Err(e) = remote_tree(fs, remote, cancel, &mut entries).await {
report.fail(remote.clone(), e);
}
for entry in entries {
match download_target(dir, remote, &entry.path) {
Some(local) if entry.is_dir => folders.push(local),
Some(local) => jobs.push((entry.path, local)),
None => report.skipped += 1,
}
}
}
Ok(Some(_)) => jobs.push((remote.clone(), top)),
Ok(None) => report.fail(remote.clone(), IdeError::not_found(format!("{remote} does not exist"))),
Err(e) => report.fail(remote.clone(), e),
}
}
let root = tokio::fs::canonicalize(dir).await?;
for folder in &folders {
if !stays_inside(&root, folder).await {
report.fail(folder.display().to_string(), outside(folder));
} else if let Err(e) = tokio::fs::create_dir_all(folder).await {
report.fail(folder.display().to_string(), e.into());
}
}
for (i, (remote, local)) in jobs.iter().enumerate() {
if cancel.is_cancelled() {
break;
}
progress(remote, i, jobs.len());
if !stays_inside(&root, local).await {
report.fail(remote.clone(), outside(local));
continue;
}
if let Some(parent) = local.parent()
&& let Err(e) = tokio::fs::create_dir_all(parent).await
{
report.fail(remote.clone(), e.into());
continue;
}
match fs.download(remote, local).await {
Ok(()) => report.files += 1,
Err(e) => report.fail(remote.clone(), e),
}
}
Ok(report)
}
async fn remote_tree(
fs: &RemoteFs,
dir: &str,
+48 -1
Переглянути файл
@@ -938,7 +938,18 @@ fn launch_env(root: &Path, config: &RunConfig) -> IdeResult<LaunchEnv> {
vars.insert("PYTHONUNBUFFERED".into(), "1".into());
}
vars.extend(config.env.iter().map(|(k, v)| (k.clone(), v.clone())));
Ok(LaunchEnv { clear: !extras.include_system_env, vars })
let mut env = LaunchEnv { clear: !extras.include_system_env, vars };
// `npm.cmd` is found on the login-shell and Windows user PATH, then started by its
// full path. The script it runs (`node …`) only sees this process's PATH, which
// does not include that directory, so `node` is not recognized.
let cwd = resolve_cwd(root, config.cwd.as_deref());
if !env.clear && !env.vars.keys().any(|k| k.eq_ignore_ascii_case("PATH")) {
let path = crate::wrap::search_path_in(config, &cwd);
if let Some(text) = path.to_str().filter(|s| !s.is_empty()) {
env.vars.insert("PATH".into(), text.to_owned());
}
}
Ok(env)
}
/// What a run in the project at `root` inherits with "Include system environment variables"
@@ -1446,6 +1457,42 @@ mod tests {
assert_eq!(binary.program, script);
}
fn bare_config(env: BTreeMap<String, String>) -> RunConfig {
RunConfig {
id: "c".into(),
name: "c".into(),
kind: "npm".into(),
command: "npm".into(),
args: vec!["run".into(), "start".into()],
cwd: None,
env,
detected: true,
is_test: false,
debug_adapter: None,
allow_parallel: false,
extras: Default::default(),
}
}
#[test]
fn a_run_inherits_the_path_used_to_resolve_its_program() {
let dir = tempfile::tempdir().unwrap();
let config = bare_config(BTreeMap::new());
let env = launch_env(dir.path(), &config).unwrap();
let path = env.vars.get("PATH").expect("child PATH");
let search = crate::wrap::search_path_in(&config, dir.path());
assert_eq!(path, search.to_str().unwrap());
}
#[test]
fn an_explicit_path_override_is_kept() {
let dir = tempfile::tempdir().unwrap();
let config = bare_config(BTreeMap::from([("Path".into(), r"C:\tools".into())]));
let env = launch_env(dir.path(), &config).unwrap();
assert_eq!(env.vars.get("Path").map(String::as_str), Some(r"C:\tools"));
assert_eq!(env.vars.keys().filter(|k| k.eq_ignore_ascii_case("PATH")).count(), 1);
}
#[test]
fn shell_lines_use_cmd_verbatim_on_windows() {
let line = r#"(if not exist "C:\T\openidea-run" mkdir "C:\T\openidea-run") && "C:\Program Files\rustc.exe" -o "C:\T\openidea-run\hi.exe" hi.rs"#;
+1
Переглянути файл
@@ -57,6 +57,7 @@ Language servers that support LSP inline completion show a grey suggestion at th
| **Next Method** / **Previous Method** | `⌃⇧↓` / `⌃⇧↑` | `Alt+Down` / `Alt+Up` |
- **Go to Declaration or Usages** on a declaration shows its usages instead.
- **Go to Implementation(s)** navigates to the symbol's own declaration when it has no implementations, as in IntelliJ IDEA.
- Hold `⌘` / `Ctrl` and hover over a name to see it underlined as a link, with brief information about it.
- Gutter icons mark types and methods that are implemented or overridden (↓) and methods that implement or override another (↑). Click one to go there.
- **Navigate › Test** jumps between a class and its tests by naming convention and offers **Create New Test…** when there is none.
+1
Переглянути файл
@@ -57,6 +57,7 @@ description: "代码补全、导航、查找用法、文档、层次结构与文
| **下一个方法** / **上一个方法** | `⌃⇧↓` / `⌃⇧↑` | `Alt+Down` / `Alt+Up` |
- 在声明本身上执行 **转到声明或用法**,会改为显示它的用法。
- 没有任何实现时,**转到实现** 会跳转到符号自身的声明,与 IntelliJ IDEA 一致。
- 按住 `⌘` / `Ctrl` 把鼠标悬停在名称上,名称会显示为链接,并附带简要信息。
- 装订区域的图标标出被实现或被重写的类型和方法(↓),以及实现或重写了其他方法的方法(↑),单击即可跳转。
- **导航 › 测试** 按命名约定在类和它的测试之间跳转;还没有测试时会提供 **创建新测试…**。
+1 -1
Переглянути файл
@@ -4,7 +4,7 @@ for (const [id, selector] of [
["general", "[class*='radios'] label"],
["notifications", "table tbody td:first-child"],
["keymap", "[class*='presetLabel']"],
["editor.inspections", "[class*='profileRow'] > span:first-child"],
["editor.inspections", "[class*='profileControls'] > span:first-child"],
["vcs.issueNavigation", "[class*='pageBody'] button:not([aria-label])"],
] as const) {
test(`${id} keeps compact labels inside their controls`, async ({ workbench: page }) => {
+89
Переглянути файл
@@ -0,0 +1,89 @@
import { expect, stubDesktop, test } from "./fixtures";
test("inspection results keep source context and actions visible as the dock narrows", async ({ workbench: page }) => {
await page.setViewportSize({ width: 1100, height: 720 });
const relative = "modules/settlement/reconciliation/QuarterlySettlementReconciliationCoordinator.ts";
const path = `/dev/acme-api/${relative}`;
const title = "The estimated settlement total ignores the currency conversion for pending merchant payments";
const detail = "Check the calculation before saving the reconciliation report.";
await page.evaluate(async (path) => {
const backend = "/src/editor/core/backend.ts";
(await import(/* @vite-ignore */ backend))
.docBackend()
.files.set(path, "const amount = 100;\nconst exchangeRate = 3;\nconst estimate = amount;\n");
const service = "/src/workbench/contributions.ts";
await (await import(/* @vite-ignore */ service)).editorService().openFile(path);
}, path);
await expect(page.locator(".cm-content")).toContainText("estimate");
await stubDesktop(page);
await page.evaluate(
async ({ path, relative, title, detail }) => {
window.__ipc.handlers.inspect_code = ({ onEvent }) => {
window.__ipc.send(onEvent, { type: "started", total: 1 });
window.__ipc.send(onEvent, {
type: "file",
done: 1,
file: {
path,
relPath: relative,
diagnostics: [
{
range: { start: { line: 2, col: 6 }, end: { line: 2, col: 14 } },
severity: "warning",
message: `${title}\n${detail}`,
source: "lint",
code: "pending-currency-conversion",
},
],
},
});
window.__ipc.send(onEvent, {
type: "done",
summary: { files: 1, problems: 1, skipped: 0, failed: 0, cancelled: false, elapsedMs: 30 },
});
};
const actions = "/src/platform/actions.ts";
await (await import(/* @vite-ignore */ actions)).executeAction("analyze.inspectFile");
},
{ path, relative, title, detail },
);
const tree = page.getByRole("tree", { name: "Inspection results" });
const problem = tree.getByRole("treeitem").filter({ hasText: title });
await problem.click({ position: { x: 95, y: 12 } });
const jump = page.getByRole("button", { name: "Jump to Source" });
const message = page.getByText(detail, { exact: false }).filter({ visible: true }).last();
expect((await jump.boundingBox())!.y).toBeLessThan((await message.boundingBox())!.y);
const details = page.getByRole("region", { name: "Inspection details" });
const quickFixes = details.getByRole("button", { name: "Show Quick Fixes" });
await expect(details.getByText(`${relative}:3:7`)).toBeVisible();
const split = page.getByRole("separator", { name: "Resize inspection panes" });
await expect(split).toHaveAttribute("aria-valuenow", "50");
await split.focus();
await page.keyboard.press("ArrowRight");
await expect(split).not.toHaveAttribute("aria-valuenow", "50");
await page.setViewportSize({ width: 540, height: 680 });
await expect(quickFixes).toBeInViewport({ ratio: 1 });
await expect(jump).toBeInViewport({ ratio: 1 });
const right = (await details.boundingBox())!;
const jumpBounds = (await jump.boundingBox())!;
expect(jumpBounds.x + jumpBounds.width).toBeLessThan(right.x + right.width);
const file = tree.getByRole("treeitem").filter({ has: page.getByTitle(relative, { exact: true }) });
const count = file.getByText("1", { exact: true });
const fileBounds = (await file.boundingBox())!;
const countBounds = (await count.boundingBox())!;
expect(countBounds.x + countBounds.width).toBeLessThan(fileBounds.x + fileBounds.width);
expect(await message.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
expect(await tree.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
await jump.click();
await expect
.poll(() =>
page.evaluate(async () => {
const service = "/src/workbench/contributions.ts";
const cursor = (await import(/* @vite-ignore */ service)).editorService().activeCursor();
return { path: cursor?.path, line: cursor?.line, col: cursor?.col };
}),
)
.toEqual({ path, line: 2, col: 6 });
});
+2 -1
Переглянути файл
@@ -53,7 +53,8 @@ test("Python syntax supplements retain PyCharm colours without a language server
await expect(page.locator(".cm-sem-python-predefined-definition")).toHaveCSS("color", "rgb(187, 153, 34)");
await expect(page.locator(".cm-sem-python-predefined-usage")).toHaveCSS("color", "rgb(204, 170, 51)");
await expect(page.locator(".cm-sem-keyword").filter({ hasText: /^type$/ })).toHaveCSS("color", "rgb(17, 34, 51)");
await expect(page.locator(".cm-sem-unused")).toHaveCSS("color", "rgb(111, 115, 122)");
// The scheme is Darcula-based and doesn't name NOT_USED_ELEMENT_ATTRIBUTES: Darcula's #72737A applies.
await expect(page.locator(".cm-sem-unused")).toHaveCSS("color", "rgb(114, 115, 122)");
expect(errors).toEqual([]);
await page.screenshot({ path: info.outputPath("python-highlighting.png") });
});
+2 -1
Переглянути файл
@@ -84,7 +84,8 @@ test("Recent Locations keeps all snippet lines visible when the editor font grow
await expect(code).toHaveCSS("font-size", "19px");
await expect(code).toHaveCSS("line-height", "30px");
await expect(code).toHaveCSS("font-family", /"Fira Code".*"Maple Mono NF CN"/);
expect((await code.boundingBox())!.height).toBe(90);
// Three 30px lines; layout may land on a fractional pixel.
expect((await code.boundingBox())!.height).toBeCloseTo(90, 0);
await page.setViewportSize({ width: 400, height: 500 });
const filter = dialog.getByRole("textbox", { name: "Filter recent locations" });
+2 -2
Переглянути файл
@@ -2,9 +2,9 @@ import { expect, test } from "./fixtures";
for (const [id, selector] of [
["build.deployment", "[class*='layout'] > [class*='note']"],
["editor.inspections", "[class*='split'] > [class*='details']"],
["editor.inspections", "[class*='split'] section[class*='details']"],
["languages.servers", "[class*='body'] > [class*='language'][aria-label]"],
["plugins", "[class*='body'] > [class*='details']"],
["plugins", "[class*='body'] [class*='details'][aria-label]"],
["agents.list", "section[aria-label='Codex']"],
] as const) {
test(`${id} keeps its details usable beside the list`, async ({ workbench: page }) => {
+12
Переглянути файл
@@ -187,6 +187,18 @@ describe("IntelliJ theme import", () => {
});
});
it("takes what a Darcula-based scheme leaves out from Darcula", () => {
const s = convertIcls(`<scheme name="Mine" version="142" parent_scheme="Darcula"><attributes>
<option name="DEFAULT_KEYWORD"><value><option name="FOREGROUND" value="ff8800"/></value></option>
<option name="DEFAULT_STRING"><value/></option>
</attributes></scheme>`);
expect(s.tokens["--bg-editor"]).toBe("#2b2b2b");
expect(s.tokens["--syn-keyword"]).toBe("#ff8800");
// An empty entry of its own replaces Darcula's colour.
expect(s.tokens["--syn-string"]).toBeUndefined();
expect(convertIcls(`<scheme name="I" parent_scheme="Islands Dark"></scheme>`).tokens).toEqual({});
});
it("only targets tokens that exist in tokens.css", () => {
const declared = new Set([...css.matchAll(/(--[a-z0-9-]+)\s*:/g)].map((m) => m[1]!));
// Read with a fallback by the editor (no tokens.css default), still themeable.
+304 -1
Переглянути файл
@@ -1,4 +1,8 @@
use ide_core::{EventSink, IdeEvent};
use ide_core::{EventSink, IdeEvent, SharedSink};
use parking_lot::Mutex;
use std::collections::{HashMap, VecDeque};
use std::sync::Arc;
use std::time::Duration;
use tauri::{AppHandle, Emitter, Manager, UserAttentionType};
/// Name of the single backend → UI event. Payload: [`IdeEvent`].
@@ -38,6 +42,103 @@ pub struct TauriSink {
pub window: Option<String>,
}
const COALESCE_WINDOW: Duration = Duration::from_millis(16);
const MAX_PENDING_DIAGNOSTICS: usize = 4096;
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
struct DiagnosticKey {
path: ide_core::IpcPath,
source: String,
}
#[derive(Default)]
struct PendingDiagnostics {
order: VecDeque<DiagnosticKey>,
events: HashMap<DiagnosticKey, IdeEvent>,
scheduled: bool,
}
fn diagnostic_key(event: &IdeEvent) -> Option<DiagnosticKey> {
let IdeEvent::Diagnostics { path, source, .. } = event else {
return None;
};
Some(DiagnosticKey { path: path.clone(), source: source.clone() })
}
fn take_pending(state: &mut PendingDiagnostics) -> Vec<IdeEvent> {
let mut events = Vec::with_capacity(state.events.len());
for key in state.order.drain(..) {
if let Some(event) = state.events.remove(&key) {
events.push(event);
}
}
events
}
/// Collapses repeated full-replacement diagnostics for one `(path, source)` into the
/// latest event in a frame-sized window. Any other event flushes the pending
/// diagnostics first so lifecycle and ordered events cannot overtake them.
pub fn coalescing_sink(sink: SharedSink, runtime: tokio::runtime::Handle) -> SharedSink {
let pending = Arc::new(Mutex::new(PendingDiagnostics::default()));
let dispatch = Arc::new(Mutex::new(()));
Arc::new(move |event| {
let Some(key) = diagnostic_key(&event) else {
let _dispatch = dispatch.lock();
let events = take_pending(&mut pending.lock());
for pending_event in events {
sink.emit(pending_event);
}
sink.emit(event);
return;
};
loop {
let schedule = {
let mut state = pending.lock();
if !state.events.contains_key(&key) && state.events.len() >= MAX_PENDING_DIAGNOSTICS {
None
} else {
if !state.events.contains_key(&key) {
state.order.push_back(key.clone());
}
state.events.insert(key.clone(), event.clone());
if state.scheduled {
return;
}
state.scheduled = true;
Some(())
}
};
if schedule.is_none() {
let _dispatch = dispatch.lock();
let events = take_pending(&mut pending.lock());
for pending_event in events {
sink.emit(pending_event);
}
continue;
}
let pending = pending.clone();
let dispatch = dispatch.clone();
let sink = sink.clone();
runtime.spawn(async move {
tokio::time::sleep(COALESCE_WINDOW).await;
let _dispatch = dispatch.lock();
let events = {
let mut state = pending.lock();
state.scheduled = false;
take_pending(&mut state)
};
for event in events {
sink.emit(event);
}
});
return;
}
})
}
/// A debug session stopped on a breakpoint: bounce/flash the taskbar icon
/// (IDEA) unless the user is already looking at an OpenIDEA window. The focus
/// check and the request both touch the windowing system, so they run on the
@@ -94,3 +195,205 @@ impl EventSink for TauriSink {
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use ide_core::{Diagnostic, IpcPath, Pos, Range, Severity, TaskId};
use parking_lot::Mutex;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::Duration;
use std::time::Instant;
fn setup() -> (ide_core::SharedSink, Arc<Mutex<Vec<IdeEvent>>>) {
let events = Arc::new(Mutex::new(Vec::new()));
let saved = events.clone();
(coalescing_sink(Arc::new(move |event| saved.lock().push(event)), tokio::runtime::Handle::current()), events)
}
fn diagnostics(path: &str, source: &str, message: &str) -> IdeEvent {
IdeEvent::Diagnostics {
path: IpcPath::from(path),
source: source.into(),
items: vec![Diagnostic {
range: Range::point(Pos::new(0, 0)),
severity: Severity::Error,
message: message.into(),
source: None,
code: None,
unnecessary: false,
deprecated: false,
server: None,
}],
}
}
fn task(message: &str, done: bool) -> IdeEvent {
IdeEvent::Task {
id: TaskId(1),
title: "Indexing".into(),
message: Some(message.into()),
fraction: Some(if done { 1.0 } else { 0.5 }),
done,
cancellable: !done,
}
}
#[tokio::test]
async fn coalesces_diagnostics_by_path_and_source() {
let (sink, events) = setup();
for index in 0..100 {
sink.emit(diagnostics("/p/a.rs", "rust-analyzer", &format!("old {index}")));
}
sink.emit(diagnostics("/p/a.rs", "eslint", "lint"));
sink.emit(diagnostics("/p/b.rs", "rust-analyzer", "other"));
assert!(events.lock().is_empty());
tokio::task::yield_now().await;
tokio::time::sleep(Duration::from_millis(30)).await;
tokio::task::yield_now().await;
{
let saved_events = events.lock();
assert_eq!(saved_events.len(), 3);
assert!(matches!(
&saved_events[0],
IdeEvent::Diagnostics { path, source, items }
if path == &IpcPath::from("/p/a.rs")
&& source == "rust-analyzer"
&& items[0].message == "old 99"
));
assert!(matches!(
&saved_events[1],
IdeEvent::Diagnostics { path, source, .. }
if path == &IpcPath::from("/p/a.rs") && source == "eslint"
));
assert!(matches!(
&saved_events[2],
IdeEvent::Diagnostics { path, source, .. }
if path == &IpcPath::from("/p/b.rs") && source == "rust-analyzer"
));
}
tokio::time::sleep(Duration::from_millis(30)).await;
assert_eq!(events.lock().len(), 3);
}
#[tokio::test]
async fn immediate_events_flush_pending_events_first() {
let (sink, events) = setup();
sink.emit(diagnostics("/p/a.rs", "rust-analyzer", "before"));
sink.emit(diagnostics("/p/b.rs", "rust-analyzer", "other"));
sink.emit(IdeEvent::SettingsChanged { key: "editor.fontSize".into() });
let events = events.lock();
assert_eq!(events.len(), 3);
assert!(matches!(&events[0], IdeEvent::Diagnostics { .. }));
assert!(matches!(&events[1], IdeEvent::Diagnostics { .. }));
assert!(matches!(&events[2], IdeEvent::SettingsChanged { .. }));
}
#[tokio::test]
async fn lifecycle_events_remain_immediate() {
let (sink, events) = setup();
sink.emit(task("complete", true));
let events = events.lock();
assert_eq!(events.len(), 1);
assert!(matches!(
&events[0],
IdeEvent::Task { message, done, .. }
if message.as_deref() == Some("complete") && *done
));
}
#[tokio::test]
async fn diagnostic_buffer_cap_flushes_without_dropping() {
let (sink, events) = setup();
for index in 0..=MAX_PENDING_DIAGNOSTICS {
sink.emit(diagnostics(&format!("/p/{index}.rs"), "rust-analyzer", "diagnostic"));
}
assert_eq!(events.lock().len(), MAX_PENDING_DIAGNOSTICS);
tokio::time::sleep(Duration::from_millis(30)).await;
assert_eq!(events.lock().len(), MAX_PENDING_DIAGNOSTICS + 1);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[ignore = "run for before/after diagnostics transport measurements"]
async fn diagnostics_coalescing_benchmark() {
const FILES: usize = 2_000;
const ROUNDS: usize = 10;
let burst: Vec<IdeEvent> = (0..ROUNDS)
.flat_map(|round| {
(0..FILES).map(move |file| {
diagnostics(&format!("/workspace/src/File{file}.rs"), "rust-analyzer", &format!("round-{round}"))
})
})
.collect();
let raw_events = Arc::new(AtomicUsize::new(0));
let raw_count = raw_events.clone();
let raw: SharedSink = Arc::new(move |event| {
let encoded = serde_json::to_vec(&event).unwrap();
raw_count.fetch_add(1, Ordering::Relaxed);
std::hint::black_box(encoded.len());
});
let raw_started = Instant::now();
for event in &burst {
raw.emit(event.clone());
}
let raw_elapsed = raw_started.elapsed();
assert_eq!(raw_events.load(Ordering::Relaxed), FILES * ROUNDS);
let coalesced_events = Arc::new(AtomicUsize::new(0));
let delivered_state = Arc::new(Mutex::new(HashMap::<IpcPath, String>::new()));
let coalesced_count = coalesced_events.clone();
let delivered = delivered_state.clone();
let target: SharedSink = Arc::new(move |event| {
let encoded = serde_json::to_vec(&event).unwrap();
coalesced_count.fetch_add(1, Ordering::Relaxed);
if let IdeEvent::Diagnostics { path, items, .. } = event {
delivered.lock().insert(path, items[0].message.clone());
}
std::hint::black_box(encoded.len());
});
let coalesced = coalescing_sink(target, tokio::runtime::Handle::current());
let coalesced_started = Instant::now();
for event in &burst {
coalesced.emit(event.clone());
}
let expected_last_round = format!("round-{}", ROUNDS - 1);
let deadline = Instant::now() + Duration::from_secs(2);
loop {
let complete = {
let delivered_state = delivered_state.lock();
delivered_state.len() == FILES
&& delivered_state.values().all(|message| message == &expected_last_round)
};
if complete {
break;
}
assert!(Instant::now() < deadline, "diagnostics did not settle before benchmark timeout");
tokio::time::sleep(Duration::from_millis(5)).await;
}
let coalesced_elapsed = coalesced_started.elapsed();
let coalesced_count = coalesced_events.load(Ordering::Relaxed);
assert!(coalesced_count >= FILES);
assert!(coalesced_count < FILES * ROUNDS);
let delivered_state = delivered_state.lock();
assert_eq!(delivered_state.len(), FILES);
assert!(delivered_state.values().all(|message| message == &expected_last_round));
println!(
"diagnostics transport burst: raw_events={} raw_ms={:.2} coalesced_events={} \
coalesced_total_ms={:.2} reduction_pct={:.1}",
FILES * ROUNDS,
raw_elapsed.as_secs_f64() * 1_000.0,
coalesced_count,
coalesced_elapsed.as_secs_f64() * 1_000.0,
(1.0 - coalesced_count as f64 / (FILES * ROUNDS) as f64) * 100.0,
);
}
}
+41 -7
Переглянути файл
@@ -1282,11 +1282,11 @@ fn build_rendered<R: Runtime>(
for rendered in menus {
let submenu = Submenu::with_id(app, format!("submenu:{}", rendered.id), &rendered.title, true)?;
append_rendered(app, &submenu, &rendered.items, disabled)?;
// The Window menu is registered after `set_menu`: doing it here cannot see the submenu
// on NSApp, so AppKit never adds the open-window list.
#[cfg(target_os = "macos")]
match rendered.id {
"window" => submenu.set_as_windows_menu_for_nsapp()?,
"help" => submenu.set_as_help_menu_for_nsapp()?,
_ => {}
if rendered.id == "help" {
submenu.set_as_help_menu_for_nsapp()?;
}
menu.append(&submenu)?;
}
@@ -1632,9 +1632,43 @@ pub fn install<R: Runtime>(app: &AppHandle<R>, menu_state: &MenuState, recent: &
*slot = Some(rendered);
return;
}
match build(app, Os::current(), &config, &items, &disabled).and_then(|menu| app.set_menu(menu)) {
Ok(_) => *slot = Some(rendered),
Err(e) => tracing::warn!("failed to build the app menu: {e}"),
let installed = match build(app, Os::current(), &config, &items, &disabled).and_then(|menu| app.set_menu(menu)) {
Ok(_) => {
*slot = Some(rendered);
true
}
Err(e) => {
tracing::warn!("failed to build the app menu: {e}");
false
}
};
drop(slot);
if installed {
// After the menu bar is installed. Holding `rendered` across this would deadlock a menu
// click on the main thread, which also takes that lock.
#[cfg(target_os = "macos")]
register_macos_windows_menu(app);
}
}
/// Makes the Window submenu the macOS windows menu, so AppKit lists open windows under it.
///
/// Each item uses the window title (`project – file`, or the workspace name). muda can only
/// resolve the submenu once `set_menu` has attached it, and Tauri itself only does this for
/// the id `__tauri_window_menu__`.
#[cfg(target_os = "macos")]
fn register_macos_windows_menu<R: Runtime>(app: &AppHandle<R>) {
let Some(menu) = app.menu() else { return };
let Ok(items) = menu.items() else { return };
for item in items {
let Some(submenu) = item.as_submenu() else { continue };
if submenu.id().as_ref() != "submenu:window" {
continue;
}
if let Err(error) = submenu.set_as_windows_menu_for_nsapp() {
tracing::warn!("failed to register the macOS Window menu: {error}");
}
return;
}
}
+45
Переглянути файл
@@ -1161,6 +1161,50 @@ pub async fn remote_import_local(
result
}
/// One file of a [`remote_download_local`] transfer starting: `done` of `total` files are finished.
#[derive(Clone, Serialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct DownloadProgress {
pub path: String,
pub done: u32,
pub total: u32,
}
/// The project view's Download to…: remote files and folders of this window's project into the
/// local folder `target`, each under its own name. Like Remote Host › Download to…, nothing is
/// written outside `target`, even through a local symlink inside it.
#[desktop_command(trust = trusted)]
#[tauri::command]
#[specta::specta]
pub async fn remote_download_local(
window: Window,
state: State<'_, AppState>,
paths: Vec<String>,
target: std::path::PathBuf,
request: ide_core::RequestId,
on_progress: Channel<DownloadProgress>,
) -> IdeResult<ide_remote::TransferReport> {
let label = AppState::owner_window(window.label());
let c = state.remote_dev.get(label).ok_or_else(|| IdeError::unavailable("Remote project is disconnected"))?;
let Some(session) = c.session.clone() else {
return Err(IdeError::unavailable("Downloading files is not supported in a WSL project yet"));
};
let cancel = state.host.begin_request(request);
let result = async {
let fs = ide_ssh::RemoteFs::new(session.sftp().await?);
let mut progress = |path: &str, done: usize, total: usize| {
let _ =
on_progress.send(DownloadProgress { path: path.to_owned(), done: done as u32, total: total as u32 });
};
let result = ide_remote::service::download_into(&fs, &paths, &target, &cancel, &mut progress).await;
fs.close().await;
result
}
.await;
state.host.end_request(request);
result
}
/// A command the server does not know, from a server of another version than this app: says so,
/// instead of the bare JSON-RPC error.
fn older_server_error(e: IdeError, server_version: &str, host: &str) -> IdeError {
@@ -1391,6 +1435,7 @@ ide_command::desktop_domain!(
remote_connect,
remote_current,
remote_disconnect,
remote_download_local,
remote_forward_port,
remote_forwarded_ports,
remote_import_local,
+9 -4
Переглянути файл
@@ -1,4 +1,4 @@
use crate::events::TauriSink;
use crate::events::{TauriSink, coalescing_sink};
use ide_core::{EventSink, IdeEvent, IdeResult, SharedSink};
use ide_language::{LanguageRegistry, Syntax};
use ide_workspace::RecentProjects;
@@ -83,9 +83,11 @@ impl AppState {
tracing::info!("invalidated caches: {removed:?}");
}
ide_host::data_dirs::migrate(&data_dir, &local_data_dir);
let global_sink: SharedSink = Arc::new(TauriSink { app: app.clone(), window: None });
let runtime = tauri::async_runtime::handle().inner().clone();
let global_sink = coalescing_sink(Arc::new(TauriSink { app: app.clone(), window: None }), runtime.clone());
let languages = Arc::new(LanguageRegistry::load(Some(&config_dir.join("languages")))?);
let sink_app = app.clone();
let sink_runtime = runtime.clone();
let host = Arc::new(Host::new(ide_host::HostConfig {
config_dir: config_dir.clone(),
data_dir: data_dir.clone(),
@@ -93,10 +95,13 @@ impl AppState {
languages: languages.clone(),
syntax,
sink_for: Box::new(move |window| {
Arc::new(TauriSink { app: sink_app.clone(), window: Some(window.to_owned()) })
coalescing_sink(
Arc::new(TauriSink { app: sink_app.clone(), window: Some(window.to_owned()) }),
sink_runtime.clone(),
)
}),
owner: Self::owner_window,
runtime: tauri::async_runtime::handle().inner().clone(),
runtime,
project_environment: false,
}));
let announce = global_sink.clone();
+1
Переглянути файл
@@ -512,6 +512,7 @@ remote_current always desktop bin
remote_delete trusted project_host bindings async
remote_disconnect always desktop bindings sync
remote_download_into trusted project_host bindings async
remote_download_local trusted desktop bindings async
remote_forward_port trusted desktop bindings async
remote_forwarded_ports trusted desktop bindings sync
remote_import_local trusted desktop bindings async
+13
Переглянути файл
@@ -1345,6 +1345,12 @@ export const commands = {
remoteDelete: (connection: FsConnection, path: string) => typedError<null, IdeError>(__TAURI_INVOKE("remote_delete", { connection, path })),
remoteDisconnect: () => __TAURI_INVOKE<void>("remote_disconnect"),
remoteDownloadInto: (connection: FsConnection, paths: string[], target: IpcPath, request: RequestId) => typedError<TransferReport, IdeError>(__TAURI_INVOKE("remote_download_into", { connection, paths, target, request })),
/**
* The project view's Download to…: remote files and folders of this window's project into the
* local folder `target`, each under its own name. Like Remote Host › Download to…, nothing is
* written outside `target`, even through a local symlink inside it.
*/
remoteDownloadLocal: (paths: string[], target: string, request: RequestId, onProgress: Channel<DownloadProgress>) => typedError<TransferReport, IdeError>(__TAURI_INVOKE("remote_download_local", { paths, target, request, onProgress })),
/**
* Forwards `localhost:<remote_port>` of the remote host to the same port here when it is free,
* else to a free one. Nothing needs to listen there yet; connections are opened per use.
@@ -5480,6 +5486,13 @@ export type DocumentTextChange = {
insert: string,
};
/** One file of a [`remote_download_local`] transfer starting: `done` of `total` files are finished. */
export type DownloadProgress = {
path: string,
done: number,
total: number,
};
export type DuplicateGroup = {
tokens: number,
/** Lines of the first fragment. */
+5
Переглянути файл
@@ -376,6 +376,11 @@ export const openideaTheme = EditorView.theme({
borderRadius: "var(--radius-popup)",
boxShadow: "var(--shadow-popup)",
},
// Near the window edge CodeMirror caps the hover host's height; its sections then shrink and
// scroll inside the popup instead of running past its border. Content tooltips still carry
// their own `max-height` + `overflow` for the space they get when not squeezed.
".cm-tooltip.cm-tooltip-hover": { display: "flex", flexDirection: "column" },
".cm-tooltip-hover > .cm-tooltip-section": { minHeight: 0, flexShrink: 1 },
".cm-tooltip .cm-tooltip-arrow:before": {
borderTopColor: "var(--border-popup)",
borderBottomColor: "var(--border-popup)",
+29
Переглянути файл
@@ -0,0 +1,29 @@
import { afterEach, expect, it } from "vitest";
import { EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { openideaTheme } from "./theme";
let view: EditorView | null = null;
afterEach(() => {
view?.destroy();
view = null;
});
it("shrinks hover tooltip sections near the window edge instead of spilling past the popup", () => {
view = new EditorView({
state: EditorState.create({ extensions: [openideaTheme] }),
parent: document.body,
});
// The DOM CodeMirror builds: the hover host wraps one section per tooltip.
const host = document.createElement("div");
host.className = "cm-tooltip cm-tooltip-hover";
const section = document.createElement("div");
section.className = "cm-tooltip-section";
host.appendChild(section);
view.dom.appendChild(host);
const hostStyle = getComputedStyle(host);
expect(hostStyle.display).toBe("flex");
expect(hostStyle.flexDirection).toBe("column");
// `min-height: 0` releases the section from the flex minimum so it can shrink and scroll.
expect(getComputedStyle(section).minHeight).toBe("0px");
});
+31 -1
Переглянути файл
@@ -386,6 +386,20 @@ async function pythonImplementations(doc: EditorDocContext, pos: Pos): Promise<D
return pythonImplementationTargets(hierarchy, doc.path, pos, outline).catch(() => []);
}
/**
* Asks for the declaration at `offset`, dropping the target under the caret. Called when Go to
* Implementation finds nothing: the jump then ends on the declaration, as in IDEA.
*/
async function implementationFallbackTargets(
view: EditorView,
offset: number,
path: string,
pos: Pos,
): Promise<readonly DeclarationTarget[]> {
const declaration = await requestNavigation(view, offset, "definition").catch(() => []);
return declaration.filter((l) => !isSelfTarget([l], path, pos));
}
/** Whether `line` (0-based) of `text` is an import statement. */
function isImportLine(text: Text, line: number): boolean {
return line < text.lines && /^\s*(from|import)\s/.test(text.line(line + 1).text);
@@ -510,7 +524,17 @@ async function gotoResolved(
const graph = graphTargets ? await graphTargets : [];
if (superseded()) return;
if (graph.length) locs = graph;
else if (isCancelled(e) || !declaration) {
else if (kind === "implementation" && !isCancelled(e) && !isUnavailable(e)) {
// Some servers fail the request instead of answering empty (gopls: "no interfaces
// implemented by this method"). Treat that as a search that found nothing, not a broken server.
const declarationTargets = await implementationFallbackTargets(view, offset, doc.path, pos);
if (superseded()) return;
if (!declarationTargets.length) {
reportLspError(view, e, true);
return;
}
locs = dedupeLocations(declarationTargets);
} else if (isCancelled(e) || !declaration) {
reportLspError(view, e, true);
return;
} else {
@@ -542,6 +566,12 @@ async function gotoResolved(
return;
}
if (superseded()) return;
// Outside `gotoAfterEdits`, whose retries would repeat the extra request.
if (!locs.length && kind === "implementation" && !serverDown) {
const declarationTargets = await implementationFallbackTargets(view, offset, doc.path, pos);
if (superseded()) return;
locs = dedupeLocations(declarationTargets);
}
if (!locs.length) {
// The server has no definition here: a link (`href`, `#include`, Markdown) or a file path.
if (
+157
Переглянути файл
@@ -0,0 +1,157 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import type { commands, Location } from "@/platform/ipc";
const { lspGoto, lspGotoImplementation } = vi.hoisted(() => ({
lspGoto: vi.fn<typeof commands.lspGoto>(),
lspGotoImplementation: vi.fn<typeof commands.lspGotoImplementation>(),
}));
vi.mock("@/platform/ipc", async (orig) => {
const real = await orig<typeof import("@/platform/ipc")>();
const fsReadText: typeof commands.fsReadText = async () => ({
status: "error",
error: { kind: "notFound", message: "not found" },
});
const navInheritance: typeof commands.navInheritance = async () => ({ status: "ok", data: [] });
return {
...real,
isTauri: () => true,
commands: { ...real.commands, lspGoto, lspGotoImplementation, fsReadText, navInheritance },
};
});
vi.mock("@tauri-apps/api/core", async (orig) => ({
...(await orig<object>()),
Channel: class {
onmessage = () => {};
},
}));
const { gotoTargets } = await import("./navigation");
const { lspDoc } = await import("./lsp");
const { closePopup } = await import("./popupStore");
const { invalidateConfigurationNavigation } = await import("./configurationNavigation");
const { provideEditorService } = await import("@/workbench/contributions");
const openFile = vi.fn(async (_path: string, _opts: unknown) => {});
provideEditorService({ openFile } as never);
const loc = (path: string, line = 1, col = 2): Location => ({
path,
uri: null,
range: { start: { line, col }, end: { line, col: col + 3 } },
});
const ok = (data: Location[]) => ({ status: "ok" as const, data });
const declared = loc("/p/store.go");
const implementation = loc("/p/iface.go");
const TEXT = "package p\n\nfunc (s *Store) Search() {}\n";
const editor = (text: string, language: string, path: string) =>
new EditorView({
state: EditorState.create({
doc: text,
extensions: [lspDoc.of({ doc: 1, path, language, uiMode: language, readOnly: false })],
}),
parent: document.body,
});
let view: EditorView;
beforeEach(() => {
vi.clearAllMocks();
invalidateConfigurationNavigation();
lspGoto.mockResolvedValue(ok([]));
lspGotoImplementation.mockResolvedValue(ok([]));
view = editor(TEXT, "go", "/p/store.go");
});
afterEach(() => {
view.destroy();
closePopup();
document.body.replaceChildren();
vi.restoreAllMocks();
});
/** Go to Implementation on `Search`, at the method's name. */
const gotoSearch = () => gotoTargets(view, "implementation", TEXT.indexOf("Search") + 2);
describe("Go to Implementation on a symbol nothing implements", () => {
it("navigates to the declaration, like IDEA", async () => {
lspGoto.mockResolvedValue(ok([declared]));
await gotoSearch();
expect(openFile.mock.calls.map(([path]) => path)).toEqual(["/p/store.go"]);
expect(lspGotoImplementation).toHaveBeenCalledOnce();
expect(lspGoto.mock.calls.map(([, , kind]) => kind)).toEqual(["definition"]);
});
it("navigates when the server reports its failed search as an error", async () => {
lspGotoImplementation.mockResolvedValue({
status: "error",
error: { kind: "protocol", message: "no interfaces implemented by this method" },
});
lspGoto.mockResolvedValue(ok([declared]));
await gotoSearch();
expect(openFile.mock.calls.map(([path]) => path)).toEqual(["/p/store.go"]);
});
it("still navigates to the implementations when there are some", async () => {
lspGotoImplementation.mockResolvedValue(ok([implementation]));
await gotoSearch();
expect(openFile.mock.calls.map(([path]) => path)).toEqual(["/p/iface.go"]);
expect(lspGoto).not.toHaveBeenCalled();
});
it("does not navigate onto the declaration the caret is already on", async () => {
const at = TEXT.indexOf("Search");
const col = at - (TEXT.lastIndexOf("\n", at) + 1);
lspGoto.mockResolvedValue(
ok([{ ...declared, range: { start: { line: 2, col }, end: { line: 2, col: col + 6 } } }]),
);
await gotoSearch();
expect(openFile).not.toHaveBeenCalled();
expect(document.querySelector(".cm-lsp-hint")?.textContent).toBe("No implementations found");
});
it("keeps the not-found hint when the declaration request fails", async () => {
lspGoto.mockRejectedValue(new Error("timeout"));
await gotoSearch();
expect(openFile).not.toHaveBeenCalled();
expect(document.querySelector(".cm-lsp-hint")?.textContent).toBe("No implementations found");
});
it("ignores the caret's own declaration among several targets", async () => {
const at = TEXT.indexOf("Search");
const col = at - (TEXT.lastIndexOf("\n", at) + 1);
const self = { ...declared, range: { start: { line: 2, col }, end: { line: 2, col: col + 6 } } };
lspGoto.mockResolvedValue(ok([self, loc("/p/other.go")]));
await gotoSearch();
expect(openFile.mock.calls.map(([path]) => path)).toEqual(["/p/other.go"]);
});
it("keeps an unavailable server's error instead of inventing a target", async () => {
lspGotoImplementation.mockResolvedValue({
status: "error",
error: { kind: "unavailable", message: "no implementation provider" },
});
lspGoto.mockResolvedValue(ok([declared]));
await gotoSearch();
expect(lspGoto).not.toHaveBeenCalled();
expect(openFile).not.toHaveBeenCalled();
expect(document.querySelector(".cm-lsp-hint")).not.toBeNull();
});
it("navigates to a type's declaration from a usage", async () => {
const text = "package p\n\nvar s Store\n";
view.destroy();
view = editor(text, "go", "/p/store.go");
lspGoto.mockResolvedValue(ok([loc("/p/store.go", 0, 5)]));
await gotoTargets(view, "implementation", text.indexOf("Store") + 2);
expect(openFile).toHaveBeenCalledWith("/p/store.go", { selection: { line: 0, col: 5 }, focus: true });
});
it("covers Python, whose servers have no type hierarchy", async () => {
const text = "class Order:\n pass\n\nuse = Order\n";
view.destroy();
view = editor(text, "python", "/p/order.py");
lspGoto.mockResolvedValue(ok([loc("/p/order.py", 0, 6)]));
await gotoTargets(view, "implementation", text.lastIndexOf("Order") + 2);
expect(openFile).toHaveBeenCalledWith("/p/order.py", { selection: { line: 0, col: 6 }, focus: true });
});
});
+3 -2
Переглянути файл
@@ -300,13 +300,14 @@ describe("mouse navigation", () => {
expect(lspGoto).not.toHaveBeenCalled();
});
it("reports missing implementations without navigating to the declaration", async () => {
it("asks for the declaration before reporting missing implementations", async () => {
lspGoto.mockResolvedValue({ status: "ok", data: [] });
click({ metaKey: true, altKey: true });
await vi.waitFor(() =>
expect(document.querySelector(".cm-lsp-hint")?.textContent).toBe("No implementations found"),
);
expect(lspGoto).toHaveBeenCalledExactlyOnceWith(1, { line: 0, col: 9 }, "implementation");
// IDEA falls back to the declaration when nothing implements the name.
expect(lspGoto.mock.calls.map(([, , kind]) => kind)).toEqual(["implementation", "definition"]);
expect(openFile).not.toHaveBeenCalled();
});
+17
Переглянути файл
@@ -28,6 +28,7 @@ import { AgentsStatus } from "./AgentsStatus";
import { activateSettingsPages } from "./settingsPages";
import { HOME_KIND, MCP_PAGE, REGISTRY_PAGE, SESSION_KIND, TASK_DRAG, TOOL_WINDOW, providerIcon } from "./model";
import { sendPaths, sendSelection, trackEditorCopies } from "./references";
import { diagnoseTestFailure, isTestFailure } from "./testFailure";
import { focusedSession, inputSession } from "./sessionFocus";
import { cycleFocusedEffort } from "./effortFocus";
import { clearAgentTabFontZoom } from "./fontZoom";
@@ -307,6 +308,22 @@ export function activate(): () => void {
else sendSelection();
},
},
{
id: "agents.diagnoseTestFailure",
title: "Diagnose with Agent",
description:
"Adds a failed test's name, source location, expected and actual values and output to the agent message typed last, to review and send.",
category: "Agents",
icon: "toolwindow-agents",
when: "projectOpen",
keywords: ["agent", "test", "failure", "diagnose", "explain", "fix"],
// Run from the test tree, which passes the failure.
hidden: true,
enabled: ({ arg }) => isTestFailure(arg),
run: ({ arg }) => {
if (isTestFailure(arg)) diagnoseTestFailure(arg);
},
},
{
id: "agents.generateCommitMessage",
title: "Generate Commit Message with Agent",
+20 -3
Переглянути файл
@@ -1600,6 +1600,18 @@ export interface ReferenceTarget {
* how many were added; a path outside every project shows a notice.
*/
export function addReferences(targets: readonly ReferenceTarget[]): number {
return appendToComposer((mentions) => mentions.join(" "), targets);
}
/**
* Appends text to the agent message typed last (a task's or New Task's) and opens it; nothing is
* sent. `compose` gets the `@` mentions of `targets` (those inside this window's projects, which
* also become chips). Returns how many targets were referenced.
*/
export function appendToComposer(
compose: (mentions: readonly string[]) => string,
targets: readonly ReferenceTarget[] = [],
): number {
const s = useAgents.getState();
const key = activeComposerKey();
const task = key === HOME ? null : s.tasks.get(key)!;
@@ -1623,9 +1635,14 @@ export function addReferences(targets: readonly ReferenceTarget[]): number {
}
if (files.length < targets.length)
notifications().notify({ level: "info", title: tx("Only files of this window's projects can be referenced") });
if (!files.length) return 0;
const joined = mentions.join(" ");
const text = current.text && !/\s$/.test(current.text) ? `${current.text} ${joined} ` : `${current.text}${joined} `;
const joined = compose(mentions);
if (!joined) return 0;
// A block of several lines (a test failure) goes in a paragraph of its own.
const text = joined.includes("\n")
? `${current.text.trimEnd() ? `${current.text.trimEnd()}\n\n` : ""}${joined}\n`
: current.text && !/\s$/.test(current.text)
? `${current.text} ${joined} `
: `${current.text}${joined} `;
updateComposer(key, { text, files: [...current.files, ...files] });
if (task) openTask(task.id);
else openHome();
+42
Переглянути файл
@@ -0,0 +1,42 @@
import { describe, expect, it } from "vitest";
import { EXCERPT_LINES, failureDraft, isTestFailure } from "./testFailure";
describe("Diagnose with Agent draft (#4716)", () => {
it("names the test, its source reference and the compared values", () => {
const draft = failureDraft(
{
name: "OrderControllerTest > creates()",
expected: "201",
actual: "403",
output: ["", "Status expected:<201> but was:<403>", ""],
},
"@src/test/java/OrderControllerTest.java:42",
);
expect(draft).toBe(
[
"The test OrderControllerTest > creates() failed. Help me find out why.",
"Test source: @src/test/java/OrderControllerTest.java:42",
"Expected: 201\nActual: 403",
"```\nStatus expected:<201> but was:<403>\n```",
].join("\n\n"),
);
});
it("shortens a long excerpt and says how much it left out", () => {
const output = Array.from({ length: EXCERPT_LINES + 5 }, (_, i) => `at frame${i}`);
const draft = failureDraft({ name: "t", output }, undefined);
expect(draft).toContain(`at frame${EXCERPT_LINES - 1}\n… 5 more lines\n\`\`\``);
expect(draft).not.toContain(`at frame${EXCERPT_LINES}\n`);
expect(draft).not.toContain("Test source");
});
it("fences output that holds backticks with a longer fence", () => {
expect(failureDraft({ name: "t", output: ["```js", "x"] }, undefined)).toContain("````\n```js\nx\n````");
});
it("accepts only a failure argument", () => {
expect(isTestFailure({ name: "t", output: [] })).toBe(true);
expect(isTestFailure(undefined)).toBe(false);
expect(isTestFailure({ name: "t" })).toBe(false);
});
});
+53
Переглянути файл
@@ -0,0 +1,53 @@
/** "Diagnose with Agent" on a failed test: its failure as an editable draft for the agent. */
import { tx } from "@/platform/i18n";
import { appendToComposer } from "./store";
/** The `arg` of `agents.diagnoseTestFailure`, from the run's test tree. */
export interface TestFailure {
name: string;
/** The test's source file (absolute), when the run could resolve it. */
path?: string | null;
/** 1-based. */
line?: number;
expected?: string;
actual?: string;
/** What the run captured for this test: its output and failure details. */
output: readonly string[];
}
/** Excerpt lines kept in the draft; the rest is counted. */
export const EXCERPT_LINES = 60;
export function isTestFailure(arg: unknown): arg is TestFailure {
const a = arg as Partial<TestFailure> | null;
return !!a && typeof a.name === "string" && Array.isArray(a.output);
}
/** The draft text; `location` is the source reference (`@path:line`), if any. */
export function failureDraft(failure: TestFailure, location: string | undefined): string {
const parts = [tx`The test ${failure.name} failed. Help me find out why.`];
if (location) parts.push(tx`Test source: ${location}`);
if (failure.expected !== undefined && failure.actual !== undefined)
parts.push(`${tx("Expected:")} ${failure.expected}\n${tx("Actual:")} ${failure.actual}`);
const lines = failure.output.map((l) => l.trimEnd());
while (lines.length && !lines[0]) lines.shift();
while (lines.length && !lines.at(-1)) lines.pop();
if (lines.length) {
const shown = lines.slice(0, EXCERPT_LINES);
const more = lines.length - shown.length;
if (more > 0) shown.push(tx`… ${more} more lines`);
// A fence longer than any backtick run inside keeps the excerpt in one block.
const longest = Math.max(0, ...shown.map((l) => l.match(/`+/g)?.reduce((m, r) => Math.max(m, r.length), 0) ?? 0));
const fence = "`".repeat(Math.max(3, longest + 1));
parts.push(`${fence}\n${shown.join("\n")}\n${fence}`);
}
return parts.join("\n\n");
}
/** Appends the failure to the agent message typed last and opens it; the user reviews it and sends it. */
export function diagnoseTestFailure(failure: TestFailure): void {
const target = failure.path
? [{ path: failure.path, lines: failure.line ? { from: failure.line, to: failure.line } : undefined }]
: [];
appendToComposer((mentions) => failureDraft(failure, mentions[0]), target);
}
+48 -4
Переглянути файл
@@ -300,11 +300,27 @@
flex-direction: column;
min-width: 0;
min-height: 0;
font-size: var(--fs-ui);
}
.panel > * {
flex: 1;
min-height: 0;
}
.resultLabel,
.resultDirectory {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
}
.resultMeta {
flex: none;
color: var(--fg-subtle);
font-size: var(--fs-small);
}
.resultDirectory {
flex-shrink: 1;
max-width: 35%;
}
.excluded .message,
.excluded .strong {
opacity: 0.5;
@@ -313,29 +329,57 @@
.details {
display: flex;
flex-direction: column;
}
.detailsBody {
flex: 1;
min-height: 0;
display: flex;
flex-direction: column;
gap: var(--space-2);
padding: 10px 12px;
padding: var(--space-2) var(--space-3);
overflow: auto;
border-left: 1px solid var(--border);
font-size: var(--fs-ui);
overflow-wrap: anywhere;
}
.detailsEmpty {
flex: 1;
display: flex;
align-items: center;
justify-content: center;
padding: var(--space-3);
color: var(--fg-faint);
text-align: center;
}
.detailsTitle {
display: flex;
align-items: center;
align-items: baseline;
gap: var(--space-1-5);
color: var(--fg-strong);
}
.detailsLocation {
color: var(--fg-subtle);
font-size: var(--fs-small);
}
.detailsCoordinates {
white-space: nowrap;
}
.detailsMessage {
margin: 0;
white-space: pre-wrap;
color: var(--fg);
}
.detailsActions {
flex: none;
display: flex;
flex-wrap: wrap;
gap: var(--space-1-5);
padding: var(--space-1) var(--space-3);
border-bottom: 1px solid var(--border);
}
.detailAction {
max-width: 100%;
height: auto;
min-height: var(--h-control);
white-space: normal;
line-height: 1.25;
overflow-wrap: anywhere;
}
+50 -31
Переглянути файл
@@ -7,7 +7,8 @@ import clsx from "clsx";
import { create } from "zustand";
import { executeAction } from "@/platform/actions";
import { shortcutLabel } from "@/platform/keymap";
import { basename, relativeDir, useProject } from "@/platform/project";
import { basename, relativeDir, relativePath, useProject } from "@/platform/project";
import { tx } from "@/platform/i18n";
import { diagnosticInspection, producerOf, type InspectionRef } from "@/platform/inspections";
import { problemControls } from "@/platform/inspectionControls";
import { editorService, useOccurrenceNavigator } from "@/workbench/contributions";
@@ -287,31 +288,33 @@ export function InspectionView() {
<span className={clsx(styles.row, off)}>
<Icon name={n.severity} size={14} className={styles[`sev-${n.severity}`]} />
<span className={styles.strong}>{SEVERITY_LABEL[n.severity]}</span>
<span className={styles.count}>{plural(n.count, "problem")}</span>
<span className={styles.resultMeta}>{plural(n.count, "problem")}</span>
</span>
);
case "inspection":
return (
<span className={clsx(styles.row, off)}>
<span className={clsx(styles.row, off)} title={n.name}>
{!bySeverity && <Icon name={n.severity} size={14} className={styles[`sev-${n.severity}`]} />}
<span className={styles.strong}>{n.name}</span>
<span className={styles.count}>{n.count}</span>
<span className={clsx(styles.strong, styles.resultLabel)}>{n.name}</span>
<span className={styles.resultMeta}>{n.count}</span>
</span>
);
case "file":
case "file": {
const directory = relativeDir(root, n.path);
return (
<span className={clsx(styles.row, off)}>
<span className={clsx(styles.row, off)} title={relativePath(root, n.path)}>
<Icon name={fileIconName(basename(n.path), n.path)} size={16} className={styles.fileIcon} />
<span className={state.selected ? styles.strong : undefined}>{basename(n.path)}</span>
<span className={styles.muted}>{relativeDir(root, n.path)}</span>
<span className={styles.count}>{n.count}</span>
<span className={clsx(styles.resultLabel, state.selected && styles.strong)}>{basename(n.path)}</span>
{directory && <span className={clsx(styles.resultMeta, styles.resultDirectory)}>{directory}</span>}
<span className={styles.resultMeta}>{n.count}</span>
</span>
);
}
case "problem":
return (
<span className={clsx(styles.row, off)} title={n.p.d.message}>
<span className={styles.message}>{n.p.d.message.split("\n")[0]}</span>
<span className={styles.muted}>:{n.p.d.range.start.line + 1}</span>
<span className={styles.resultMeta}>:{n.p.d.range.start.line + 1}</span>
</span>
);
}
@@ -342,7 +345,11 @@ export function InspectionView() {
</div>
)}
<div className={styles.body} onKeyDown={onKeyDown}>
<SplitGroup orientation="horizontal" id="inspection-details-split">
<SplitGroup
orientation="horizontal"
id="inspection-details-split"
storageKey={roots.length > 0 ? "openidea.inspection.results.layout.v1" : undefined}
>
<SplitPanel id="results" minSize={160} className={styles.panel}>
<Tree<Node>
aria-label="Inspection results"
@@ -417,9 +424,11 @@ export function InspectionView() {
</SplitPanel>
{roots.length > 0 && (
<>
<SplitHandle />
<SplitPanel id="details" minSize={160} defaultSize="40%" className={styles.panel}>
<ProblemDetails node={lead} root={root} />
<SplitHandle aria-label={tx("Resize inspection panes")} />
<SplitPanel id="details" minSize={160} defaultSize="50%" className={styles.panel}>
<section className={styles.details} aria-label={tx("Inspection details")}>
<ProblemDetails node={lead} root={root} />
</section>
</SplitPanel>
</>
)}
@@ -434,14 +443,14 @@ function ProblemDetails({ node, root }: { node: Node | null; root: string }) {
if (!node || node.kind === "severity" || node.kind === "file") {
const count = node ? nodeProblems(node).length : 0;
return (
<div className={clsx(styles.details, styles.detailsEmpty)}>
<div className={styles.detailsEmpty}>
{node ? plural(count, "problem") : <T>Select a problem to see its details</T>}
</div>
);
}
if (node.kind === "inspection") {
return (
<div className={styles.details}>
<div className={styles.detailsBody}>
<div className={styles.detailsTitle}>{node.name}</div>
<div className={styles.muted}>
{SEVERITY_LABEL[node.severity]} · {plural(node.count, "problem")}
@@ -451,25 +460,35 @@ function ProblemDetails({ node, root }: { node: Node | null; root: string }) {
}
const { p } = node;
const sev = severityKey(p.d);
const pathParts = relativePath(root, p.path).split("/");
return (
<div className={styles.details}>
<div className={styles.detailsTitle}>
<Icon name={sev} size={14} className={styles[`sev-${sev}`]} />
<span>{p.d.source ? `${p.d.source}${p.d.code ? ` (${p.d.code})` : ""}` : <T>Language server</T>}</span>
</div>
<p className={clsx(styles.detailsMessage, selectableText)}>{p.d.message}</p>
<div className={styles.muted}>
{relativeDir(root, p.path) ? `${relativeDir(root, p.path)}/` : ""}
{basename(p.path)}:{p.d.range.start.line + 1}:{p.d.range.start.col + 1}
</div>
<div className={styles.detailsActions}>
<Button size="small" icon="bulb" onClick={() => void showFixes(p)}>
<>
<div className={styles.detailsActions} role="group" aria-label={tx("Inspection actions")}>
<Button size="small" icon="bulb" className={styles.detailAction} onClick={() => void showFixes(p)}>
<T>Show Quick Fixes</T>
</Button>
<Button size="small" variant="ghost" onClick={() => void open(p)}>
<Button size="small" variant="ghost" className={styles.detailAction} onClick={() => void open(p)}>
<T>Jump to Source</T>
</Button>
</div>
</div>
<div className={styles.detailsBody}>
<div className={styles.detailsTitle}>
<Icon name={sev} size={14} className={styles[`sev-${sev}`]} />
<span>{p.d.source ? `${p.d.source}${p.d.code ? ` (${p.d.code})` : ""}` : <T>Language server</T>}</span>
</div>
<div className={clsx(styles.detailsLocation, selectableText)}>
{pathParts.slice(0, -1).map((part, i) => (
<span key={i}>
{part}/<wbr />
</span>
))}
{pathParts.at(-1)}
<span className={styles.detailsCoordinates}>
:{p.d.range.start.line + 1}:{p.d.range.start.col + 1}
</span>
</div>
<p className={clsx(styles.detailsMessage, selectableText)}>{p.d.message}</p>
</div>
</>
);
}
+13 -1
Переглянути файл
@@ -91,7 +91,17 @@ interface Shaping {
export interface DataViewProps extends Pick<
GridProps,
"rowState" | "isModified" | "editable" | "onEdit" | "onResetCell" | "driver" | "sort" | "onSort" | "rowMenu"
| "rowState"
| "isModified"
| "editable"
| "onEdit"
| "onResetCell"
| "driver"
| "sort"
| "onSort"
| "rowMenu"
| "initialScrollLeft"
| "onHorizontalScroll"
> {
columns: readonly GridColumn[];
rowCount: number;
@@ -238,6 +248,8 @@ export function DataView(props: DataViewProps) {
onSelectionChange={setRange}
onFilter={(col, anchor) => setFilterAt({ col, anchor })}
filtered={(col) => filter.has(col)}
initialScrollLeft={props.initialScrollLeft}
onHorizontalScroll={props.onHorizontalScroll}
/>
{filter.size > 0 && (
<div className={styles.filterPill} role="status">
+14
Переглянути файл
@@ -98,6 +98,10 @@ export interface GridProps {
onFind?: () => void;
/** Go to Column: a new object selects that column's cell in the current row, scrolls to it and focuses the grid. */
revealColumn?: { col: number } | null;
/** Horizontal scroll offset to restore on mount, when a caller keeps view state across mounts. */
initialScrollLeft?: number;
/** Reports horizontal scroll changes to a caller that keeps view state across mounts. */
onHorizontalScroll?: (left: number) => void;
"aria-label"?: string;
}
@@ -254,6 +258,15 @@ export function Grid(props: GridProps) {
}, [revealColumn]);
const totalWidth = useMemo(() => numberWidth + widths.reduce((a, b) => a + b, 0), [numberWidth, widths]);
const template = `${numberWidth}px ${widths.map((w) => `${w}px`).join(" ")}`;
// Retried as columns are measured, until the content is wide enough to reach the offset.
const pendingScrollLeft = useRef(props.initialScrollLeft);
useLayoutEffect(() => {
const el = scrollRef.current;
const left = pendingScrollLeft.current;
if (!el || !left) return;
el.scrollLeft = left;
if (el.scrollLeft >= left - 1) pendingScrollLeft.current = undefined;
}, [totalWidth]);
const selected = (r: number, c: number) => {
if (!sel) return false;
@@ -605,6 +618,7 @@ export function Grid(props: GridProps) {
pointerFocus.current = true;
setTimeout(() => (pointerFocus.current = false));
}}
onScroll={(e) => props.onHorizontalScroll?.(e.currentTarget.scrollLeft)}
onPaste={onPaste}
onContextMenu={onContextMenu}
>
+22 -1
Переглянути файл
@@ -48,6 +48,7 @@ interface TableViewState {
sort: DbSortKey[];
filterText: string;
filter: string;
horizontalScrollLeft: number;
}
const MAX_VIEW_STATES = 100;
@@ -72,10 +73,28 @@ export function TableEditor({ input }: { input: EditorInput }) {
const [sort, setSort] = useState<DbSortKey[]>(initial?.sort ?? []);
const [filterText, setFilterText] = useState(initial?.filterText ?? "");
const [filter, setFilter] = useState(initial?.filter ?? "");
// A ref, not state: scrolling must not re-render the editor.
const scrollLeft = useRef(initial?.horizontalScrollLeft ?? 0);
useEffect(
() => rememberViewState(input.key, { offset, limit, sort, filterText, filter }),
() =>
rememberViewState(input.key, {
offset,
limit,
sort,
filterText,
filter,
horizontalScrollLeft: scrollLeft.current,
}),
[input.key, offset, limit, sort, filterText, filter],
);
const onHorizontalScroll = useCallback(
(left: number) => {
scrollLeft.current = left;
const state = viewStates.get(input.key);
if (state) state.horizontalScrollLeft = left;
},
[input.key],
);
const [nonce, setNonce] = useState(0);
const [edits, setEdits] = useState<PendingEdits>(emptyEdits);
const [panel, setPanel] = useState<DataPanel | null>(null);
@@ -432,6 +451,8 @@ export function TableEditor({ input }: { input: EditorInput }) {
driver={source?.driver}
sort={sort}
onSort={onSort}
initialScrollLeft={scrollLeft.current}
onHorizontalScroll={onHorizontalScroll}
pager={
<Toolbar className={styles.resultPager} aria-label="Table pages">
{!singlePage && (
+10 -3
Переглянути файл
@@ -112,6 +112,7 @@ const TEMPLATE_CONTEXT_KEY = "openideaTemplateContexts";
import { formatElapsed } from "./resultView";
import { SQL_LANGUAGE } from "./sqlLanguage";
import { jdbcDialect } from "./vendors";
export { SQL_LANGUAGE };
const ROW_LIMITS = ["100", "500", "1000", "5000", "50000"];
@@ -343,18 +344,20 @@ async function executeRange(view: EditorView, path: string, from: number, to: nu
const token = ++nextExecution;
const sent = view.state.doc;
const start = (statements: readonly SqlStatement[]) => {
const st = view.state.field(runField, false);
// The offsets are into the text sent; an edit since (while asking for parameters) leaves them unplaced.
if (view.state.doc !== sent) return;
if (!st || view.state.doc !== sent) return;
const spans = statements.map((st) => ({ from: st.from, to: st.to }));
const last = spans.at(-1);
if (!last) return;
const at = view.state.sliceDoc(last.to, last.to + 1) === ";" ? last.to + 1 : last.to;
const executing = { token, sent: spans, spans, at, startedAt: Date.now() };
view.dispatch({ effects: setRun.of({ ...view.state.field(runField), executing }) });
view.dispatch({ effects: setRun.of({ ...st, executing }) });
};
try {
const outcomes = await executeConsole(path, sent.toString(), from, to, start);
if (outcomes.length) markOutcomes(view, placed(view.state.field(runField).executing, token, outcomes));
const st = view.state.field(runField, false);
if (st && outcomes.length) markOutcomes(view, placed(st.executing, token, outcomes));
} finally {
const st = view.state.field(runField, false);
if (st?.executing?.token === token) view.dispatch({ effects: setRun.of({ ...st, executing: null }) });
@@ -1067,6 +1070,9 @@ export function completionSource(path: string, sql: SqlText = WHOLE_FILE): Compl
const current = id ? databaseRequest(id) : projectRequest();
const source = sourceById(id);
const driver: DbDriver = source?.driver ?? "sqlite";
// A custom JDBC source (`driver: "jdbc"`) says nothing about how its server folds
// identifiers; its URL does (`jdbc:oracle:thin:@…`). Quoting follows that dialect.
const dialect = driver === "jdbc" ? jdbcDialect(source?.url) : null;
const model = id ? (useDatabase.getState().completion[id] ?? null) : null;
if (id && !model) void loadCompletion(id);
// Unqualified names resolve in the console's active schema (IDEA's schema dropdown).
@@ -1089,6 +1095,7 @@ export function completionSource(path: string, sql: SqlText = WHOLE_FILE): Compl
model: scoped,
analysis,
driver,
dialect,
sourceName: source?.name ?? undefined,
catalog: cataloged ? catalogOf(id) : undefined,
});
+34 -1
Переглянути файл
@@ -3,7 +3,7 @@ import { EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { useProject } from "@/platform/project";
import { consoleExtension, executeScriptInView } from "./console";
import { consoleExtension, executeInView, executeScriptInView } from "./console";
import { SQL_LANGUAGE } from "./sqlLanguage";
import { executeConsole, rerunResult, useDatabase } from "./store";
import { provideToolWindowService } from "@/workbench/contributions";
@@ -138,6 +138,39 @@ describe("In-Editor Results", () => {
});
describe("statements in flight", () => {
it("runs SQL from a read-only editor without leaving execution progress behind", async () => {
useProject.setState({ settings: {} as never });
const view = new EditorView({
parent: document.body,
state: EditorState.create({
doc: "SELECT 1;",
extensions: [
EditorState.readOnly.of(true),
consoleExtension({ language: SQL_LANGUAGE, path: PATH, readOnly: true } as never),
],
}),
});
try {
await executeInView(view, PATH);
const { results, running, executions } = useDatabase.getState();
expect(results[0]?.outcome.result?.rows).toEqual([["SELECT 1 #1"]]);
expect(running).toEqual({});
expect(executions).toEqual({});
} finally {
view.destroy();
}
});
it("clears execution progress if setting up editor marks fails", async () => {
const outcomes = await executeConsole(PATH, "SELECT 1;", 0, 0, () => {
throw new Error("Could not set up editor marks");
});
expect(outcomes).toEqual([]);
const { running, executions } = useDatabase.getState();
expect(running).toEqual({});
expect(executions).toEqual({});
});
it("marks what was submitted with its running time, then the outcome", async () => {
const parent = document.createElement("div");
document.body.append(parent);
+28 -12
Переглянути файл
@@ -63,20 +63,26 @@ export function shouldAutoCompleteSql(analysis: Analysis): boolean {
const MAX_ALL_COLUMNS = 3000;
/** `name`, quoted when the dialect needs it (case, characters, reserved words). */
export function quoteIdent(name: string, driver: DbDriver): string {
/**
* `name`, quoted when the dialect needs it (case, characters, reserved words).
* A `jdbc` source quotes by the dialect its URL speaks (`dialect`); without one, only
* what is not a plain word is quoted, which is right for the dialects that fold case
* neither way.
*/
export function quoteIdent(name: string, driver: DbDriver, dialect?: DbDriver | null): string {
const d = driver === "jdbc" && dialect ? dialect : driver;
const plain =
driver === "postgres"
d === "postgres"
? /^[a-z_][a-z0-9_$]*$/
: // Oracle and Snowflake fold unquoted names to upper case; a lower-case name must stay quoted.
driver === "oracle" || driver === "snowflake"
d === "oracle" || d === "snowflake"
? /^[A-Z_][A-Z0-9_$]*$/
: driver === "clickhouse"
: d === "clickhouse"
? /^[A-Za-z_][A-Za-z0-9_]*$/
: /^[A-Za-z_][A-Za-z0-9_$]*$/;
if (plain.test(name) && !isReserved(name, driver)) return name;
if (driver === "clickhouse") return `"${name.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
const q = driver === "mysql" ? "`" : '"';
if (plain.test(name) && !isReserved(name, d)) return name;
if (d === "clickhouse") return `"${name.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
const q = d === "mysql" ? "`" : '"';
return q + name.split(q).join(q + q) + q;
}
@@ -121,11 +127,20 @@ export interface CompletionInput {
model: DbCompletion | null;
analysis: Analysis;
driver: DbDriver;
/** The dialect a `jdbc` source speaks, from its URL (`jdbcDialect`); quoting follows it. */
dialect?: DbDriver | null;
/** Data source name, shown next to tables like IDEA does. */
sourceName?: string;
}
export function sqlCandidates({ model, analysis: a, driver, sourceName, catalog }: CompletionInput): SqlCandidate[] {
export function sqlCandidates({
model,
analysis: a,
driver,
dialect,
sourceName,
catalog,
}: CompletionInput): SqlCandidate[] {
const eq = nameMatcher(driver);
const ctx = a.context;
if (ctx.kind === "none") return [];
@@ -135,7 +150,7 @@ export function sqlCandidates({ model, analysis: a, driver, sourceName, catalog
const kw = (k: string) => (lower ? k.toLowerCase() : k);
const tables = model?.tables ?? [];
const defaultSchema = model?.defaultSchema ?? "";
const exact = (n: string) => quoteIdent(n, driver);
const exact = (n: string) => quoteIdent(n, driver, dialect);
// Snowflake folds unquoted names to upper case, so a name typed in lower case may stay lower case.
const lowerQualifier = !!a.qualifier?.length && a.qualifier.every((p) => /[a-z]/.test(p) && p === p.toLowerCase());
// What is typed decides: the name's own prefix, else the qualifier before it, else the statement's keywords.
@@ -270,7 +285,7 @@ export function sqlCandidates({ model, analysis: a, driver, sourceName, catalog
case "table": {
const taken = new Set(a.refs.flatMap((r) => [refName(r).toLowerCase(), r.name.toLowerCase()]));
if (ctx.join) out.push(...joinCandidates(a, model, driver, taken, kw));
if (ctx.join) out.push(...joinCandidates(a, model, driver, dialect, taken, kw));
for (const c of a.ctes) out.push({ label: c.name, kind: "table", tail: "(CTE)", boost: 40 });
const schemas = new Set<string>();
for (const t of tables) {
@@ -472,13 +487,14 @@ function joinCandidates(
a: Analysis,
model: DbCompletion | null,
driver: DbDriver,
dialect: DbDriver | null | undefined,
taken: Set<string>,
kw: Kw,
): SqlCandidate[] {
if (!model) return [];
const eq = nameMatcher(driver);
const out: SqlCandidate[] = [];
const q = (n: string) => quoteIdent(n, driver);
const q = (n: string) => quoteIdent(n, driver, dialect);
const seen = new Set<string>();
const local = (s: string) => eq(s, model.defaultSchema) || driver === "sqlite";
const tableText = (schema: string, name: string) => (local(schema) ? q(name) : `${q(schema)}.${q(name)}`);
+46
Переглянути файл
@@ -8,6 +8,7 @@ import { identName, inLiteral, lex } from "./lexer";
import { DATA_TYPES, statementStarters } from "./dialect";
import { bindParams, findParams } from "./params";
import { SqlResolver } from "./resolve";
import { jdbcDialect } from "../vendors";
const col = (name: string, dataType = "INTEGER", primaryKey = false, hasDefault = false) => ({
name,
@@ -280,6 +281,51 @@ describe("completion candidates", () => {
expect(quoteIdent('a"b', "oracle")).toBe('"a""b"');
});
it("quotes a custom JDBC source's names by the dialect its URL speaks", () => {
expect(jdbcDialect("jdbc:oracle:thin:@//db.local:1521/ORCL")).toBe("oracle");
expect(jdbcDialect("JDBC:Oracle:thin:@db:1521:ORCL")).toBe("oracle");
expect(jdbcDialect("jdbc:postgresql://db.local/shop")).toBe("postgres");
expect(jdbcDialect("jdbc:MariaDB://db/shop")).toBe("mysql");
expect(jdbcDialect("jdbc:sqlserver://db;databaseName=shop")).toBe("sqlServer");
expect(jdbcDialect("jdbc:unknown://db/shop")).toBeNull();
expect(jdbcDialect("")).toBeNull();
expect(jdbcDialect(null)).toBeNull();
// Oracle folds unquoted names to upper case, so only an upper-case name stays bare.
expect(quoteIdent("MyTable", "jdbc", "oracle")).toBe('"MyTable"');
expect(quoteIdent("MYTABLE", "jdbc", "oracle")).toBe("MYTABLE");
expect(quoteIdent("mytable", "jdbc", "oracle")).toBe('"mytable"');
// Without a dialect, a plain word still stays bare: the source never said which server it is.
expect(quoteIdent("MyTable", "jdbc")).toBe("MyTable");
expect(quoteIdent("MyTable", "jdbc", null)).toBe("MyTable");
const hr: DbCompletion = {
defaultSchema: "HR",
tables: [
{
schema: "HR",
name: "MyTable",
kind: "table",
columns: [col("ID", "NUMBER", true), col("fullName", "VARCHAR2")],
},
],
foreignKeys: [],
};
const tables = sqlCandidates({
model: hr,
analysis: at("SELECT * FROM |", "jdbc"),
driver: "jdbc",
dialect: jdbcDialect("jdbc:oracle:thin:@//db.local:1521/ORCL"),
});
expect(tables.find((c) => c.label === "MyTable")?.insert).toBe('"MyTable"');
const columns = sqlCandidates({
model: hr,
analysis: at("SELECT | FROM MyTable", "jdbc"),
driver: "jdbc",
dialect: "oracle",
});
expect(columns.find((c) => c.label === "ID")?.insert).toBe("ID");
expect(columns.find((c) => c.label === "fullName")?.insert).toBe('"fullName"');
});
it("offers Snowflake vocabulary and quotes names the server folds to upper case", () => {
expect(statementStarters("snowflake")).toEqual(
expect.arrayContaining([
+1 -1
Переглянути файл
@@ -1281,8 +1281,8 @@ export async function executeConsole(
running: { ...s.running, [path]: request },
executions: { ...s.executions, [path]: { startedAt: Date.now(), statements: statements.length } },
}));
onStart?.(statements);
try {
onStart?.(statements);
// IDEA brings the results up as the run starts, showing it executing.
if (!inEditorResults()) showServiceView(RESULTS_VIEW, false);
const pageSize = useDatabase.getState().maxRows;
+16
Переглянути файл
@@ -224,6 +224,22 @@ it("omits a reset inserted cell from Submit instead of writing SQL NULL", async
});
describe("table editor view state", () => {
it("restores the grid's horizontal scroll position when its tab mounts again (#4775)", async () => {
const input = tableInput("source", "default", "users");
let view!: ReturnType<typeof render>;
await act(async () => {
view = render(<TableEditor input={input} />);
});
const grid = await screen.findByRole("grid");
grid.scrollLeft = 180;
fireEvent.scroll(grid);
view.unmount();
await act(async () => {
render(<TableEditor input={input} />);
});
expect((await screen.findByRole("grid")).scrollLeft).toBe(180);
});
it("queries with the sort it had when its tab mounts again", async () => {
const input = tableInput("source", "default", "users");
let view!: ReturnType<typeof render>;
+9
Переглянути файл
@@ -176,6 +176,15 @@ const SCHEMES: Record<string, string> = {
export const vendorOfScheme = (scheme: string): DbVendor | undefined => BY_ID.get(SCHEMES[scheme.toLowerCase()] ?? "");
/**
* The dialect a custom JDBC source's URL speaks (`jdbc:oracle:thin:@//db:1521/ORCL` → `oracle`):
* its `driver: "jdbc"` says nothing about how the server folds identifiers.
*/
export function jdbcDialect(url: string | null | undefined): DbDriver | null {
const scheme = /^(?:jdbc:)?([a-z][a-z0-9]*):/i.exec((url ?? "").trim())?.[1] ?? "";
return vendorOfScheme(scheme)?.driver ?? null;
}
const bracketed = (host: string) => (host.includes(":") && !host.startsWith("[") ? `[${host}]` : host);
/** The JDBC URL of a data source's fields (the General tab's URL preview). */
+26 -1
Переглянути файл
@@ -10,7 +10,15 @@ import {
updateBreakpoint,
useBreakpoints,
} from "../breakpoints/store";
import { adoptSession, useExecutionPoint, useDebug, handleDebugEvent, type DebugSession } from "../state";
import {
adoptSession,
selectSession,
stopTarget,
useExecutionPoint,
useDebug,
handleDebugEvent,
type DebugSession,
} from "../state";
import { getContext } from "@/platform/context";
import styles from "../editor/editor.module.css";
@@ -314,6 +322,23 @@ describe("session events", () => {
expect(getContext().debugSessionActive).toBe(false);
});
it("enables Stop for the selected session tab only (#4738)", () => {
adoptSession(80, { name: "server" });
adoptSession(81, { name: "client" });
selectSession(80);
expect(getContext().debugCanStop).toBe(true);
expect(stopTarget()?.id).toBe(80);
handleDebugEvent(81, { kind: "terminated" });
selectSession(81);
// The finished session's tab: Stop is off although the server still runs.
expect(getContext().debugSessionActive).toBe(true);
expect(getContext().debugCanStop).toBe(false);
expect(stopTarget()).toBeNull();
selectSession(80);
expect(getContext().debugCanStop).toBe(true);
handleDebugEvent(80, { kind: "terminated" });
});
it("ignores sessions this window did not start, but adopts children of its own", async () => {
vi.spyOn(console, "warn").mockImplementation(() => {});
adoptSession(90, { name: "app", adapter: "js-debug" });
+3 -2
Переглянути файл
@@ -79,6 +79,7 @@ import {
startPreparedSession,
stopSession,
stopAssociatedProcess,
stopTarget,
useDebug,
type DebugSession,
} from "./state";
@@ -560,9 +561,9 @@ export function registerDebugActions(): () => void {
title: "Stop",
category: "Debug",
icon: "stop",
when: "debugSessionActive",
when: "debugCanStop",
run: () => {
const s = activeSession() ?? Object.values(useDebug.getState().sessions).find(isLive);
const s = stopTarget();
if (s) void stopSession(s.id);
},
},
+9
Переглянути файл
@@ -197,6 +197,13 @@ export function isLive(s: DebugSession | null | undefined): boolean {
return !!s && s.status !== "terminated";
}
/** The session the Debug tool window's Stop acts on: the selected one while it runs (any live one when none is selected). */
export function stopTarget(): DebugSession | null {
const s = activeSession();
if (s) return isLive(s) ? s : null;
return Object.values(useDebug.getState().sessions).find(isLive) ?? null;
}
/** Whether the session with this id is still there and running, as of now. */
export const isLiveSession = (id: DebugSessionId) => isLive(useDebug.getState().sessions[id]);
@@ -405,6 +412,8 @@ export function publishContext() {
});
const anyLive = Object.values(useDebug.getState().sessions).some(isLive);
setContext("debugSessionActive", anyLive);
// Stop acts on the selected session tab, so a finished one doesn't stop another session.
setContext("debugCanStop", !!stopTarget());
setContext("debugSessionRunning", s?.status === "running");
setContext("debugSessionPaused", s?.status === "paused");
// Dart and Flutter sessions: Hot Reload / Hot Restart.
+116
Переглянути файл
@@ -0,0 +1,116 @@
import { indentUnit } from "@codemirror/language";
import { EditorState } from "@codemirror/state";
import { describe, expect, it } from "vitest";
import { formatJsonBody, httpBodyFormatter } from "./bodyFormat";
describe("formatJsonBody", () => {
it("indents objects and arrays and keeps values as written", () => {
expect(formatJsonBody('{"id":12345678901234567890,"tags":["a","b"],"meta":{},"list":[],"ok":true}', " ")).toBe(
[
"{",
' "id": 12345678901234567890,',
' "tags": [',
' "a",',
' "b"',
" ],",
' "meta": {},',
' "list": [],',
' "ok": true',
"}",
].join("\n"),
);
});
it("keeps {{variables}} as values, quoted or not", () => {
expect(formatJsonBody('{"user":{{userId}},"name":"{{name}}", "n": {{base}}-1}', " ")).toBe(
["{", ' "user": {{userId}},', ' "name": "{{name}}",', ' "n": {{base}}-1', "}"].join("\n"),
);
});
it("keeps escaped quotes and structural characters inside strings", () => {
expect(formatJsonBody('{"q":"a \\"b\\" {c}, [d]: e"}', " ")).toBe('{\n "q": "a \\"b\\" {c}, [d]: e"\n}');
});
it("leaves text that isn't one JSON value alone", () => {
for (const text of ['{"a":1', '{"a":1}}', '{"a" 1}', "{a:1}", '{"a":1} {"b":2}', "[1,]", "name=value"])
expect(formatJsonBody(text, " ")).toBeNull();
});
});
describe("Reformat Code in .http files (#4727)", () => {
const blocksOf = (text: string) => {
const lines = text.split("\n");
const out: Array<{ line: number; endLine: number }> = [];
lines.forEach((l, i) => {
if (/^(GET|POST|PUT|PATCH|DELETE) /.test(l)) out.push({ line: i, endLine: lines.length - 1 });
});
out.forEach((b, i) => {
const next = out[i + 1];
if (next) b.endLine = next.line - 2;
});
return out;
};
const format = (text: string, range: { from: number; to: number } | null = null) => {
const state = EditorState.create({ doc: text, extensions: [indentUnit.of(" ")] });
const changes = httpBodyFormatter(() => blocksOf(text))(state, range);
return state.update({ changes }).state.doc.toString();
};
it("formats JSON bodies after the headers and keeps the rest of the request", () => {
const text = [
"POST https://example.com/api/users",
" ?debug=true",
"Content-Type: application/json",
"Authorization: Bearer {{token}}",
"",
'{"name":"Ann","roles":["admin"],"id":{{id}}}',
"",
"> {%",
' client.global.set("id", response.body.id);',
"%}",
"",
"###",
"GET https://example.com/api/users/1",
].join("\n");
expect(format(text)).toBe(
[
"POST https://example.com/api/users",
" ?debug=true",
"Content-Type: application/json",
"Authorization: Bearer {{token}}",
"",
"{",
' "name": "Ann",',
' "roles": [',
' "admin"',
" ],",
' "id": {{id}}',
"}",
"",
"> {%",
' client.global.set("id", response.body.id);',
"%}",
"",
"###",
"GET https://example.com/api/users/1",
].join("\n"),
);
});
it("leaves bodies of other content types, form bodies and file inputs alone", () => {
for (const text of [
'POST https://example.com\nContent-Type: text/plain\n\n{"a":1}',
"POST https://example.com\nContent-Type: application/x-www-form-urlencoded\n\na=1&b=2",
"POST https://example.com\nContent-Type: application/json\n\n< ./body.json",
])
expect(format(text)).toBe(text);
});
it("formats only the bodies a selection touches", () => {
const one = 'POST https://example.com/a\n\n{"a":1}';
const two = 'POST https://example.com/b\n\n{"b":2}';
const text = `${one}\n\n###\n${two}`;
const from = text.indexOf('{"b"');
expect(format(text, { from, to: from + 3 })).toBe(`${one}\n\n###\nPOST https://example.com/b\n\n{\n "b": 2\n}`);
});
});
+139
Переглянути файл
@@ -0,0 +1,139 @@
/**
* Reformat Code in `.http` files: JSON request bodies are re-indented. `{{variables}}` and
* number literals stay as written, so a body that is only JSON once its variables are
* substituted is formatted too.
*/
import { getIndentUnit } from "@codemirror/language";
import type { EditorState } from "@codemirror/state";
import type { ContributedFormatter } from "@/editor/api";
interface Block {
/** 0-based request line. */
line: number;
/** 0-based last line of the block (inclusive). */
endLine: number;
}
type Token = { kind: "punct"; text: "{" | "}" | "[" | "]" | ":" | "," } | { kind: "value"; text: string };
/** Values (strings, numbers, literals, `{{variables}}`) and punctuation; `null` when it can't be JSON. */
function tokenize(text: string): Token[] | null {
const out: Token[] = [];
let i = 0;
while (i < text.length) {
const c = text[i]!;
if (/\s/.test(c)) {
i++;
} else if (text.startsWith("{{", i)) {
const end = text.indexOf("}}", i + 2);
if (end < 0) return null;
// A variable glued to more text (`{{base}}-1`) stays one value.
let j = end + 2;
while (j < text.length && !/[\s{}[\]:,"]/.test(text[j]!)) j++;
out.push({ kind: "value", text: text.slice(i, j) });
i = j;
} else if (c === '"') {
let j = i + 1;
while (j < text.length && text[j] !== '"') j += text[j] === "\\" ? 2 : 1;
if (j >= text.length) return null;
out.push({ kind: "value", text: text.slice(i, j + 1) });
i = j + 1;
} else if ("{}[]:,".includes(c)) {
out.push({ kind: "punct", text: c as "{" });
i++;
} else {
let j = i;
while (j < text.length && !/[\s{}[\]:,"]/.test(text[j]!)) j++;
const word = text.slice(i, j);
if (!/^(-?\d|true$|false$|null$)/.test(word)) return null;
out.push({ kind: "value", text: word });
i = j;
}
}
return out;
}
/** `text` as indented JSON (empty `{}` / `[]` stay inline), or `null` when it isn't one JSON value. */
export function formatJsonBody(text: string, indent: string): string | null {
const tokens = tokenize(text);
if (!tokens?.length) return null;
let i = 0;
const value = (depth: number): string | null => {
const t = tokens[i++];
if (!t) return null;
if (t.kind === "value") return t.text;
if (t.text !== "{" && t.text !== "[") return null;
const object = t.text === "{";
const close = object ? "}" : "]";
if (tokens[i]?.text === close) {
i++;
return object ? "{}" : "[]";
}
const pad = indent.repeat(depth + 1);
const items: string[] = [];
for (;;) {
let key = "";
if (object) {
const k = tokens[i++];
if (k?.kind !== "value" || tokens[i++]?.text !== ":") return null;
key = `${k.text}: `;
}
const v = value(depth + 1);
if (v === null) return null;
items.push(pad + key + v);
const sep = tokens[i++];
if (sep?.text === close) break;
if (sep?.text !== ",") return null;
}
return `${t.text}\n${items.join(",\n")}\n${indent.repeat(depth)}${close}`;
};
const out = value(0);
return out !== null && i === tokens.length ? out : null;
}
const HANDLER_OR_INPUT = /^(> \{%|<>|>>|> |< )/;
/** The body lines of the request at `block`: after its headers, up to a response handler or reference. */
function bodyRange(state: EditorState, block: Block): { from: number; to: number; json: boolean } | null {
const doc = state.doc;
const last = Math.min(block.endLine + 1, doc.lines);
let n = block.line + 2;
// Indented query continuation lines, then headers up to the first blank line.
while (n <= last && /^[ \t]+[?&/]/.test(doc.line(n).text)) n++;
let contentType: string | null = null;
for (; n <= last; n++) {
const text = doc.line(n).text;
if (!text.trim()) break;
const m = /^([^\s:]+)\s*:(.*)$/.exec(text);
if (m && m[1]!.toLowerCase() === "content-type") contentType = m[2]!.trim().toLowerCase();
}
let first = 0;
let end = 0;
for (n++; n <= last; n++) {
const text = doc.line(n).text;
if (HANDLER_OR_INPUT.test(text.trimStart())) break;
if (!text.trim()) continue;
if (!first) first = n;
end = n;
}
if (!first) return null;
const json = contentType === null || contentType.includes("json");
return { from: doc.line(first).from, to: doc.line(end).to, json };
}
/** Reformat Code for the JSON bodies of `blocks` that overlap `range` (all when `null`). */
export function httpBodyFormatter(blocks: (state: EditorState) => readonly Block[]): ContributedFormatter {
return (state, range) => {
const indent = " ".repeat(getIndentUnit(state));
const changes: Array<{ from: number; to: number; insert: string }> = [];
for (const block of blocks(state)) {
const body = bodyRange(state, block);
if (!body?.json || (range && (body.to < range.from || body.from > range.to))) continue;
const text = state.sliceDoc(body.from, body.to);
if (!/^[{[]/.test(text.trimStart())) continue;
const formatted = formatJsonBody(text, indent);
if (formatted !== null && formatted !== text) changes.push({ from: body.from, to: body.to, insert: formatted });
}
return changes;
};
}
+6 -2
Переглянути файл
@@ -3,11 +3,11 @@
* (like run configurations' gutter) and a toolbar panel above the text with
* the environment selector, Run All and Stop.
*/
import { RangeSet, StateEffect, StateField, type EditorState, type Extension } from "@codemirror/state";
import { EditorState, RangeSet, StateEffect, StateField, type Extension } from "@codemirror/state";
import { EditorView, GutterMarker, ViewPlugin, gutter, showPanel, type Panel, type ViewUpdate } from "@codemirror/view";
import { useEffect } from "react";
import { createRoot } from "react-dom/client";
import { mapLineStart, type EditorDocContext } from "@/editor/api";
import { CONTRIBUTED_FORMAT, mapLineStart, type EditorDocContext } from "@/editor/api";
import { shortcutLabel } from "@/platform/keymap";
import { isVirtualUri } from "@/platform/virtualDocs";
import type { HttpRequestBlock } from "@/platform/ipc";
@@ -23,6 +23,7 @@ import {
setEnvironment,
useHttpClient,
} from "./store";
import { httpBodyFormatter } from "./bodyFormat";
import styles from "./HttpClient.module.css";
export const HTTP_LANGUAGE = "http";
@@ -209,8 +210,11 @@ export function httpEditorExtension(ctx: EditorDocContext): Extension {
}
},
);
// Reformat Code: JSON request bodies (the blocks as last parsed).
const format = httpBodyFormatter((state) => state.field(requestsField, false) ?? []);
return [
requestsField,
EditorState.languageData.of(() => [{ [CONTRIBUTED_FORMAT]: format }]),
detector,
curlPaste,
showPanel.of(toolbarPanel(path)),
+104
Переглянути файл
@@ -0,0 +1,104 @@
/**
* IntelliJ's bundled Darcula editor scheme (`DefaultColorSchemesManager.xml`) as `convertIcls` reads it.
* A theme's `.icls` with `parent_scheme="Darcula"` lists only what differs, and takes the rest from here.
*/
export const DARCULA_TOKENS: Readonly<Record<string, string>> = {
"--gutter-added": "#384c38",
"--gutter-modified": "#374752",
"--gutter-deleted": "#656e76",
"--caret": "#bbbbbb",
"--bg-current-line": "#323232",
"--bg-console": "#2b2b2b",
"--vcs-added": "#629755",
"--vcs-deleted": "#6c6c6c",
"--vcs-ignored": "#848504",
"--vcs-conflict": "#d5756c",
"--vcs-modified": "#6897bb",
"--vcs-untracked": "#d1675a",
"--border-indent-guide": "#373737",
"--fg-line-number": "#606366",
"--fg-line-number-current": "#a4a3a3",
"--border-method-separator": "#4d4d4d",
"--border-right-margin": "#4d4d4d",
"--border-indent-guide-active": "#505050",
"--bg-editor-selection": "#214283",
"--fg-whitespace": "#606060",
"--bg-breakpoint-line": "#3a2323",
"--ansi-black": "#000000",
"--terminal-ansi-black": "#000000",
"--ansi-blue": "#3993d4",
"--terminal-ansi-blue": "#3993d4",
"--ansi-bright-blue": "#1fb0ff",
"--terminal-ansi-bright-blue": "#1fb0ff",
"--ansi-cyan": "#00a3a3",
"--terminal-ansi-cyan": "#00a3a3",
"--ansi-bright-cyan": "#00e5e5",
"--terminal-ansi-bright-cyan": "#00e5e5",
"--ansi-bright-black": "#595959",
"--terminal-ansi-bright-black": "#595959",
"--ansi-white": "#808080",
"--terminal-ansi-white": "#808080",
"--ansi-green": "#5c962c",
"--terminal-ansi-green": "#5c962c",
"--ansi-bright-green": "#4fc414",
"--terminal-ansi-bright-green": "#4fc414",
"--ansi-magenta": "#a771bf",
"--terminal-ansi-magenta": "#a771bf",
"--ansi-bright-magenta": "#ed7eed",
"--terminal-ansi-bright-magenta": "#ed7eed",
"--ansi-red": "#f0524f",
"--terminal-ansi-red": "#f0524f",
"--ansi-bright-red": "#ff4050",
"--terminal-ansi-bright-red": "#ff4050",
"--ansi-bright-white": "#ffffff",
"--terminal-ansi-bright-white": "#ffffff",
"--ansi-yellow": "#a68a0d",
"--terminal-ansi-yellow": "#a68a0d",
"--ansi-bright-yellow": "#e5bf00",
"--terminal-ansi-bright-yellow": "#e5bf00",
"--syn-inline-value": "#666d75",
"--syn-constant": "#9876aa",
"--syn-doc-comment": "#629755",
"--syn-doc-comment-tag": "#629755",
"--syn-doc-markup": "#77b767",
"--syn-function-call": "#a9b7c6",
"--syn-function": "#ffc66d",
"--syn-variable": "#a9b7c6",
"--syn-property": "#9876aa",
"--syn-keyword": "#cc7832",
"--syn-comment": "#808080",
"--syn-annotation": "#bbb529",
"--syn-decorator": "#bbb529",
"--syn-number": "#6897bb",
"--syn-punct": "#a9b7c6",
"--syn-string": "#6a8759",
"--syn-escape": "#cc7832",
"--diff-conflict-stripe": "#8f5247",
"--diff-deleted": "#484a4a",
"--diff-deleted-stripe": "#656e76",
"--diff-inserted": "#294436",
"--diff-inserted-stripe": "#447152",
"--diff-modified": "#385570",
"--diff-modified-stripe": "#43698d",
"--syn-doc-comment-tag-value": "#8a653b",
"--wave-error": "#bc3f3c",
"--fg-fold-placeholder": "#8c8c8c",
"--bg-fold-placeholder": "#3a3a3a",
"--bg-identifier-under-caret": "#344134",
"--fg-inlay": "#787878",
"--bg-inlay": "#3b3b3b",
"--bg-matched-brace": "#3b514d",
"--fg-unused": "#72737a",
"--bg-search-result": "#155221",
"--fg-editor": "#a9b7c6",
"--bg-editor": "#2b2b2b",
"--bg-text-search-result": "#32593d",
"--syn-todo": "#a8c023",
"--bg-identifier-under-caret-write": "#40332b",
"--syn-rainbow-1": "#be7070",
"--syn-rainbow-2": "#3d7676",
"--syn-rainbow-3": "#be9970",
"--syn-rainbow-4": "#9d527c",
"--editor-error-decoration": "underline wavy #bc3f3c",
"--bg-editor-gutter": "#2b2b2b",
};
+9 -1
Переглянути файл
@@ -4,11 +4,13 @@
* plugin into an OpenIDEA theme plugin package. The mapping covers the main
* keys only; anything unmapped keeps the built-in value of the base (`kind`).
*
* Pure functions without imports: Settings › Plugins › Import IntelliJ Theme
* Pure functions, importing only data: Settings › Plugins › Import IntelliJ Theme
* uses them on what the host read from the plugin (`plugin_read_intellij_theme`),
* and so does the command line (`scripts/theme/import-intellij-theme.ts`).
*/
import { DARCULA_TOKENS } from "./intellijDarcula.ts";
/** OpenIDEA token ← IntelliJ `ui` keys, first present wins. `*.prop` wildcards apply too. */
export const UI_KEYS: Record<string, string[]> = {
"--bg-app": ["Panel.background"],
@@ -358,6 +360,12 @@ export function convertIcls(xml: string): { name: string; dark: boolean | null;
tokens["--syn-comment-style"] = Number(parts.get("FONT_TYPE")) & 2 ? "italic" : "normal";
}
}
if (parent === "Darcula") {
// IntelliJ replaces a parent's attribute as a whole: what the file names, even empty or by baseAttributes, wins.
const keys = [...body.matchAll(/<option name="([^"]+)"/g)].map((m) => m[1]!);
const own = new Set(keys.flatMap((key) => (ICLS_ATTRIBUTES[key] ?? []).map(([, t]) => t)));
for (const [token, value] of Object.entries(DARCULA_TOKENS)) if (!own.has(token)) tokens[token] ??= value;
}
if (tokens["--wave-error"]) tokens["--editor-error-decoration"] = `underline wavy ${tokens["--wave-error"]}`;
if (tokens["--bg-editor"]) tokens["--bg-editor-gutter"] ??= tokens["--bg-editor"];
return { name, dark, tokens };
+12
Переглянути файл
@@ -36,6 +36,7 @@ import {
} from "./operations";
import { nameOf, parentOf } from "./paths";
import { showFilePathPopup } from "./filePath";
import { canDownload, downloadTo } from "./download";
import { showNewPopup, treeHandle } from "./ProjectView";
import { lastFileRefactoring, undoFileRefactoring } from "./fileRefactor";
import {
@@ -412,6 +413,17 @@ export function registerProjectActions(): () => void {
keywords: ["show in explorer", "open in finder"],
run: ({ arg }) => revealInFinder(nodesFrom(contextTarget(arg))),
},
{
id: "project.downloadTo",
title: "Download to…",
category: "Project View",
icon: "download",
when: OPEN,
enabled: () => canDownload(),
description: "Copy the selected files and folders of a remote project to a folder on this computer",
keywords: ["save to local", "copy to local", "scp", "remote"],
run: ({ arg }) => downloadTo(nodesFrom(contextTarget(arg)).map((n) => n.path)),
},
{
id: "project.openWithAssociatedApp",
title: "Open in Associated Application",
+16
Переглянути файл
@@ -215,6 +215,22 @@ describe("project view context menu", () => {
}
});
it("offers Download to… for remote project files only (#4718)", () => {
const off = registerActions([{ id: "project.downloadTo", title: "Download to…", run: () => undefined }]);
try {
const files = [node(`${ROOT}/src`, true), node(`${ROOT}/a.py`)];
expect(labels(contextMenuItems(files))).not.toContain("Download to…");
useRemote.setState({
session: { target: { kind: "ssh", config: "box" }, root: ROOT, host: "h", os: "linux", commands: [] },
});
const l = labels(contextMenuItems(files));
expect(l.indexOf("Download to…")).toBe(l.indexOf("Open In") + 1);
expect(labels(contextMenuItems([node(`${SCRATCHES}/s.py`)]))).not.toContain("Download to…");
} finally {
off();
}
});
it("offers file revision actions only for a single file", () => {
expect(sub(contextMenuItems([node("/p/a.py")]), "Git")).toEqual(
expect.arrayContaining(["Compare with Revision…", "Show Current Revision"]),
+9
Переглянути файл
@@ -34,6 +34,7 @@ import {
revealInFinder,
vcsArg,
} from "./operations";
import { canDownload } from "./download";
import { isSameOrInside } from "./paths";
import { useProjectTree } from "./store";
import { tx } from "@/platform/i18n";
@@ -355,6 +356,14 @@ export function contextMenuItems(nodes: ProjectNode[]): MenuItem[] {
{ kind: "separator" },
...menuGroupItems("openIn", menuGroupContext(nodes)),
]),
inWorkspace &&
canDownload() &&
delegated(
"project.downloadTo",
nodes.map((n) => n.path),
"Download to…",
{ icon: "download" },
),
{ kind: "separator" },
);
+120
Переглянути файл
@@ -0,0 +1,120 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { DownloadProgress, TransferReport } from "@/bindings";
import { commands } from "@/platform/ipc";
import { useRemote } from "@/platform/remote";
import { invokeLocal } from "@/platform/tauriCore";
import { useTasks } from "@/workbench/tasks";
const open = vi.fn();
vi.mock("@/platform/dialog", () => ({ open: (...args: unknown[]) => open(...args) }));
// `@tauri-apps/api/core` resolves to this module (vite.config.ts).
vi.mock("@/platform/tauriCore", async (orig) => ({
...(await orig<typeof import("@/platform/tauriCore")>()),
invokeLocal: vi.fn(async () => undefined),
Channel: class {
onmessage = (_p: unknown) => {};
},
}));
const notify = vi.fn();
vi.mock("@/workbench/contributions", async (orig) => ({
...(await orig<typeof import("@/workbench/contributions")>()),
notifications: () => ({ notify }),
}));
const { canDownload, downloadTo } = await import("./download");
const report = (r: Partial<TransferReport>): TransferReport => ({ files: 0, skipped: 0, errors: [], ...r });
beforeEach(() => {
useTasks.setState({ tasks: [] });
useRemote.setState({
session: { target: { kind: "ssh", config: "s" }, root: "/srv/app", host: "box", os: "linux", commands: [] },
});
open.mockResolvedValue("/Users/me/Downloads");
});
afterEach(() => {
vi.restoreAllMocks();
open.mockReset();
notify.mockReset();
useRemote.setState({ session: null });
useTasks.setState({ tasks: [] });
});
describe("Download to… (#4718)", () => {
it("is offered only in a remote window", () => {
expect(canDownload()).toBe(true);
useRemote.setState({ session: null });
expect(canDownload()).toBe(false);
});
it("downloads the top-level selection into the chosen folder and reports progress", async () => {
let finish!: (r: { status: "ok"; data: TransferReport }) => void;
const download = vi.spyOn(commands, "remoteDownloadLocal").mockReturnValue(
new Promise((resolve) => {
finish = resolve;
}),
);
const work = downloadTo(["/srv/app/src", "/srv/app/src/main.rs", "/srv/app/Cargo.toml"]);
await vi.waitFor(() => expect(download).toHaveBeenCalled());
const [paths, target, request, channel] = download.mock.calls[0]!;
expect(paths).toEqual(["/srv/app/src", "/srv/app/Cargo.toml"]);
expect(target).toBe("/Users/me/Downloads");
(channel as unknown as { onmessage: (p: DownloadProgress) => void }).onmessage({
path: "/srv/app/src/main.rs",
done: 1,
total: 4,
});
const task = useTasks.getState().tasks[0]!;
expect(task).toMatchObject({ title: "Downloading files", message: "main.rs", fraction: 0.25, done: false });
task.cancel!();
expect(invokeLocal).toHaveBeenCalledWith("cancel_request", { id: request });
finish({ status: "ok", data: report({ files: 4 }) });
await work;
expect(notify).toHaveBeenCalledWith(
expect.objectContaining({ level: "info", title: "Downloaded 4 files to /Users/me/Downloads" }),
);
expect(useTasks.getState().tasks[0]?.done).toBe(true);
});
it("lists the files that failed", async () => {
vi.spyOn(commands, "remoteDownloadLocal").mockResolvedValue({
status: "ok",
data: report({ files: 1, errors: [{ path: "/srv/app/link", message: "leads outside the target folder" }] }),
});
await downloadTo(["/srv/app"]);
expect(notify).toHaveBeenCalledWith(
expect.objectContaining({
level: "warning",
title: "Download to /Users/me/Downloads finished with errors",
body: "/srv/app/link: leads outside the target folder",
}),
);
});
it("does nothing when the folder picker is cancelled", async () => {
open.mockResolvedValue(null);
const download = vi.spyOn(commands, "remoteDownloadLocal");
await downloadTo(["/srv/app/a.txt"]);
expect(download).not.toHaveBeenCalled();
expect(useTasks.getState().tasks).toEqual([]);
});
it("reports a failed download, but not a cancelled one", async () => {
vi.spyOn(commands, "remoteDownloadLocal").mockResolvedValueOnce({
status: "error",
error: { kind: "unavailable", message: "Remote project is disconnected" },
});
await downloadTo(["/srv/app/a.txt"]);
expect(notify).toHaveBeenCalledWith(
expect.objectContaining({ level: "error", body: "Remote project is disconnected" }),
);
notify.mockReset();
vi.spyOn(commands, "remoteDownloadLocal").mockResolvedValueOnce({
status: "error",
error: { kind: "cancelled", message: "Cancelled" },
});
await downloadTo(["/srv/app/a.txt"]);
expect(notify).not.toHaveBeenCalled();
expect(useTasks.getState().tasks.every((t) => t.done)).toBe(true);
});
});
+57
Переглянути файл
@@ -0,0 +1,57 @@
/** Download to… in a remote project: copies the selected remote files and folders to this machine. */
import { Channel } from "@tauri-apps/api/core";
import type { DownloadProgress } from "@/bindings";
import { open } from "@/platform/dialog";
import { tx } from "@/platform/i18n";
import { call, commands, isCancelled, nextRequestId } from "@/platform/ipc";
import { isRemoteWindow } from "@/platform/remote";
import { invokeLocal } from "@/platform/tauriCore";
import { notifications } from "@/workbench/contributions";
import { upsertTask } from "@/workbench/tasks";
import { isInside, nameOf } from "./paths";
/** Whether this window's project files live on another machine, so they can be downloaded. */
export const canDownload = () => isRemoteWindow();
/** Asks for a local folder and downloads `paths` into it, each under its own name. */
export async function downloadTo(paths: readonly string[]) {
// A selected folder brings its selected children along; downloading them again would duplicate them.
const tops = paths.filter((p, i) => paths.indexOf(p) === i && !paths.some((q) => isInside(p, q)));
if (!tops.length || !canDownload()) return;
const folder = await open({ directory: true, multiple: false, title: tx("Download to") });
if (typeof folder !== "string") return;
const request = nextRequestId();
const task = {
id: `file-download-${request}`,
title: tx("Downloading files"),
message: null as string | null,
fraction: null as number | null,
cancel: () => void invokeLocal("cancel_request", { id: request }).catch(() => {}),
};
upsertTask({ ...task, done: false });
const progress = new Channel<DownloadProgress>();
progress.onmessage = (p) =>
upsertTask({ ...task, message: nameOf(p.path), fraction: p.total ? p.done / p.total : null, done: false });
try {
const report = await call(commands.remoteDownloadLocal([...tops], folder, request, progress));
const failed = report.errors.length > 0;
notifications().notify({
level: failed ? (report.files ? "warning" : "error") : "info",
title: failed
? tx`Download to ${folder} finished with errors`
: tx`Downloaded ${report.files} files to ${folder}`,
body: failed ? report.errors.map((e) => `${e.path}: ${e.message}`).join("\n") : undefined,
key: "project.download",
});
} catch (e) {
if (isCancelled(e)) return;
notifications().notify({
level: "error",
title: tx`Cannot download to ${folder}`,
body: e instanceof Error ? e.message : String(e),
key: "project.download",
});
} finally {
upsertTask({ ...task, done: true });
}
}
+29 -1
Переглянути файл
@@ -8,7 +8,10 @@ import { TestResults } from "./testing";
import { TestTreeView } from "./TestTreeView";
import { testTree } from "./testTree";
const nav = vi.hoisted(() => ({ openTarget: vi.fn(async () => {}) }));
const nav = vi.hoisted(() => ({
openTarget: vi.fn(async () => {}),
resolveTarget: vi.fn(async () => "/p/src/test/java/MathTest.java"),
}));
vi.mock("./navigate", () => nav);
const actions = vi.hoisted(() => ({ executeAction: vi.fn(async () => {}) }));
vi.mock("@/platform/actions", async (orig) => ({ ...(await orig<object>()), executeAction: actions.executeAction }));
@@ -97,6 +100,31 @@ describe("TestTreeView", () => {
);
});
it("context menu: Diagnose with Agent passes the selected failure to the agents action (#4716)", async () => {
// Offered only while the agents feature provides the action.
render(<Host />);
fireEvent.contextMenu(screen.getByText("subs()"));
expect(screen.queryByText("Diagnose with Agent")).toBeNull();
fireEvent.keyDown(document.activeElement ?? document.body, { key: "Escape" });
onTestFinished(
registerActions([{ id: "agents.diagnoseTestFailure", title: "Diagnose with Agent", run: () => {} }]),
);
// A suite is not one test.
fireEvent.contextMenu(screen.getByText("MathTest"));
expect(screen.queryByText("Diagnose with Agent")).toBeNull();
fireEvent.keyDown(document.activeElement ?? document.body, { key: "Escape" });
fireEvent.contextMenu(screen.getByText("subs()"));
await act(async () => fireEvent.click(screen.getByText("Diagnose with Agent")));
expect(actions.executeAction).toHaveBeenCalledWith("agents.diagnoseTestFailure", {
name: "subs()",
path: "/p/src/test/java/MathTest.java",
line: 9,
expected: "1",
actual: "2",
output: ["org.opentest4j.AssertionFailedError: expected: <1> but was: <2>"],
});
});
it.each([true, false])(
"enables Run and Debug only when the async selector returns support (%s)",
async (supported) => {
+32 -3
Переглянути файл
@@ -1,6 +1,6 @@
import { useEffect, useMemo, useRef, useState, type MouseEvent } from "react";
import clsx from "clsx";
import { executeAction } from "@/platform/actions";
import { executeAction, getAction } from "@/platform/actions";
import {
findOccurrence,
Icon,
@@ -15,14 +15,24 @@ import {
type TreeHandle,
} from "@/ui";
import { useOccurrenceNavigator } from "@/workbench/contributions";
import { openTarget } from "./navigate";
import { formatDuration, nodeDuration, nodeStatus, type TestNode, type TestResults, type TestStatus } from "./testing";
import { openTarget, resolveTarget } from "./navigate";
import {
formatDuration,
nodeDuration,
nodeOutput,
nodeStatus,
type TestNode,
type TestResults,
type TestStatus,
} from "./testing";
import { parseComparison } from "./testing/comparison";
import { TEST_TREE_FOCUS, testTree } from "./testTree";
import { ExportTestResultsDialog } from "./ExportTestResultsDialog";
import styles from "./Run.module.css";
import { tx } from "@/platform/i18n";
const DIAGNOSE = "agents.diagnoseTestFailure";
/** Test tree filters and sorting, kept across runs and restarts (IDEA hides passed tests by default). */
const FILTERS_KEY = "openidea.run.testFilters";
@@ -215,6 +225,23 @@ export function TestTreeView({
if (target) void openTarget(target, cwd, true);
};
// The agents feature's action: the failure becomes a draft the user reviews and sends.
const diagnose = async (n: TestNode, name: string) => {
const located = n.location ?? firstLocated(n)?.location;
const path = located ? await resolveTarget(located, cwd).catch(() => null) : null;
// Rust's `left` / `right` don't say which side is expected; the output excerpt shows them as written.
const parsed = parseComparison(n.output);
const comparison = parsed?.labels ? null : parsed;
await executeAction(DIAGNOSE, {
name,
path,
line: path ? located?.line : undefined,
expected: comparison?.expected,
actual: comparison?.actual,
output: nodeOutput(n),
});
};
const contextMenu = (node: TestNode | null, sel: Set<string>, e: MouseEvent) => {
if (!node) return;
const ids = sel.has(node.id) ? [...sel] : [node.id];
@@ -245,6 +272,8 @@ export function TestTreeView({
}
if (ids.length === 1 && nodeStatus(node) === "failed" && parseComparison(node.output))
items.push({ label: "Show Diff", icon: "diff", run: () => void showTestDiff(node) });
if (ids.length === 1 && !node.children.length && nodeStatus(node) === "failed" && getAction(DIAGNOSE))
items.push({ label: "Diagnose with Agent", icon: "toolwindow-agents", run: () => void diagnose(node, name) });
items.push({
label: "Jump to Source",
icon: "external-link",
+15
Переглянути файл
@@ -180,6 +180,21 @@ describe("SeController", () => {
).not.toContain("f:/data/scratches/scratch_3.md");
});
// #4079 follow-up: a plain Windows absolute path names an indexed file.
it("searches a pasted Windows absolute path as its project-relative path", async () => {
const findFiles = vi.fn(async () => [fm("pkg/service/Config.go")]);
const { c, last } = setup({ findFiles, root: () => "E:/work/sample" });
c.run({
query: String.raw`e:\work\sample\pkg\service\Config.go`,
tab: "files",
includeNonProject: false,
extra: {},
});
await flush();
expect(findFiles).toHaveBeenCalledWith("pkg/service/Config.go", expect.any(Number));
expect(last().sections.get("files")!.items[0]).toMatchObject({ key: "f:/p/pkg/service/Config.go" });
});
it("parses File.kt:42 and opens files at the line", async () => {
const findFiles = vi.fn(async () => [fm("File.kt")]);
const { c, last } = setup({ findFiles });
+27
Переглянути файл
@@ -31,10 +31,37 @@ describe("parseLocationQuery", () => {
expect(parseLocationQuery("/elsewhere/x.kt", "/dev/acme").text).toBe("/elsewhere/x.kt");
});
it("reduces a pasted Windows absolute path to the project-relative one", () => {
expect(parseLocationQuery(String.raw`E:\work\sample\pkg\service\Config.go`, "E:/work/sample").text).toBe(
"pkg/service/Config.go",
);
// A drive-letter path is case-insensitive on Windows, its drive letter included.
expect(parseLocationQuery(String.raw`e:\work\sample\pkg\Config.go`, "E:/work/sample").text).toBe("pkg/Config.go");
expect(parseLocationQuery(String.raw`E:\WORK\Sample\pkg\Config.go`, "e:/work/sample").text).toBe("pkg/Config.go");
// Mixed separators and the `\\?\` verbatim prefix.
expect(parseLocationQuery(String.raw`E:/work\sample\pkg/Config.go`, "E:/work/sample").text).toBe("pkg/Config.go");
expect(parseLocationQuery(String.raw`\\?\E:\work\sample\pkg\Config.go`, "E:/work/sample").text).toBe(
"pkg/Config.go",
);
expect(parseLocationQuery(String.raw`E:\work\sample\pkg\Config.go:12:3`, "E:/work/sample")).toEqual({
text: "pkg/Config.go",
line: 11,
col: 2,
});
});
it("keeps POSIX and out-of-project paths as they are", () => {
// POSIX paths stay case-sensitive: `/Users/me/Src` is not `/Users/me/src`.
expect(parseLocationQuery("/Users/me/src/a.ts", "/Users/me/src").text).toBe("a.ts");
expect(parseLocationQuery("/Users/me/Src/a.ts", "/Users/me/src").text).toBe("/Users/me/Src/a.ts");
expect(parseLocationQuery(String.raw`E:\elsewhere\x.go`, "E:/work/sample").text).toBe("E:/elsewhere/x.go");
});
it("handles quotes, file:// URLs and Windows separators", () => {
expect(parseLocationQuery('"src/a.ts"').text).toBe("src/a.ts");
expect(parseLocationQuery("file:///dev/acme/My%20File.kt", "/dev/acme").text).toBe("My File.kt");
expect(parseLocationQuery("src\\main\\App.kt").text).toBe("src/main/App.kt");
expect(parseLocationQuery("src/main\\App.kt").text).toBe("src/main/App.kt");
// Windows file URLs, with a space and an encoded `#` in the name (#4079).
expect(parseLocationQuery("file:///C:/work/sample/src/a%20b%23c.txt", "C:/work/sample").text).toBe("src/a b#c.txt");
});
+19 -4
Переглянути файл
@@ -31,7 +31,10 @@ export function parseLocationQuery(raw: string, root?: string | null): ParsedQue
// `file:///C:/x` names `C:/x` on Windows.
if (/^\/[a-zA-Z]:\//.test(text)) text = text.slice(1);
}
if (/^[a-zA-Z]:\\/.test(text) || (text.includes("\\") && !text.includes("/"))) text = text.replace(/\\/g, "/");
// Index paths are `/`-separated: separators may be mixed after a paste.
if (text.includes("\\")) text = text.replace(/\\/g, "/");
// `\\?\E:\x` (verbatim) and `\\.\E:\x` name `E:/x`.
text = text.replace(/^\/\/[?.]\//, "");
let line: number | null = null;
let col: number | null = null;
@@ -47,13 +50,25 @@ export function parseLocationQuery(raw: string, root?: string | null): ParsedQue
}
if (root) {
const r = root.replace(/\/+$/, "");
if (text === r) text = "";
else if (text.startsWith(r + "/")) text = text.slice(r.length + 1);
const rel = relativeToRoot(text, root.replace(/\/+$/, ""));
if (rel !== null) text = rel;
}
return { text, line, col };
}
/**
* `text` relative to the project `root`, or `null` when it is not below it. A drive-letter root
* compares like Windows, where case does not matter (the backend upper-cases the drive letter).
*/
function relativeToRoot(text: string, root: string): string | null {
if (text.length < root.length) return null;
const head = text.slice(0, root.length);
const same = /^[a-zA-Z]:\//.test(root) ? head.toLowerCase() === root.toLowerCase() : head === root;
if (!same) return null;
if (text.length === root.length) return "";
return text[root.length] === "/" ? text.slice(root.length + 1) : null;
}
/** Selection for opening a parsed location; `undefined` when no line was given. */
export function selectionOf(q: Pick<ParsedQuery, "line" | "col">): { line: number; col: number } | undefined {
return q.line === null ? undefined : { line: q.line, col: q.col ?? 0 };
+7
Переглянути файл
@@ -484,4 +484,11 @@ describe("current line decoration", () => {
// The visible label is the pointer/click region; the anchor stays zero-width.
expect(inlineBlameTheme['.cm-vcs-inline-blame-inner[role="button"]']).toEqual({ cursor: "pointer" });
});
it("caps the commit tooltip's height and scrolls inside it, so a long message stays on screen", () => {
expect(inlineBlameTheme[".cm-vcs-inline-blame-tooltip"]).toMatchObject({
maxHeight: expect.any(String),
overflow: "auto",
});
});
});
+3
Переглянути файл
@@ -271,6 +271,9 @@ export const inlineBlameTheme = {
".cm-vcs-inline-blame-tooltip": {
padding: "8px 12px",
maxWidth: "min(70ch, 80vw)",
maxHeight: "min(420px, 55vh)",
overflow: "auto",
overscrollBehavior: "contain",
whiteSpace: "pre-wrap",
overflowWrap: "anywhere",
},
+13 -5
Переглянути файл
@@ -1,5 +1,6 @@
import { tx } from "@/platform/i18n";
import { call, commands } from "@/platform/ipc";
import { isMacHost } from "@/platform/keymap";
import { Icon, IconButton, SearchField, type MenuItem } from "@/ui";
import clsx from "clsx";
import { useContext, useEffect, useLayoutEffect, useRef, useState } from "react";
@@ -251,11 +252,18 @@ export function FilterBar() {
onOpen: (anchor: HTMLElement) =>
menuBelow(
anchor,
repositories.map((repo) => ({
label: repoName(repo),
checked: filters.repositories?.includes(repo) ?? false,
run: () => setLogFilters({ repositories: toggleRepository(filters.repositories, repo) }),
})),
repositories.map((repo) => {
const name = repoName(repo);
const modifier = isMacHost() ? "⌘" : "Ctrl";
return {
label: name,
verbatim: true,
checked: filters.repositories?.includes(repo) ?? false,
run: () => setLogFilters({ repositories: toggleRepository(filters.repositories, repo) }),
runWithModifier: () => setLogFilters({ repositories: [repo] }),
hint: tx`${modifier}+Click to only see "${name}"`,
};
}),
),
onClear: () => setLogFilters({ repositories: [] }),
},
+16
Переглянути файл
@@ -64,6 +64,22 @@ describe("color schemes", () => {
}
});
it("keeps an imported scheme's gutter on its editor background unless it sets its own", () => {
const customs = (gutter?: string) => ({
"custom-a": {
name: "A",
parent: "dark" as const,
attributes: { text: { background: "#2b2b2b" }, ...(gutter ? { gutter: { background: gutter } } : {}) },
},
});
expect(schemeCss("custom-a", undefined, document.documentElement, customs())).toContain(
"--bg-editor-gutter: #2b2b2b !important;",
);
expect(schemeCss("custom-a", undefined, document.documentElement, customs("#313335"))).toContain(
"--bg-editor-gutter: #313335 !important;",
);
});
it("offers a Go scheme page and scopes its overrides to Go editors", () => {
expect(ATTRIBUTES.find((a) => a.id === "go.constant")?.path).toEqual(["Go"]);
const css = schemeCss("dark", { dark: { "go.constant": { foreground: "#224466" } } });
+4 -1
Переглянути файл
@@ -826,7 +826,10 @@ export function schemeCss(
}
// The editor surface follows the scheme, not the island colour of the UI theme.
const bg = tokens.get("--bg-editor") ?? tokens.get("--bg-island");
if (bg) decls.push(["--bg-editor", bg], ["--bg-editor-gutter", tokens.get("--bg-editor-gutter") ?? bg]);
// An imported scheme's gutter keeps its editor background unless it sets one of its own.
const custom = valid[id];
const gutter = custom ? (custom.attributes.gutter?.background ?? bg) : (tokens.get("--bg-editor-gutter") ?? bg);
if (bg) decls.push(["--bg-editor", bg], ["--bg-editor-gutter", gutter ?? bg]);
}
decls.push(...overrideDeclarations(overrides?.[id]));
const body = decls
+22 -1
Переглянути файл
@@ -10,6 +10,7 @@ import {
schemeCss,
} from "./colorScheme";
import { deleteScheme, exportIcls, importScheme, parseIcls, SchemeParseError } from "./icls";
import { DARCULA_ATTRIBUTES } from "./iclsDarcula";
import { validateSettings } from "@/features/settings/model/schema";
import { colorSchemeItems } from "@/workbench/quickSwitch";
import { useProject } from "./project";
@@ -178,7 +179,7 @@ describe(".icls schemes", () => {
expect(fg("docCommentTagValue")).toBe("#e5c07b");
expect(fg("regexp")).toBe("#56b6c2");
// Superseded keys and DEFAULT_SEMICOLON are counted as skipped.
expect(scheme.attributes.operator).toBeUndefined();
expect(scheme.attributes.operator).toEqual(DARCULA_ATTRIBUTES.operator);
expect([applied, skipped]).toEqual([10, 6]);
});
@@ -405,6 +406,26 @@ describe(".icls schemes", () => {
expect(parseIcls(exportIcls(id, customs)).scheme.attributes.pyFString?.foreground).toBe("#808080");
});
it("takes what a Darcula-based scheme leaves out from Darcula, as IntelliJ does", () => {
const { scheme, applied } = parseIcls(`<scheme name="Mine" parent_scheme="Darcula"><attributes>
<option name="DEFAULT_KEYWORD"><value><option name="FOREGROUND" value="ff8800"/></value></option>
<option name="ERRORS_ATTRIBUTES"><value/></option>
<option name="DEFAULT_CONSTANT" baseAttributes="DEFAULT_IDENTIFIER"/>
</attributes></scheme>`);
expect(applied).toBe(1);
expect(scheme.parent).toBe("dark");
expect(scheme.attributes.text).toEqual({ foreground: "#a9b7c6", background: "#2b2b2b" });
expect(scheme.attributes.string?.foreground).toBe("#6a8759");
expect(scheme.attributes.keyword).toEqual({ foreground: "#ff8800", bold: false, italic: false });
// An entry of its own, even an empty one, replaces Darcula's.
expect(scheme.attributes.error).toBeUndefined();
expect(scheme.attributes.constant).toBeUndefined();
// The gutter keeps the editor's background, as in IntelliJ's new UI.
expect(scheme.attributes.gutter).toBeUndefined();
// Other parents keep the IDE's own base.
expect(parseIcls('<scheme name="I" parent_scheme="Islands Dark"></scheme>').scheme.attributes).toEqual({});
});
it("imports the global variable colour", () => {
const xml =
'<scheme name="G" parent_scheme="Darcula"><attributes><option name="DEFAULT_GLOBAL_VARIABLE"><value>' +
+9 -1
Переглянути файл
@@ -10,6 +10,7 @@ import {
} from "./colorScheme";
import { isBuiltinTheme, themeKind } from "./themes";
import type { CustomColorScheme, CustomColorSchemes, TextAttributesOverride } from "./editorSettings";
import { DARCULA_ATTRIBUTES } from "./iclsDarcula";
// Many language keys share the editor's language-default tokens.
const ATTRIBUTE_NAMES: Record<string, string> = {
@@ -439,6 +440,12 @@ export function parseIcls(
}
}
const parentName = root.getAttribute("parent_scheme") ?? "";
// IntelliJ replaces a parent's attribute as a whole: any entry of the file, even an empty one or
// one only naming its baseAttributes, wins.
if (parentName === "Darcula") {
const own = new Set([...entries.keys()].flatMap((name) => (name ? targets(name) : [])));
for (const [id, value] of Object.entries(DARCULA_ATTRIBUTES)) if (!own.has(id)) attributes[id] ??= { ...value };
}
const bg = attributes.text?.background;
const rgb = bg ? [1, 3, 5].map((i) => parseInt(bg.slice(i, i + 2), 16)) : [255, 255, 255];
const dark = rgb[0]! * 0.299 + rgb[1]! * 0.587 + rgb[2]! * 0.114 < 128;
@@ -547,7 +554,8 @@ export function exportIcls(
if (isHexColor(v[field])) opts.push(`<option name="${key}" value="${exportColor(v[field]!)}" />`);
if (attr.token) opts.push(`<option name="FONT_TYPE" value="${(v.bold ? 1 : 0) + (v.italic ? 2 : 0)}" />`);
if (effect) opts.push(`<option name="EFFECT_TYPE" value="${effect}" />`);
if (opts.length) attributes.push(` <option name="${key}"><value>${opts.join("")}</value></option>`);
// An empty value keeps the parent scheme's attribute from showing through.
attributes.push(` <option name="${key}"><value>${opts.join("")}</value></option>`);
}
const parent = custom?.parent ?? (isBuiltinTheme(id) ? themeKind(id) : "dark");
return `<scheme name="${escapeXml(name)}" version="142" parent_scheme="${parent === "dark" ? "Darcula" : "Default"}">\n <colors>\n${colors.join("\n")}\n </colors>\n <attributes>\n${attributes.join("\n")}\n </attributes>\n</scheme>\n`;
+64
Переглянути файл
@@ -0,0 +1,64 @@
import type { TextAttributesOverride } from "./editorSettings";
/**
* IntelliJ's bundled Darcula editor scheme (`DefaultColorSchemesManager.xml`) as read by `parseIcls`.
* An exported scheme lists only what differs from its parent, so one with `parent_scheme="Darcula"`
* takes every attribute it leaves out from here (background `#2b2b2b`, not Islands Dark's). Its classic
* GUTTER_BACKGROUND is left out: the gutter keeps the editor's background, as in IntelliJ's new UI.
*/
export const DARCULA_ATTRIBUTES: Readonly<Record<string, TextAttributesOverride>> = {
caret: { foreground: "#bbbbbb" },
caretRow: { background: "#323232" },
consoleBackground: { background: "#2b2b2b" },
indentGuide: { foreground: "#373737" },
lineNumber: { foreground: "#606366" },
lineNumberCaret: { foreground: "#a4a3a3" },
methodSeparator: { foreground: "#4d4d4d" },
rightMargin: { foreground: "#4d4d4d" },
selection: { background: "#214283" },
whitespaces: { foreground: "#606060" },
ansiBlack: { foreground: "#000000" },
ansiBlue: { foreground: "#3993d4" },
ansiBrightBlue: { foreground: "#1fb0ff" },
ansiCyan: { foreground: "#00a3a3" },
ansiBrightCyan: { foreground: "#00e5e5" },
ansiBrightBlack: { foreground: "#595959" },
ansiWhite: { foreground: "#808080" },
ansiGreen: { foreground: "#5c962c" },
ansiBrightGreen: { foreground: "#4fc414" },
ansiMagenta: { foreground: "#a771bf" },
ansiBrightMagenta: { foreground: "#ed7eed" },
ansiRed: { foreground: "#f0524f" },
ansiBrightRed: { foreground: "#ff4050" },
ansiBrightWhite: { foreground: "#ffffff" },
ansiYellow: { foreground: "#a68a0d" },
ansiBrightYellow: { foreground: "#e5bf00" },
constant: { bold: false, italic: true, foreground: "#9876aa" },
docComment: { bold: false, italic: true, foreground: "#629755" },
docCommentTag: { bold: true, italic: true, foreground: "#629755", effectColor: "#629755", effect: "underline" },
docCommentMarkup: { bold: false, italic: false, foreground: "#77b767" },
functionCall: { bold: false, italic: false },
functionDeclaration: { bold: false, italic: false, foreground: "#ffc66d" },
identifier: { bold: false, italic: false, foreground: "#a9b7c6" },
field: { bold: false, italic: false, foreground: "#9876aa" },
invalid: { bold: false, italic: false, foreground: "#6a8759", effectColor: "#ff0000", effect: "wave" },
keyword: { bold: false, italic: false, foreground: "#cc7832" },
lineComment: { bold: false, italic: false, foreground: "#808080" },
metadata: { bold: false, italic: false, foreground: "#bbb529" },
number: { bold: false, italic: false, foreground: "#6897bb" },
operator: { bold: false, italic: false },
string: { bold: false, italic: false, foreground: "#6a8759" },
escape: { bold: false, italic: false, foreground: "#cc7832" },
docCommentTagValue: { bold: false, italic: false, foreground: "#8a653b" },
error: { effectColor: "#bc3f3c", effect: "wave" },
folded: { foreground: "#8c8c8c", background: "#3a3a3a" },
identifierUnderCaret: { background: "#344134" },
inlay: { foreground: "#787878", background: "#3b3b3b" },
matchedBrace: { background: "#3b514d" },
unused: { foreground: "#72737a" },
searchResult: { background: "#155221" },
text: { foreground: "#a9b7c6", background: "#2b2b2b" },
searchResultCurrent: { background: "#32593d" },
todo: { bold: false, italic: true, foreground: "#a8c023" },
identifierUnderCaretWrite: { background: "#40332b" },
};
+15 -1
Переглянути файл
@@ -18,6 +18,7 @@
"MCP tools": "MCP tools",
"Autocompact buffer": "Autocompact buffer",
"Inspection details": "Inspection details",
"Inspection actions": "Inspection actions",
"Resize inspection panes": "Resize inspection panes",
"Resize branch comparison panes": "Resize branch comparison panes",
"Resize inspection description": "Resize inspection description",
@@ -2775,5 +2776,18 @@
"rename it back to {name}": "rename it back to {name}",
"restore {name} and check out the previous branch again": "restore {name} and check out the previous branch again",
"Unset upstream of {to} ({root})": "Unset upstream of {to} ({root})",
"Group by Repository": "Group by Repository"
"Group by Repository": "Group by Repository",
"Diagnose with Agent": "Diagnose with Agent",
"Adds a failed test's name, source location, expected and actual values and output to the agent message typed last, to review and send.": "Adds a failed test's name, source location, expected and actual values and output to the agent message typed last, to review and send.",
"The test {name} failed. Help me find out why.": "The test {name} failed. Help me find out why.",
"Test source: {location}": "Test source: {location}",
"Expected:": "Expected:",
"Actual:": "Actual:",
"… {more} more lines": "… {more} more lines",
"Downloading files": "Downloading files",
"Downloaded {files} files to {folder}": "Downloaded {files} files to {folder}",
"Download to {folder} finished with errors": "Download to {folder} finished with errors",
"Cannot download to {folder}": "Cannot download to {folder}",
"Copy the selected files and folders of a remote project to a folder on this computer": "Copy the selected files and folders of a remote project to a folder on this computer",
"{modifier}+Click to only see \"{name}\"": "{modifier}+Click to only see \"{name}\""
}
+15 -1
Переглянути файл
@@ -18,6 +18,7 @@
"MCP tools": "MCP 工具",
"Autocompact buffer": "自动压缩预留空间",
"Inspection details": "检查详情",
"Inspection actions": "检查操作",
"Resize inspection panes": "调整检查窗格大小",
"Resize branch comparison panes": "调整分支比较窗格大小",
"Resize inspection description": "调整检查说明窗格大小",
@@ -9138,5 +9139,18 @@
"{name} changed on disk": "{name} 已在磁盘上更改",
"The file was changed outside the IDE while it has unsaved changes in the editor. Saving keeps the editor's version and overwrites the file.": "该文件在 IDE 外被修改,而编辑器中还有未保存的更改。保存会保留编辑器中的版本并覆盖该文件。",
"Load Changes from Disk": "从磁盘加载更改",
"Keep Editor Changes": "保留编辑器中的更改"
"Keep Editor Changes": "保留编辑器中的更改",
"Diagnose with Agent": "用智能体诊断",
"Adds a failed test's name, source location, expected and actual values and output to the agent message typed last, to review and send.": "把失败测试的名称、源码位置、期望值与实际值和输出添加到最近编辑的智能体消息中,检查后再发送。",
"The test {name} failed. Help me find out why.": "测试 {name} 失败了,帮我找出原因。",
"Test source: {location}": "测试源码:{location}",
"Expected:": "期望:",
"Actual:": "实际:",
"… {more} more lines": "… 另有 {more} 行",
"Downloading files": "正在下载文件",
"Downloaded {files} files to {folder}": "已下载 {files} 个文件到 {folder}",
"Download to {folder} finished with errors": "下载到 {folder} 完成,但有错误",
"Cannot download to {folder}": "无法下载到 {folder}",
"Copy the selected files and folders of a remote project to a folder on this computer": "把远程项目中选中的文件和文件夹复制到本机的文件夹",
"{modifier}+Click to only see \"{name}\"": "{modifier}+点击仅显示“{name}”"
}
+14 -6
Переглянути файл
@@ -15,7 +15,7 @@ import clsx from "clsx";
import { create } from "zustand";
import { getAction, isActionEnabled, executeActionFrom, actionToggled } from "@/platform/actions";
import { useContextKeys } from "@/platform/context";
import { shortcutLabel } from "@/platform/keymap";
import { hasPrimaryModifier, shortcutLabel } from "@/platform/keymap";
import { Icon, type IconName } from "./icons";
import { Popup, type PopupAnchor } from "./Popup";
import type { Placement } from "@floating-ui/react-dom";
@@ -48,6 +48,10 @@ export type MenuItem =
checked?: boolean;
danger?: boolean;
run?: () => void;
/** Run instead of `run` on ⌘-click (macOS) / Ctrl-click, e.g. "only this one" in a multi-choice filter. */
runWithModifier?: () => void;
/** Tooltip of the whole row (the label's own tooltip shows a truncated label). */
hint?: string;
/** The pointer or the keyboard made it the active item (not on opening the menu). */
onActive?: () => void;
submenu?: MenuItem[];
@@ -65,6 +69,8 @@ interface Resolved {
checked?: boolean;
danger?: boolean;
run?: () => void;
runWithModifier?: () => void;
hint?: string;
onActive?: () => void;
submenu?: MenuItem[];
}
@@ -205,7 +211,7 @@ export function MenuList({
}
};
const activate = (i: number) => {
const activate = (i: number, modifiers?: Pick<KeyboardEvent, "metaKey" | "ctrlKey">) => {
cancelHover();
const item = resolved[i];
if (!selectable(item)) return;
@@ -215,7 +221,8 @@ export function MenuList({
return;
}
onDone();
item!.run?.();
if (item!.runWithModifier && modifiers && hasPrimaryModifier(modifiers)) item!.runWithModifier();
else item!.run?.();
};
const cancelHover = () => {
@@ -320,7 +327,7 @@ export function MenuList({
break;
case "Enter":
case " ":
activate(active);
activate(active, e);
break;
default:
if (e.key.length === 1 && !e.metaKey && !e.ctrlKey && !e.altKey) {
@@ -396,7 +403,8 @@ export function MenuList({
onMouseEnter={(e) => hover(i, { x: e.clientX, y: e.clientY })}
onPointerLeave={() => leave(i)}
onMouseLeave={() => leave(i)}
onClick={() => activate(i)}
onClick={(e) => activate(i, e)}
title={r.hint}
>
{numbers && (
<span className={styles.mnemonic} data-menu-number={numbersOf[i]} aria-hidden={true}>
@@ -408,7 +416,7 @@ export function MenuList({
{r.checked ? <Icon name="check" size={13} /> : r.icon ? <Icon name={r.icon} size={14} /> : null}
</span>
)}
<span className={styles.label} title={r.label}>
<span className={styles.label} title={r.hint ? undefined : r.label}>
{r.label}
</span>
{r.shortcut && (
+27
Переглянути файл
@@ -3,6 +3,7 @@ import { describe, expect, it, vi } from "vitest";
import { act, fireEvent, render, screen } from "@testing-library/react";
import { getContext, setContext } from "@/platform/context";
import { registerAction } from "@/platform/actions";
import { usePlatform } from "@/platform/platformInfo";
import { Popup } from "./Popup";
import { ContextMenuHost, Menu, MenuList, hideContextMenu, showContextMenu, useContextMenuStore } from "./Menu";
import menuStyles from "./Menu.module.css";
@@ -265,6 +266,32 @@ describe("Menu action enablement", () => {
}
});
it("runs an item's modifier action on ⌘-click (macOS) or Ctrl-click, and shows its hint", () => {
const os = usePlatform.getState().os;
try {
for (const [platform, mod] of [
["macos", { metaKey: true }],
["linux", { ctrlKey: true }],
] as const) {
usePlatform.setState({ os: platform });
const run = vi.fn();
const only = vi.fn();
const items = [{ label: "frontend", run, runWithModifier: only, hint: "Only frontend" }];
const { unmount } = render(<MenuList items={items} onDone={() => {}} />);
const row = screen.getByRole("menuitem", { name: /frontend/ });
expect(row).toHaveAttribute("title", "Only frontend");
fireEvent.click(row);
expect(run).toHaveBeenCalledTimes(1);
fireEvent.click(row, mod);
expect(only).toHaveBeenCalledTimes(1);
expect(run).toHaveBeenCalledTimes(1);
unmount();
}
} finally {
usePlatform.setState({ os });
}
});
it("highlights the row under the pointer without moving focus", () => {
render(
<MenuList