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

...
Автор SHA1 Повідомлення Дата
l0ng-ai abd3eabb10 feat(editor): colour Vue component tags apart from HTML elements
Component tags in Vue templates (<Icon>, <el-input>) had the same colour as HTML elements. Tag names that are PascalCase or hyphenated now use a new --syn-custom-tag token, IDEA's Custom tag name colour: #2fbaa3 in Islands Dark, #b21dbf in Islands Light, with values for high contrast, the palette themes and Harbor Night.

Fixes #6894
2026-11-30 21:55:18 +08:00
l0ng-ai f7f2efaace feat(debugger): evaluate the expression of an operator on hover and Quick Evaluate (#7055)
Hovering or Alt-clicking an operator while suspended evaluated nothing, because only identifiers, member chains and calls were taken. An operator now gives the expression it belongs to, from the syntax tree: && gives a > 1 && !flag, > gives a > 1, ! gives !flag. A hover leaves out expressions with calls, increments or assignments, which Quick Evaluate still evaluates; an identifier is still just the identifier.

Fixes #7000
2026-11-30 21:19:38 +08:00
l0ng-ai e8cb141d86 fix(plugins): activate plugins whose activation event fired before they loaded (#7054)
A remote project's server receives the desktop's plugin packages after the window has opened its files, so on-language:twig reached the server before the Twig plugin was installed there and was lost; the plugin stayed inactive and Twig files got no highlighting or completion. The same happened locally when a plugin was installed with a matching file already open. The host now remembers the language, file and view activation events fired so far (bounded) and activates a plugin that loads later if one matches, and the window reports on-language again when the active file's language changes.

Fixes #7014
2026-11-30 21:16:47 +08:00
l0ng-ai 3eb6933644 fix(find): keep the usages popup size loader private and fix a knip import (#7049)
#7048 exported the size loader only its own file uses, and its e2e test imported usages.ts from a literal path; knip reported both. Unexport the loader and import through a variable like the other spec in the file.
2026-11-30 21:06:50 +08:00
l0ng-ai 72669a04c2 fix(find): make the Show Usages popup resizable and remember its size (#7048)
The usages popup had a fixed width and a height derived from its row count, so it could not be enlarged on any platform. It now resizes from its right and bottom edges and corner, the list takes the added height, and the size is remembered for the next time it opens.

Fixes #6999
2026-11-30 21:05:36 +08:00
audichuang 0b9c675172 test(mcp): stop agent commands only once they run, not while the login shell reads its profile (#7041)
The agent-commands MCP test stopped and interrupted 'sleep 30' right after run_command returned with timeout 0, while the login shell could still be reading its profile; a profile command that handles SIGINT lets the shell go on to run the command, leaving the tab stopping past the 10 s wait. Both stops now wait for the command to print 'ready' and assert it is running first.

Co-authored-by: audichuang <[email protected]>
2026-11-30 20:58:49 +08:00
Chris-young42таChris-young42 5188a34e3d fix(java): hot swap Gradle applications without resources (#7044)
Gradle's processResources succeeds with NO-SOURCE when a project has no resources and never creates its output directory, so Update Application stopped before asking the debugger to reload classes. A missing output directory now counts as an empty resource set, and resources an earlier update copied are removed.

Refs #6977

Co-authored-by: Chris-young42 <[email protected]>
2026-11-30 20:56:38 +08:00
Qslia 8d26a9b483 fix(notebook): respect editor tab size (#7043)
Notebook cell editors used CodeMirror's default indent of 4 regardless of settings. Cells now take the Python (code cells) or Markdown Code Style, falling back to the editor tab size, through an indent compartment that is reconfigured in place when settings change, so the cell editor is not rebuilt.

Co-authored-by: qslia <[email protected]>
2026-11-30 20:55:53 +08:00
LU XIANGRUIтаwildcatDownstairs 267a61c581 feat(coverage): run Xcode tests with coverage (#6944)
Run with Coverage is offered for xcode-test configurations: it adds -enableCodeCoverage YES and names the run's result bundle, which xcode::prepare_test uses instead of its own, so there is still one test run and one bundle. Afterwards xcrun xccov view --report and --archive feed the shared coverage accumulator: files compiled only by .xctest targets, files outside the project and DerivedData/.build are left out, resolved paths map back to the project root, and lines with a missed subrange are partial.

Closes #6941

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-30 20:53:41 +08:00
LU XIANGRUIтаwildcatDownstairs 21dfa8dd10 feat(xcode): build CocoaPods projects through their workspace and run pod install/update (#6957)
In a project with a Podfile the app project's schemes are built and tested through the .xcworkspace that pod install writes (it has no schemes of its own), and Pods/ gets no run configurations. Pod Install and Pod Update run in the Run tool window from Find Action, Build > Xcode and a Podfile's context menu; afterwards configurations are detected again and an xcode-build-server buildServer.json is regenerated for the workspace. Opening a project whose Pods/Manifest.lock is missing or differs from Podfile.lock offers Pod Install.

Closes #6956

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-30 20:49:53 +08:00
LU XIANGRUIтаwildcatDownstairs 0cfabdbbbd feat(swift): choose the Xcode a project uses and pass it to its tools as DEVELOPER_DIR (#6964)
Settings > Languages > Swift gets an Xcode field (empty = the xcode-select one). For a trusted project the chosen Xcode.app or Contents/Developer becomes DEVELOPER_DIR in the project environment, so sourcekit-lsp, xcodebuild, xcrun, simulators, debug adapters and terminals use it; it overrides a DEVELOPER_DIR from .envrc and is not applied to untrusted projects or LightEdit.

Closes #6963

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-30 20:43:48 +08:00
l0ng-ai 485d7bf99d test(vim): count Select in Project View as a known action (#7042)
#7011 mapped IDEA's SelectInProjectView to navigate.selectInProjectView, a registered action with no default shortcut in any preset, so the rc.test.ts :action id check failed on main. List it with the other unbound actions.
2026-11-30 20:40:00 +08:00
Anka Tamaтаxirf 53a1e9255e fix(vcs): reopen the repository after its volume was remounted (#6949)
The cached gitoxide handle kept pack mappings from the old mount; after a remount with the same device, inodes and mtimes it was reused and reading it raised SIGBUS. The cache now detects the remount and reopens the repository. A volume lost in the middle of a git operation is not covered.

Refs #6948

Co-authored-by: xirf <[email protected]>
2026-11-30 20:27:43 +08:00
audichuang 40ab249cb8 fix(http): route WebSocket tunnels through the macOS PAC in Auto mode (#6939)
In Auto mode the TCP/CONNECT tunnel used for WebSockets resolved the proxy with the system matcher only, so a macOS PAC script was ignored. It now asks the PAC resolver first on a blocking thread and falls back to the matcher when there is no PAC or an env proxy is set.

Co-authored-by: audichuang <[email protected]>
2026-11-30 20:27:28 +08:00
LU XIANGRUIтаwildcatDownstairs 9da3d6d9b5 feat(typescript): Go to Source Definition, Project Configuration, Move to File and TS Server log through vtsls (#6935)
Five vtsls commands, run through workspace/executeCommand on a vtsls server that advertises them (other TypeScript servers report that vtsls is needed). Go to Source Definition opens the JavaScript implementation instead of the .d.ts; Go to Project Configuration opens the file's tsconfig.json or jsconfig.json; Move to File appears in Refactor > Move and the intention menu, offering tsserver's suggested target files and Choose File, and applies the move with its import updates as one workspace edit; Open TS Server Log offers to turn on logging through the new languages.typescript.tsserverLog setting, which restarts vtsls, and then opens the log.

Closes #6922

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-30 20:24:55 +08:00
l0ng-ai 0df7cb1da2 fix(keymap): list Select Opened File in the VS Code preset (#7038)
project.selectOpenedFile (#7011) was added to the IntelliJ presets only, so the keymap test that the VS Code preset covers every IntelliJ action id failed on main.
2026-11-30 20:23:48 +08:00
LU XIANGRUIтаwildcatDownstairs ee9b50179e feat(welcome): import recent projects and groups from a JetBrains IDE (#6979)
Import Recent Projects from JetBrains IDE (Welcome screen more menu, File > Manage IDE Settings) reads the IDE's options/recentProjects.xml and merges its recent projects and project groups into OpenIDEA's. Entries keep their custom or display name and the later of their open and activation times; hidden (LightEdit) entries are skipped, $USER_HOME$ and $APPLICATION_CONFIG_DIR$ are expanded, and projects whose folder is gone are skipped and counted. Existing entries and groups are kept, a taken group name gets a number, and importing twice adds nothing. Import Settings from JetBrains IDE lists the recent projects as a row of its confirmation and merges them too.

Closes #6970

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-30 20:15:11 +08:00
Muuтаmuutot baab92c804 feat(vcs): create patches from selected historical files (#6981)
Git Log and File History changed files get Create Patch and Copy as Patch to Clipboard, in the toolbar and the context menu. Only the selected repository-relative paths are exported, as path-filtered revision diffs with Git's empty tree on the missing side of additions and deletions and both names for renames. The existing patch dialog, base directory defaults, reverse option and clipboard flow are reused; empty, malformed, no-op, mixed-repository and external-repository selections are disabled.

Co-authored-by: muutot <[email protected]>
2026-11-30 20:08:11 +08:00
l0ng-ai 2b7a18ffd7 fix(search): start Find in Files from the selection in its preview (#7033)
Find in Files and Search Everywhere took the selection only from the active editor tab, so text selected in the Find in Files preview (or another focused editor, such as a diff pane) was ignored when the action ran again. The focused editor's selection now comes first, then the active editor's.

Fixes #6992
2026-11-30 20:04:14 +08:00
Muuтаmuutot f47a83828c feat(structure): temporarily enable filters to find matches (#6934)
With Narrow down on typing on, a File Structure query that matches nothing now turns on the unchecked filters (Show fields, Show non-public, Show inherited members) one at a time until a match appears. Filters enabled this way are restored as the query gets shorter and when the popup closes, and are never saved; a checkbox the user changes by hand keeps its new state, and the cascade stops right after a backspace restores a filter.

Co-authored-by: muutot <[email protected]>
2026-11-30 19:58:05 +08:00
薛纪克таxuejike 4d5ee2d01c feat(agents): drag and delete the whole task list selection (#6933)
In the Agents task list, dragging a row of a multi-selection moves every selected task (into a group, Pinned, a status group, or before or after a task, keeping their order), and Delete deletes the selection while the list has focus. Tree collapsed the selection to the pressed row on mouse down, before a drag could start; a press on a selected row now narrows the selection only on a release without movement. agents.deleteTasks gets a list-focus key binding like agents.archiveTasks, and a click or arrow key opens the session without taking focus from the list; Enter and double-click still focus it.

Closes #6932

Co-authored-by: xuejike <[email protected]>
2026-11-30 19:56:24 +08:00
l0ng-ai 2ecb44098a fix(debugger): drop lldb-dap pseudo paths on Windows too (#7030)
A referenced source's pseudo path such as /usr/lib/swift/libswiftCore.dylib`swift_willThrow was kept on Windows, where a path with a root but no drive is not absolute, so frames_drop_pseudo_paths_of_referenced_sources failed on Rust (windows-latest) since #6961. A rooted path now counts.
2026-11-30 19:48:37 +08:00
Mollo-i b1039bc175 feat(search): select Search Everywhere results in the Project view (#6955)
File, symbol and text results in Search Everywhere get Select in Project View, in the Alt+Enter menu and in a new right-click menu on the row: it closes the popup and selects the result in the Project tool window. This helps with files that open in another application, such as a .doc, where choosing the result leaves no trace of where the file lives. The item is offered only for paths inside the project. One item list now feeds both menus, and Open to the Side is disabled for folders.

Co-authored-by: Greenker <[email protected]>
2026-11-30 19:43:10 +08:00
薛纪克таxuejike 182c7c1dbb feat(editor): double-click the empty tab strip to maximize the editor (#6969)
A double click on the empty part of an editor tab strip (not on a tab, a button or trailing content) now maximizes the editor by hiding all tool windows, the same as a double click on a regular tab; doing it again restores them. Tabs gets an onBlankDoubleClick callback that fires only for the strip itself or its scroller.

Closes #6968

Co-authored-by: xuejike <[email protected]>
2026-11-30 19:42:00 +08:00
l0ng-ai c8dc613485 fix(projects): offer New Tab when opening a remote project or from a remote window (#7017)
The Open Project prompt gated Attach and New Tab on one flag that required a local project in a local window, so opening an SSH/WSL project, or any project from a remote window, offered only New Window and This Window, and "Open project in: tab" fell back to a new window. Attach still needs a local project in a local window, but a project tab is a window of its own joined to this window's group, so it now applies whenever this window has a project: a remote project opens in a new window that joins the group.

Fixes #6923
2026-11-30 18:36:46 +08:00
audichuang 88a6bbca14 perf(vcs): run Git outside the log index lock so commit details and one-commit queries do not wait for a history walk (#7006)
history::log held the log index lock for its whole run, so every Git subprocess it started (file history, path selection, range ids, rev-list, the --grep text filter) ran under the lock, and commit details plus the one-commit queries behind inline blame waited for the whole walk. The lock is now taken per phase: Git runs unlocked and only in-memory work holds the guard. update_head_reachable runs under the guard that builds the rows, and the shared nodes are used only when they were built for the query's shallow set, rebuilt otherwise, so a query stays on one snapshot while others run in between.

Co-authored-by: audichuang <[email protected]>
2026-11-30 18:32:37 +08:00
Ivan b9e555300f fix(macos): defer moving a full-screen tab out of its group until the app is active (#6997)
Close Project on a tab of a native full-screen group moves the tab into a window, and so a full-screen Space, of its own. While the app is inactive, AppKit's enter-full-screen transition for that Space crashes in SLSWindowServerClientSpaceAddWindowsAndRemoveFromSpaces as soon as the web view draws its next frame, taking every project window with it. Detaching such a tab is now deferred: the tab stays in its group (showing Welcome) and moves to its own Space when the app is next activated. Foreground closes and windowed groups detach immediately as before.

Fixes #6937

Co-authored-by: Pecnikas <[email protected]>
2026-11-30 18:30:57 +08:00
l0ng-ai 7ff223001b fix(fonts): keep Latin text monospaced when the chosen font isn't installed (#7013)
With a fallback font set and a primary family that isn't installed, every glyph came from the fallback. A CJK fallback such as PingFang SC has proportional Latin letters, and the terminal sized its cells for the widest of them, so text came out spread apart. Once the native font catalog shows the family is missing, the bundled JetBrains Mono now stands in for it ahead of the fallback, which still covers the glyphs it lacks. Applies to every monospace stack built from the editor or terminal font settings.

Fixes #6974
2026-11-30 18:25:17 +08:00
l0ng-ai cc9279a6d6 fix(editor): indent Slint element blocks by their braces (#7012)
Slint borrows the C mode for highlighting until slint-lsp's semantic tokens arrive, and Enter used that mode's statement indentation: after a child element's closing brace the next line went back to column 0, and nested blocks below it opened one level short. Slint now uses the brace-based fallback indentation even though a highlighting mode is loaded. No other language with a borrowed mode has this mismatch.

Fixes #6976
2026-11-30 18:22:26 +08:00
l0ng-ai 1cfbb24b31 fix(project-tree): add Select Opened File as a Project View action for the keymap (#7011)
The keymap listed "Select Opened File" only as the Database view action, so a shortcut assigned to it revealed the file in the Database view and did nothing in a project without data sources. Like IDEA's SelectOpenedFileInProjectView, the Project view now has its own Select Opened File action (the toolbar button runs it), and imported IDEA keymaps map SelectOpenedFileInProjectView and SelectInProjectView.

Fixes #6978
2026-11-30 18:18:33 +08:00
150 змінених файлів з 5156 додано та 249 видалено

No files matched your search

Створено
+1
Переглянути файл
@@ -5116,6 +5116,7 @@ dependencies = [
"ide-text",
"ide-vfs",
"parking_lot 0.12.5",
"quick-xml 0.42.0",
"semver",
"serde",
"serde_json",
+53 -9
Переглянути файл
@@ -85,13 +85,26 @@ gradle.projectsEvaluated {{
pub fn publish(root: &Path, cache: &Path, class_paths: &[String], main_class: &str) -> IdeResult<()> {
let output = PathBuf::from(fs::read_to_string(cache.join("resource-output.txt"))?.trim());
if !output.is_absolute() || !output.is_dir() {
return Err(IdeError::invalid("The resource build did not report an output directory"));
let invalid_output = "The resource build did not report an output directory";
if !output.is_absolute() {
return Err(IdeError::invalid(invalid_output));
}
let output = dunce::canonicalize(output)?;
let output = match fs::metadata(&output) {
Ok(metadata) if metadata.is_dir() => Some(dunce::canonicalize(output)?),
// Gradle's processResources can succeed with NO-SOURCE and never create its destination.
Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
_ => return Err(IdeError::invalid(invalid_output)),
};
let paths: Vec<_> = class_paths.iter().filter_map(|p| dunce::canonicalize(root.join(p)).ok()).collect();
// A separate resource directory is already on the runtime classpath (e.g. build/resources/main).
if paths.contains(&output) {
if output.as_ref().is_some_and(|dir| paths.contains(dir)) {
return Ok(());
}
let previous: Vec<String> = fs::read(cache.join("published-resources.json"))
.ok()
.and_then(|bytes| serde_json::from_slice(&bytes).ok())
.unwrap_or_default();
if output.is_none() && previous.is_empty() {
return Ok(());
}
// jdtls uses bin/main for Gradle, rather than Gradle's build/resources/main.
@@ -99,12 +112,10 @@ pub fn publish(root: &Path, cache: &Path, class_paths: &[String], main_class: &s
let destination = paths.iter().find(|p| p.join(&class_file).is_file()).ok_or_else(|| {
IdeError::invalid("Cannot find the running main class output directory; restart the application")
})?;
let previous: Vec<String> = fs::read(cache.join("published-resources.json"))
.ok()
.and_then(|bytes| serde_json::from_slice(&bytes).ok())
.unwrap_or_default();
let mut current = Vec::new();
copy_resources(&output, &output, destination, &mut current)?;
if let Some(output) = output {
copy_resources(&output, &output, destination, &mut current)?;
}
for rel in previous.iter().filter(|p| !current.contains(p)) {
let path = destination.join(rel);
if path.is_file() {
@@ -220,6 +231,39 @@ mod tests {
}
}
#[test]
fn missing_resource_output_publishes_an_empty_set() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
let output = root.join("build/resources/main");
let cache = root.join("cache");
let runtime = root.join("bin/main");
let class_paths = [runtime.to_string_lossy().into_owned()];
let resource = "application.properties";
fs::create_dir(&cache).unwrap();
fs::create_dir_all(runtime.join("example")).unwrap();
fs::write(cache.join("resource-output.txt"), output.to_string_lossy().as_bytes()).unwrap();
let class = runtime.join("example/Application.class");
fs::write(&class, "running").unwrap();
publish(root, &cache, &class_paths, "example.Application").unwrap();
assert!(!output.exists());
fs::create_dir_all(&output).unwrap();
fs::write(output.join(resource), "server.port=8081").unwrap();
publish(root, &cache, &class_paths, "example.Application").unwrap();
assert!(runtime.join(resource).is_file());
fs::remove_file(output.join(resource)).unwrap();
fs::remove_dir(&output).unwrap();
publish(root, &cache, &class_paths, "example.Application").unwrap();
assert!(!runtime.join(resource).exists());
assert_eq!(fs::read_to_string(class).unwrap(), "running");
fs::write(output, "not a directory").unwrap();
assert!(publish(root, &cache, &class_paths, "example.Application").is_err());
}
#[test]
fn leaves_separate_runtime_resource_directories_in_place_and_rejects_jar_only_runs() {
let tmp = tempfile::tempdir().unwrap();
+23
Переглянути файл
@@ -1176,6 +1176,29 @@ mod tests {
set_env_overlay(Vec::new());
}
#[test]
fn a_child_inside_a_project_gets_its_xcode() {
let root = std::path::Path::new("/openidea-test-process/xcode");
let xcode = "/Applications/Xcode-beta.app/Contents/Developer";
crate::project_env::set_developer_dir(root, Some(xcode.into()));
let developer_dir = |cmd: &Command| {
cmd.get_envs().find(|(n, _)| *n == "DEVELOPER_DIR").and_then(|(_, v)| v.map(OsStr::to_owned))
};
// xcodebuild, xcrun, a language server: a `Command` started in the project.
let mut tool = Command::new("xcodebuild");
prepare(tool.current_dir(root.join("App")));
assert_eq!(developer_dir(&tool), Some(xcode.into()));
// A terminal: a PTY applies the fixes itself.
assert!(host_env_fixes_in(root).contains(&("DEVELOPER_DIR".into(), Some(xcode.into()))));
let mut elsewhere = Command::new("xcodebuild");
prepare(elsewhere.current_dir("/openidea-test-process/other"));
assert_eq!(developer_dir(&elsewhere), None);
crate::project_env::set_developer_dir(root, None);
let mut tool = Command::new("xcodebuild");
prepare(tool.current_dir(root));
assert_eq!(developer_dir(&tool), None, "empty: the system default");
}
#[test]
fn a_child_inside_a_project_gets_its_environment() {
let root = std::path::Path::new("/openidea-test-process/project");
+62 -2
Переглянути файл
@@ -16,13 +16,21 @@ struct Entry {
root: PathBuf,
direnv: Vec<(OsString, Option<OsString>)>,
github_token: Option<OsString>,
developer_dir: Option<OsString>,
changes: Changes,
loading: bool,
}
impl Entry {
fn new(root: PathBuf) -> Self {
Self { root, direnv: Vec::new(), github_token: None, changes: Changes::default(), loading: false }
Self {
root,
direnv: Vec::new(),
github_token: None,
developer_dir: None,
changes: Changes::default(),
loading: false,
}
}
fn rebuild(&mut self) {
@@ -33,11 +41,16 @@ impl Entry {
// `.envrc` entries override the project GitHub token when both define `GH_TOKEN`.
combined.retain(|(k, _)| !self.direnv.iter().any(|(dk, _)| dk == k));
combined.extend(self.direnv.iter().cloned());
// The project's chosen Xcode overrides a `DEVELOPER_DIR` from `.envrc`: it is set for this project only.
if let Some(dir) = &self.developer_dir {
combined.retain(|(k, _)| k != DEVELOPER_DIR);
combined.push((DEVELOPER_DIR.into(), Some(dir.clone())));
}
self.changes = Arc::new(combined);
}
fn is_idle_empty(&self) -> bool {
!self.loading && self.direnv.is_empty() && self.github_token.is_none()
!self.loading && self.direnv.is_empty() && self.github_token.is_none() && self.developer_dir.is_none()
}
}
@@ -144,6 +157,31 @@ pub fn set_github_token(root: &Path, token: Option<OsString>) -> bool {
}
}
const DEVELOPER_DIR: &str = "DEVELOPER_DIR";
/// Sets or clears the `DEVELOPER_DIR` (the Xcode `xcrun`, `xcodebuild` and sourcekit-lsp use)
/// injected for children started in `root`. Returns whether it changed.
pub fn set_developer_dir(root: &Path, dir: Option<OsString>) -> bool {
let dir = dir.filter(|d| !d.is_empty());
let mut entries = entries();
let idx = match entries.iter().position(|e| e.root == root) {
Some(idx) if entries[idx].developer_dir == dir => return false,
Some(idx) => idx,
None if dir.is_none() => return false,
None => {
entries.push(Entry::new(root.to_path_buf()));
entries.len() - 1
}
};
let entry = &mut entries[idx];
entry.developer_dir = dir;
entry.rebuild();
if entry.is_idle_empty() {
entries.remove(idx);
}
true
}
/// The project-scoped `GH_TOKEN` configured for the innermost project holding `dir`, if any.
pub fn github_token(dir: &Path) -> Option<OsString> {
find(&entries(), dir).and_then(|e| e.github_token.clone())
@@ -202,6 +240,28 @@ mod tests {
assert!(for_dir(inner).is_empty());
}
#[test]
fn the_projects_xcode_wins_over_envrc_and_clears() {
let root = Path::new("/openidea-test-env/xcode");
set(root, vec![change("DEVELOPER_DIR", Some("/envrc")), change("A", Some("1"))]);
assert!(set_developer_dir(root, Some("/Applications/Xcode-beta.app/Contents/Developer".into())));
assert!(!set_developer_dir(root, Some("/Applications/Xcode-beta.app/Contents/Developer".into())));
assert_eq!(
*for_dir(&root.join("App")),
[change("A", Some("1")), change("DEVELOPER_DIR", Some("/Applications/Xcode-beta.app/Contents/Developer"))]
);
assert!(set_developer_dir(root, None));
assert_eq!(*for_dir(root), [change("DEVELOPER_DIR", Some("/envrc")), change("A", Some("1"))]);
remove(root);
assert!(for_dir(root).is_empty());
let alone = Path::new("/openidea-test-env/xcode-alone");
assert!(!set_developer_dir(alone, Some("".into())), "empty is the system default");
assert!(set_developer_dir(alone, Some("/X".into())));
assert_eq!(*for_dir(alone), [change("DEVELOPER_DIR", Some("/X"))]);
assert!(set_developer_dir(alone, None));
assert!(entries().iter().all(|e| e.root != alone), "an empty entry is dropped");
}
#[test]
fn waiting_ends_once_the_environment_is_read() {
let root = Path::new("/openidea-test-env/waiting");
+72 -1
Переглянути файл
@@ -1452,6 +1452,7 @@ pub struct LanguagesSettings {
pub arduino: ArduinoSettings,
pub zig: ZigSettings,
pub flutter: FlutterSettings,
pub swift: SwiftSettings,
}
impl Default for LanguagesSettings {
@@ -1485,6 +1486,7 @@ impl Default for LanguagesSettings {
arduino: ArduinoSettings::default(),
zig: ZigSettings::default(),
flutter: FlutterSettings::default(),
swift: SwiftSettings::default(),
}
}
}
@@ -1769,6 +1771,26 @@ pub struct ZigSettings {
pub zig: String,
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct SwiftSettings {
/// The Xcode (`Xcode.app` or its `Contents/Developer`) whose tools the project's sourcekit-lsp,
/// `xcodebuild`, `xcrun` and terminals use, as `DEVELOPER_DIR`. Empty = the `xcode-select` one.
pub xcode: String,
}
impl SwiftSettings {
/// [`Self::xcode`] as a `DEVELOPER_DIR` value (`Xcode.app` gets `/Contents/Developer`); `None` when unset.
pub fn developer_dir(&self) -> Option<std::path::PathBuf> {
let xcode = self.xcode.trim();
if xcode.is_empty() {
return None;
}
let path = std::path::Path::new(xcode);
Some(if path.extension().is_some_and(|e| e == "app") { path.join("Contents/Developer") } else { path.into() })
}
}
/// The Flutter plugin's "Flutter SDK path".
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
@@ -1975,6 +1997,10 @@ pub struct TypeScriptSettings {
/// plugin (hybrid mode; a Vue project's program alone needs ~3 GiB, and the
/// vtsls default 3072 dies in a GC death spiral), else unset (vtsls default).
pub tsserver_max_memory: u32,
/// tsserver's log (`typescript.tsserver.log`). TypeScript: Open TS Server Log opens it.
#[serde(deserialize_with = "or_default")]
#[specta(type = TsServerLog)]
pub tsserver_log: TsServerLog,
/// Problems › TypeScript project errors: the project's own `tsc --watch` per root
/// `tsconfig.json` reports the errors of files that are not open.
pub watch_problems: bool,
@@ -1982,10 +2008,27 @@ pub struct TypeScriptSettings {
impl Default for TypeScriptSettings {
fn default() -> Self {
Self { version: "bundled".into(), tsserver_max_memory: 0, watch_problems: false }
Self {
version: "bundled".into(),
tsserver_max_memory: 0,
tsserver_log: TsServerLog::Off,
watch_problems: false,
}
}
}
/// tsserver's log verbosity, as vtsls' `typescript.tsserver.log` spells it.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum TsServerLog {
#[default]
Off,
Terse,
Normal,
RequestTime,
Verbose,
}
/// Dependency scope for a module dependency or project library (IDEA's Modules › Dependencies).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
@@ -2158,6 +2201,20 @@ impl Settings {
mod tests {
use super::*;
#[test]
fn the_xcode_setting_becomes_a_developer_dir() {
let dir = |xcode: &str| SwiftSettings { xcode: xcode.into() }.developer_dir();
assert_eq!(dir(""), None);
assert_eq!(dir(" "), None);
assert_eq!(dir("/Applications/Xcode-beta.app"), Some("/Applications/Xcode-beta.app/Contents/Developer".into()));
assert_eq!(
dir("/Applications/Xcode.app/Contents/Developer"),
Some("/Applications/Xcode.app/Contents/Developer".into())
);
let s: Settings = serde_json::from_str(r#"{"languages":{"swift":{"xcode":"/X.app"}}}"#).unwrap();
assert_eq!(s.languages.swift.xcode, "/X.app");
}
#[test]
fn ruff_safe_fixes_on_save_default_off_and_round_trip() {
let old: Settings = serde_json::from_str(r#"{"languages":{"ruff":{"runOnSave":true}}}"#).unwrap();
@@ -2168,6 +2225,20 @@ mod tests {
assert_eq!(serde_json::to_value(&on).unwrap()["languages"]["ruff"]["fixOnSave"], true);
}
#[test]
fn tsserver_log_reads_known_levels_and_drops_anything_else() {
let log = |v: &str| {
let s: Settings =
serde_json::from_str(&format!(r#"{{"languages":{{"typescript":{{"tsserverLog":{v}}}}}}}"#)).unwrap();
s.languages.typescript.tsserver_log
};
assert_eq!(log(r#""requestTime""#), TsServerLog::RequestTime);
assert_eq!(log(r#""verbose""#), TsServerLog::Verbose);
assert_eq!(log(r#""--trace""#), TsServerLog::Off);
assert_eq!(log("3"), TsServerLog::Off);
assert_eq!(serde_json::to_value(TsServerLog::RequestTime).unwrap(), "requestTime");
}
#[test]
fn python_interpreter_may_name_a_run_target() {
let python = |interpreter: &str| PythonSettings { interpreter: interpreter.into(), ..Default::default() };
+1 -1
Переглянути файл
@@ -1,6 +1,6 @@
[package]
name = "ide-coverage"
description = "Run with Coverage: coverage-tool launch plans (cargo-llvm-cov, vitest / jest / c8, coverage.py, go test, JaCoCo) and report parsers (lcov, Go cover profiles, JaCoCo and Cobertura XML, SimpleCov, coverage.py data)"
description = "Run with Coverage: coverage-tool launch plans (cargo-llvm-cov, vitest / jest / c8, coverage.py, go test, JaCoCo, xcodebuild) and report parsers (lcov, Go cover profiles, JaCoCo and Cobertura XML, SimpleCov, coverage.py data, xccov)"
version.workspace = true
edition.workspace = true
license.workspace = true
+1 -1
Переглянути файл
@@ -59,7 +59,7 @@ pub(crate) fn parse(text: &str, module: &str, module_dir: &Path) -> Accumulator
impl Accumulator {
/// Removes the branch data of lines whose branches are all taken or all missed.
fn drop_unanimous_branches(&mut self) {
pub(crate) fn drop_unanimous_branches(&mut self) {
for lines in self.files.values_mut() {
for acc in lines.values_mut() {
let taken = acc.branches.values().filter(|t| **t).count();
+26
Переглянути файл
@@ -13,6 +13,7 @@
//! | Ruby (rspec, minitest, rake, scripts) | SimpleCov (`coverage/.resultset.json`) | SimpleCov resultset |
//! | Go (`go test`) | `-coverprofile` | Go cover profile |
//! | Maven / Gradle tests | JaCoCo (plugin goals / an init script) | JaCoCo XML |
//! | Xcode tests (`xcodebuild test`) | `-enableCodeCoverage YES` | the result bundle, read with `xccov` |
//!
//! Lines in the model are 0-based, like every IPC coordinate.
@@ -24,6 +25,7 @@ mod jacoco;
mod lcov;
mod plan;
mod simplecov;
mod xccov;
pub use coveragepy::is_data_file;
pub use import::{import, import_data};
@@ -94,6 +96,8 @@ pub enum CoverageReportSpec {
Jacoco { dir: IpcPath },
/// The tool's raw data is exported to lcov by `argv` first (coverage.py: `… -m coverage lcov -o <lcov>`).
Exported { runner: String, argv: Vec<String>, cwd: IpcPath, env: BTreeMap<String, String>, lcov: IpcPath },
/// An Xcode result bundle, read with `xcrun xccov`; only files under `root` are kept.
Xccov { bundle: IpcPath, root: IpcPath },
}
/// A command line that installs a missing tool (run in the Run tool window).
@@ -234,9 +238,31 @@ pub fn collect(spec: &CoverageReportSpec) -> IdeResult<CoverageSuite> {
let text = read_report(lcov)?;
Ok(lcov::parse(&text, cwd).finish(runner))
}
CoverageReportSpec::Xccov { bundle, root } => {
if !bundle.exists() {
return Err(IdeError::not_found(format!("the run produced no result bundle ({})", bundle.display())));
}
let report = xccov_json(&["--report", "--json"], bundle)?;
let archive = xccov_json(&["--archive", "--json"], bundle)?;
Ok(xccov::parse(&report, &archive, root)
.map_err(|e| IdeError::invalid(format!("unexpected xccov output: {e}")))?
.finish("xccov"))
}
}
}
/// `xcrun xccov view <args> <bundle>`'s output.
fn xccov_json(args: &[&str], bundle: &Path) -> IdeResult<String> {
let out = ide_core::process::prepare(Command::new("xcrun").args(["xccov", "view"]).args(args).arg(bundle))
.output()
.map_err(|e| IdeError::unavailable(format!("cannot run xcrun xccov: {e}")))?;
if !out.status.success() {
let text = ide_core::output_encoding::decode_tool_output(&out.stderr).trim().to_owned();
return Err(IdeError::not_found(format!("the result bundle has no coverage data: {text}")));
}
Ok(String::from_utf8_lossy(&out.stdout).into_owned())
}
fn read_report(path: &Path) -> IdeResult<String> {
std::fs::read_to_string(path).map_err(|e| match e.kind() {
std::io::ErrorKind::NotFound => {
+34
Переглянути файл
@@ -61,6 +61,9 @@ fn ready(
/// data; it must exist (the Gradle init script is written there). Probes tools,
/// so call it from a blocking thread.
pub fn prepare(root: &Path, config: &RunConfig, out: &Path) -> CoveragePrepared {
if config.kind == "xcode-test" {
return xcode(root, config, out);
}
let dir = wrap::run_dir(root, config);
let program = program_name(&config.command);
let first = config.args.first().map(String::as_str).unwrap_or_default();
@@ -336,6 +339,20 @@ fn python(config: &RunConfig, dir: &Path, out: &Path, py: wrap::PythonCommand) -
ready("coverage.py", &config, command, args, report)
}
/// `xcodebuild test` with coverage on, into a result bundle of its own (`xcode::prepare_test`
/// adds it at launch).
fn xcode(root: &Path, config: &RunConfig, out: &Path) -> CoveragePrepared {
let mut config = config.clone();
if let Some(at) = config.args.iter().position(|a| a == "-enableCodeCoverage") {
config.args.drain(at..(at + 2).min(config.args.len()));
}
config.args.extend([s("-enableCodeCoverage"), s("YES")]);
let bundle = out.join("coverage.xcresult");
config.extras.params.insert(s(ide_run::xcode::RESULT_BUNDLE_PARAM), path(&bundle));
let report = CoverageReportSpec::Xccov { bundle: bundle.into(), root: root.to_path_buf().into() };
ready("xccov", &config, config.command.clone(), config.args.clone(), report)
}
#[cfg(test)]
mod tests {
use super::*;
@@ -535,6 +552,23 @@ mod tests {
);
}
#[test]
fn xcode_tests_turn_coverage_on_into_their_own_bundle() {
let dir = tempfile::tempdir().unwrap();
let config = cfg("xcode-test", "xcodebuild", &["test", "-scheme", "App", "-enableCodeCoverage", "NO"]);
let p = prepare(dir.path(), &config, dir.path());
let (l, report) = launch(&p);
assert_eq!(l.args, ["test", "-scheme", "App", "-enableCodeCoverage", "YES"]);
let bundle = dir.path().join("coverage.xcresult");
assert_eq!(l.extras.params[ide_run::xcode::RESULT_BUNDLE_PARAM], bundle.to_string_lossy());
assert!(matches!(report, CoverageReportSpec::Xccov { bundle: b, .. } if (b.as_ref() as &Path) == bundle));
// A trailing flag without a value is replaced too.
let config = cfg("xcode-test", "xcodebuild", &["test", "-enableCodeCoverage"]);
let p = prepare(dir.path(), &config, dir.path());
assert_eq!(launch(&p).0.args, ["test", "-enableCodeCoverage", "YES"]);
}
#[test]
fn unknown_commands_are_unsupported() {
let dir = tempfile::tempdir().unwrap();
+188
Переглянути файл
@@ -0,0 +1,188 @@
//! Xcode coverage (`xcodebuild test -enableCodeCoverage YES`), read from the result bundle:
//!
//! - `xcrun xccov view --report --json <bundle>`: the targets and their files. Files that only
//! test bundles (`*.xctest`) compile are left out.
//! - `xcrun xccov view --archive --json <bundle>`: `{ "<path>": [{ line, isExecutable,
//! executionCount, subranges? }] }` for every file. A subrange is a region of the line with its
//! own count; a covered line with a missed region is partial.
use crate::Accumulator;
use serde::Deserialize;
use std::collections::{BTreeMap, BTreeSet};
use std::path::{Component, Path, PathBuf};
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct Report {
#[serde(default)]
targets: Vec<Target>,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct Target {
#[serde(default)]
build_product_path: String,
#[serde(default)]
files: Vec<ReportFile>,
}
#[derive(Deserialize)]
struct ReportFile {
path: String,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct Line {
line: u32,
is_executable: bool,
#[serde(default)]
execution_count: u64,
#[serde(default)]
subranges: Vec<Subrange>,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct Subrange {
column: u32,
#[serde(default)]
length: u32,
#[serde(default)]
execution_count: u64,
}
/// `path` inside the project as the project names it: the project and xccov may name it through
/// different symlinks (`/tmp` and `/private/tmp`). `None` outside the project and for DerivedData.
fn in_project(path: &Path, root: &Path, real_root: &Path) -> Option<PathBuf> {
let real;
let rel = match path.strip_prefix(root) {
Ok(rel) => rel,
Err(_) => {
real = path.canonicalize().ok()?;
real.strip_prefix(real_root).ok()?
}
};
let generated = rel.components().any(|c| matches!(c, Component::Normal(n) if n == "DerivedData" || n == ".build"));
(!generated).then(|| root.join(rel))
}
pub(crate) fn parse(report: &str, archive: &str, root: &Path) -> Result<Accumulator, serde_json::Error> {
let report: Report = serde_json::from_str(report)?;
let archive: BTreeMap<String, Vec<Line>> = serde_json::from_str(archive)?;
// App and framework sources: a file listed by an app or framework target counts even when a test
// bundle compiles it too (sources added to the test target's membership instead of `@testable`).
let is_test_bundle = |t: &Target| {
Path::new(&t.build_product_path)
.components()
.any(|c| matches!(c, Component::Normal(n) if Path::new(n).extension().is_some_and(|e| e == "xctest")))
};
let real_root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
// Both views go through `in_project`, so they match however each spells the path.
let sources: BTreeSet<PathBuf> = report
.targets
.iter()
.filter(|t| !is_test_bundle(t))
.flat_map(|t| &t.files)
.filter_map(|f| in_project(Path::new(&f.path), root, &real_root))
.collect();
let mut acc = Accumulator::default();
for (file, lines) in &archive {
let Some(path) = in_project(Path::new(file), root, &real_root).filter(|p| sources.contains(p)) else {
continue;
};
acc.file(&path);
for l in lines.iter().filter(|l| l.is_executable && l.line > 0) {
let n = l.line - 1;
acc.line(&path, n, l.execution_count);
if !l.subranges.is_empty() {
acc.branch(&path, n, "line".into(), l.execution_count > 0);
for r in &l.subranges {
acc.branch(&path, n, format!("{}+{}", r.column, r.length), r.execution_count > 0);
}
}
}
}
// Regions are not branches: keep only the partial marks of lines with mixed regions.
acc.drop_unanimous_branches();
Ok(acc)
}
#[cfg(test)]
mod tests {
use super::*;
// Captured from `xcodebuild test -enableCodeCoverage YES` (Xcode 27.1) on an app with a unit
// test target; paths rewritten to /Users/me.
const REPORT: &str = include_str!("../tests/fixtures/xccov-report.json");
const ARCHIVE: &str = include_str!("../tests/fixtures/xccov-archive.json");
#[test]
fn reads_app_sources_and_leaves_out_test_bundles() {
let suite = parse(REPORT, ARCHIVE, Path::new("/Users/me/CovDemo")).unwrap().finish("xccov");
assert!(!suite.has_branches);
let names: Vec<_> = suite.files.iter().map(|f| f.path.as_ref() as &Path).collect();
assert_eq!(
names,
[Path::new("/Users/me/CovDemo/CovDemo/App.swift"), Path::new("/Users/me/CovDemo/CovDemo/Calculator.swift")]
);
// xccov's own totals for Calculator.swift: 14 of 17 lines.
let calc = &suite.files[1];
assert_eq!((calc.lines_total, calc.lines_covered), (17, 14));
let at = |n: u32| calc.lines.iter().find(|l| l.line == n).unwrap();
// `return nil` (line 8) never ran; `if b == 0 {` (line 7) ran with a missed region.
assert_eq!(at(7).hits, 0);
assert!(at(6).partial());
assert!(!at(1).partial());
}
#[test]
fn files_outside_the_project_are_dropped() {
let suite = parse(REPORT, ARCHIVE, Path::new("/Users/me/Other")).unwrap().finish("xccov");
assert!(suite.files.is_empty());
let report = r#"{"targets":[{"buildProductPath":"/d/App.app/App","files":[{"path":"/p/DerivedData/G.swift"},{"path":"/p/A.swift"}]}]}"#;
let line = r#"[{"line":1,"isExecutable":true,"executionCount":2}]"#;
let archive = format!(r#"{{"/p/DerivedData/G.swift":{line},"/p/A.swift":{line}}}"#);
let suite = parse(report, &archive, Path::new("/p")).unwrap().finish("xccov");
assert_eq!(suite.files.len(), 1);
assert_eq!(suite.files[0].lines[0].hits, 2);
}
#[test]
fn a_file_of_an_app_and_a_test_bundle_counts() {
let report = r#"{"targets":[
{"buildProductPath":"/d/App.app/App","files":[{"path":"/p/A.swift"}]},
{"buildProductPath":"/d/AppTests.xctest/AppTests","files":[{"path":"/p/A.swift"},{"path":"/p/T.swift"}]}]}"#;
let line = r#"[{"line":1,"isExecutable":true,"executionCount":1}]"#;
let archive = format!(r#"{{"/p/A.swift":{line},"/p/T.swift":{line}}}"#);
let suite = parse(report, &archive, Path::new("/p")).unwrap().finish("xccov");
let names: Vec<_> = suite.files.iter().map(|f| f.path.as_ref() as &Path).collect();
assert_eq!(names, [Path::new("/p/A.swift")]);
}
#[cfg(unix)]
#[test]
fn paths_through_another_symlink_map_to_the_project() {
let dir = tempfile::tempdir().unwrap();
let real = dir.path().canonicalize().unwrap().join("real");
std::fs::create_dir_all(&real).unwrap();
std::fs::write(real.join("A.swift"), "").unwrap();
let link = dir.path().join("link");
std::os::unix::fs::symlink(&real, &link).unwrap();
let file = real.join("A.swift").to_string_lossy().into_owned();
let report =
format!(r#"{{"targets":[{{"buildProductPath":"/d/App.app/App","files":[{{"path":"{file}"}}]}}]}}"#);
let archive = format!(r#"{{"{file}":[{{"line":1,"isExecutable":true,"executionCount":1}}]}}"#);
let suite = parse(&report, &archive, &link).unwrap().finish("xccov");
assert_eq!(suite.files.len(), 1);
assert_eq!(suite.files[0].path.as_ref() as &Path, link.join("A.swift"));
// The report names the file through the symlink, the archive by its real path.
let linked = link.join("A.swift").to_string_lossy().into_owned();
let report = report.replace(&file, &linked);
let suite = parse(&report, &archive, &link).unwrap().finish("xccov");
assert_eq!(suite.files.len(), 1);
assert_eq!(suite.files[0].lines[0].hits, 1);
}
}
+226
Переглянути файл
@@ -0,0 +1,226 @@
{
"/Users/me/CovDemo/CovDemo/App.swift": [
{
"isExecutable": false,
"line": 1
},
{
"isExecutable": false,
"line": 2
},
{
"isExecutable": false,
"line": 3
},
{
"isExecutable": false,
"line": 4
},
{
"executionCount": 1,
"isExecutable": true,
"line": 5
},
{
"executionCount": 1,
"isExecutable": true,
"line": 6
},
{
"executionCount": 1,
"isExecutable": true,
"line": 7
}
],
"/Users/me/CovDemo/CovDemo/Calculator.swift": [
{
"isExecutable": false,
"line": 1
},
{
"executionCount": 1,
"isExecutable": true,
"line": 2
},
{
"executionCount": 1,
"isExecutable": true,
"line": 3
},
{
"executionCount": 1,
"isExecutable": true,
"line": 4
},
{
"isExecutable": false,
"line": 5
},
{
"executionCount": 1,
"isExecutable": true,
"line": 6
},
{
"executionCount": 1,
"isExecutable": true,
"line": 7,
"subranges": [
{
"column": 19,
"executionCount": 0,
"length": 0
}
]
},
{
"executionCount": 0,
"isExecutable": true,
"line": 8
},
{
"executionCount": 1,
"isExecutable": true,
"line": 9,
"subranges": [
{
"column": 1,
"executionCount": 0,
"length": 9
}
]
},
{
"executionCount": 1,
"isExecutable": true,
"line": 10
},
{
"executionCount": 1,
"isExecutable": true,
"line": 11
},
{
"isExecutable": false,
"line": 12
},
{
"executionCount": 1,
"isExecutable": true,
"line": 13
},
{
"executionCount": 1,
"isExecutable": true,
"line": 14,
"subranges": [
{
"column": 18,
"executionCount": 0,
"length": 0
}
]
},
{
"executionCount": 0,
"isExecutable": true,
"line": 15
},
{
"executionCount": 1,
"isExecutable": true,
"line": 16,
"subranges": [
{
"column": 1,
"executionCount": 0,
"length": 9
},
{
"column": 26,
"executionCount": 0,
"length": 0
}
]
},
{
"executionCount": 0,
"isExecutable": true,
"line": 17
},
{
"executionCount": 1,
"isExecutable": true,
"line": 18,
"subranges": [
{
"column": 1,
"executionCount": 0,
"length": 9
}
]
},
{
"executionCount": 1,
"isExecutable": true,
"line": 19
},
{
"executionCount": 1,
"isExecutable": true,
"line": 20
}
],
"/Users/me/CovDemo/CovDemoTests/CalculatorTests.swift": [
{
"isExecutable": false,
"line": 1
},
{
"isExecutable": false,
"line": 2
},
{
"isExecutable": false,
"line": 3
},
{
"isExecutable": false,
"line": 4
},
{
"executionCount": 1,
"isExecutable": true,
"line": 5
},
{
"executionCount": 1,
"isExecutable": true,
"line": 6
},
{
"executionCount": 1,
"isExecutable": true,
"line": 7
},
{
"isExecutable": false,
"line": 8
},
{
"executionCount": 1,
"isExecutable": true,
"line": 9
},
{
"executionCount": 1,
"isExecutable": true,
"line": 10
},
{
"executionCount": 1,
"isExecutable": true,
"line": 11
}
]
}
+140
Переглянути файл
@@ -0,0 +1,140 @@
{
"coveredLines": 28,
"executableLines": 31,
"lineCoverage": 0.9032258064516129,
"targets": [
{
"buildProductPath": "/Users/me/Library/Developer/Xcode/DerivedData/CovDemo-abc/Build/Products/Debug-iphonesimulator/CovDemo.app/CovDemo",
"coveredLines": 18,
"executableLines": 21,
"files": [
{
"coveredLines": 14,
"executableLines": 17,
"functions": [
{
"coveredLines": 3,
"executableLines": 3,
"executionCount": 1,
"lineCoverage": 1,
"lineNumber": 2,
"name": "Calculator.add(_:_:)"
},
{
"coveredLines": 5,
"executableLines": 6,
"executionCount": 1,
"lineCoverage": 0.8333333333333334,
"lineNumber": 6,
"name": "Calculator.divide(_:_:)"
},
{
"coveredLines": 6,
"executableLines": 8,
"executionCount": 1,
"lineCoverage": 0.75,
"lineNumber": 13,
"name": "Calculator.describe(_:)"
}
],
"lineCoverage": 0.8235294117647058,
"name": "Calculator.swift",
"path": "/Users/me/CovDemo/CovDemo/Calculator.swift"
},
{
"coveredLines": 4,
"executableLines": 4,
"functions": [
{
"coveredLines": 3,
"executableLines": 3,
"executionCount": 1,
"lineCoverage": 1,
"lineNumber": 5,
"name": "CovDemoApp.body.getter"
},
{
"coveredLines": 1,
"executableLines": 1,
"executionCount": 1,
"lineCoverage": 1,
"lineNumber": 6,
"name": "closure #1 in CovDemoApp.body.getter"
}
],
"lineCoverage": 1,
"name": "App.swift",
"path": "/Users/me/CovDemo/CovDemo/App.swift"
}
],
"lineCoverage": 0.8571428571428571,
"name": "CovDemo.app"
},
{
"buildProductPath": "/Users/me/Library/Developer/Xcode/DerivedData/CovDemo-abc/Build/Products/Debug-iphonesimulator/CovDemo.app/PlugIns/CovDemoTests.xctest/CovDemoTests",
"coveredLines": 10,
"executableLines": 10,
"files": [
{
"coveredLines": 10,
"executableLines": 10,
"functions": [
{
"coveredLines": 3,
"executableLines": 3,
"executionCount": 1,
"lineCoverage": 1,
"lineNumber": 5,
"name": "CalculatorTests.testAdd()"
},
{
"coveredLines": 1,
"executableLines": 1,
"executionCount": 1,
"lineCoverage": 1,
"lineNumber": 6,
"name": "implicit closure #1 in CalculatorTests.testAdd()"
},
{
"coveredLines": 1,
"executableLines": 1,
"executionCount": 1,
"lineCoverage": 1,
"lineNumber": 6,
"name": "implicit closure #2 in CalculatorTests.testAdd()"
},
{
"coveredLines": 3,
"executableLines": 3,
"executionCount": 1,
"lineCoverage": 1,
"lineNumber": 9,
"name": "CalculatorTests.testDivide()"
},
{
"coveredLines": 1,
"executableLines": 1,
"executionCount": 1,
"lineCoverage": 1,
"lineNumber": 10,
"name": "implicit closure #1 in CalculatorTests.testDivide()"
},
{
"coveredLines": 1,
"executableLines": 1,
"executionCount": 1,
"lineCoverage": 1,
"lineNumber": 10,
"name": "implicit closure #2 in CalculatorTests.testDivide()"
}
],
"lineCoverage": 1,
"name": "CalculatorTests.swift",
"path": "/Users/me/CovDemo/CovDemoTests/CalculatorTests.swift"
}
],
"lineCoverage": 1,
"name": "CovDemoTests.xctest"
}
]
}
+7 -4
Переглянути файл
@@ -362,21 +362,24 @@ fn find_binary_in(
/// [`find_binary`], plus Xcode's toolchain on macOS (`xcrun -f lldb-dap`): Xcode ships
/// lldb-dap without putting it on `PATH`.
pub fn resolve_binary(command: &str, cwd: &Path) -> Option<PathBuf> {
find_binary(command, cwd).or_else(|| xcrun_tool(command))
find_binary(command, cwd).or_else(|| xcrun_tool(command, cwd))
}
/// `cwd`, inside a project, picks the project's Xcode (`DEVELOPER_DIR`).
#[cfg(target_os = "macos")]
fn xcrun_tool(command: &str) -> Option<PathBuf> {
fn xcrun_tool(command: &str, cwd: &Path) -> Option<PathBuf> {
if command != "lldb-dap" {
return None;
}
let out = std::process::Command::new("/usr/bin/xcrun").args(["-f", command]).stderr(Stdio::null()).output().ok()?;
let mut cmd = std::process::Command::new("/usr/bin/xcrun");
cmd.current_dir(cwd);
let out = ide_core::process::prepare(&mut cmd).args(["-f", command]).stderr(Stdio::null()).output().ok()?;
let path = PathBuf::from(String::from_utf8_lossy(&out.stdout).trim());
(out.status.success() && is_executable(&path, false)).then_some(path)
}
#[cfg(not(target_os = "macos"))]
fn xcrun_tool(_command: &str) -> Option<PathBuf> {
fn xcrun_tool(_command: &str, _cwd: &Path) -> Option<PathBuf> {
None
}
+2 -1
Переглянути файл
@@ -618,9 +618,10 @@ pub(crate) fn take_debug_server(arguments: &mut Value) -> IdeResult<Option<Debug
/// lldb-dap's ``/usr/lib/swift/libswiftCore.dylib`swift_willThrow`` for a frame without
/// debug info. Opening it would show an error tab; without a path the stop selects the
/// first frame with source instead. Non-file paths (`jdt://`, `<node_internals>`) stay.
/// Rooted rather than absolute: on Windows a `/usr/…` path has a root but no drive.
fn is_pseudo_path(source: Option<&Value>, path: &str) -> bool {
let reference = source.and_then(|s| s.get("sourceReference")).and_then(Value::as_i64).unwrap_or(0);
reference > 0 && Path::new(path).is_absolute() && !Path::new(path).exists()
reference > 0 && Path::new(path).has_root() && !Path::new(path).exists()
}
/// DAP stack frame → [`StackFrame`] (1-based → 0-based).
+1
Переглянути файл
@@ -31,6 +31,7 @@ pub mod trust;
mod ts_code_style;
mod tsc_watch;
pub mod web_server;
mod xcode_env;
pub use project::{Project, history_retention};
+2
Переглянути файл
@@ -277,6 +277,7 @@ pub fn spec(os: Os) -> Vec<Entry> {
act("file.exportSettings", "Export Settings…"),
act("file.importSettings", "Import Settings…"),
act("file.importJetBrainsSettings", "Import Settings from JetBrains IDE…"),
act("file.importJetBrainsRecentProjects", "Import Recent Projects from JetBrains IDE…"),
act("file.syncSettings", "Sync Settings Now"),
],
),
@@ -484,6 +485,7 @@ pub fn spec(os: Os) -> Vec<Entry> {
act("navigate.declaration", "Declaration or Usages"),
act("navigate.implementation", "Implementation(s)"),
act("navigate.typeDeclaration", "Type Declaration"),
act("navigate.sourceDefinition", "Source Definition"),
act("navigate.superMethod", "Super Method"),
act("navigate.gotoTest", "Test"),
act("navigate.relatedSymbol", "Related Symbol…"),
+1 -1
Переглянути файл
@@ -17,7 +17,7 @@ pub async fn ios_simulators(host: &Host, window: &str) -> IdeResult<Option<Vec<I
if !cfg!(target_os = "macos") || !simulator::is_xcode_project(&root) {
return Ok(None);
}
blocking(simulator::list).await.map(Some)
blocking(move || simulator::list(&root)).await.map(Some)
}
/// Boots a simulator; returns once it is booted.
+50
Переглянути файл
@@ -675,6 +675,53 @@ pub async fn lsp_switch_source_header(
Ok(result?.map(|path| path.to_string_lossy().into_owned()))
}
/// Go to Source Definition (vtsls): the JavaScript implementation of the symbol at `pos`
/// instead of its `.d.ts`. Cancel with `cancel_request(request)`.
#[command(trust = trusted)]
pub async fn lsp_source_definition(
host: &Host,
window: &str,
request: RequestId,
doc: DocId,
pos: Pos,
) -> IdeResult<Vec<Location>> {
let lsp = host.project(window)?.lsp.clone();
let cancel = host.begin_request(request);
let result = tokio::select! {
result = lsp.source_definition(doc, pos, cancel.clone()) => result,
_ = cancel.cancelled() => Err(ide_core::IdeError::cancelled()),
};
host.end_request(request);
result
}
/// Has vtsls open the document's `tsconfig.json` / `jsconfig.json` or the TS Server log.
#[command(trust = trusted)]
pub async fn lsp_open_typescript_file(host: &Host, window: &str, doc: DocId, what: TypeScriptFile) -> IdeResult<()> {
let lsp = host.project(window)?.lsp.clone();
lsp.open_typescript_file(doc, what).await
}
/// The files tsserver suggests for vtsls' Move to File code action `command`. Cancel with
/// `cancel_request(request)`.
#[command(trust = trusted)]
pub async fn lsp_move_to_file_targets(
host: &Host,
window: &str,
request: RequestId,
doc: DocId,
command: Command,
) -> IdeResult<Vec<ide_core::IpcPath>> {
let lsp = host.project(window)?.lsp.clone();
let cancel = host.begin_request(request);
let result = tokio::select! {
result = lsp.move_to_file_targets(doc, command, cancel.clone()) => result,
_ = cancel.cancelled() => Err(ide_core::IdeError::cancelled()),
};
host.end_request(request);
Ok(result?.into_iter().map(ide_core::IpcPath::from).collect())
}
/// Implementations of the symbols at `positions`, one list per position (the
/// editor's "is implemented / overridden" gutter markers). Cancel with
/// `cancel_request(request)`.
@@ -3344,6 +3391,9 @@ ide_command::domain!(
lsp_implementation_locations,
lsp_file_references,
lsp_switch_source_header,
lsp_source_definition,
lsp_open_typescript_file,
lsp_move_to_file_targets,
lsp_implementations,
lsp_inlay_hints,
lsp_inline_completion,
+6
Переглянути файл
@@ -468,6 +468,12 @@ pub fn set_settings(
}
});
}
if ["languages", "languages.swift", "languages.swift.xcode"].contains(&key) {
// An untrusted project keeps no Xcode of its own (see `xcode_env`).
for project in affected().into_iter().filter(|p| p.is_trusted()) {
host.runtime.spawn(async move { crate::xcode_env::apply_and_restart(&project).await });
}
}
// `flutter daemon` and DevTools run on the Flutter SDK; the next request starts DevTools again.
if ["languages", "languages.flutter", "languages.flutter.sdk"].contains(&key) {
for project in affected() {
+2 -1
Переглянути файл
@@ -575,9 +575,10 @@ async fn start_inner(
}
if config.kind == "xcode-test" {
let bundles = project.cache_dir.join("xcresult");
let dir = project.root.clone();
config = host
.blocking(move || {
ide_run::xcode::prepare_test(&mut config, &bundles)?;
ide_run::xcode::prepare_test(&mut config, &dir, &bundles)?;
Ok(config)
})
.await?;
+2
Переглянути файл
@@ -30,6 +30,8 @@ pub async fn run_xcode_test_results(host: &Host, window: &str, bundle: std::path
return Err(IdeError::invalid("Not an Xcode result bundle"));
}
let mut cmd = tokio::process::Command::new("xcrun");
// The project's Xcode reads the bundle its `xcodebuild` wrote.
cmd.current_dir(&host.project(window)?.root);
cmd.args(["xcresulttool", "get", "test-results", "tests", "--compact", "--path"]).arg(&bundle);
ide_core::process::prepare(cmd.as_std_mut());
let out = cmd.output().await?;
+24 -2
Переглянути файл
@@ -422,6 +422,10 @@ pub struct PluginHost {
initial_load: (Mutex<bool>, Condvar),
/// `on-startup-finished` has fired.
startup_finished: AtomicBool,
/// Language, file and view activation events fired so far (with their project), so a plugin
/// installed or synced afterwards (a remote server gets its packages after the window opened
/// files) still activates for a Twig file that is already open.
fired_activations: Mutex<Vec<(ActivationEvent, Option<PathBuf>)>>,
/// The theme last announced with `ThemeChanged`.
announced_theme: Mutex<Option<ActiveTheme>>,
/// [`PluginLanguages::revision`] last announced with `LanguagesChanged`.
@@ -541,6 +545,7 @@ impl PluginHost {
lifecycle: Mutex::new(()),
initial_load: (Mutex::new(false), Condvar::new()),
startup_finished: AtomicBool::new(false),
fired_activations: Mutex::new(Vec::new()),
announced_theme: Mutex::new(None),
announced_languages: AtomicU64::new(0),
announced_skills: AtomicU64::new(0),
@@ -699,6 +704,16 @@ impl PluginHost {
/// Fires an activation event from the UI (`on-language:rust`, `on-file:…`, `on-view:…`).
pub fn activation_event(&self, event: &ActivationEvent, project: Option<&Path>) {
{
let mut fired = self.fired_activations.lock();
let entry = (event.clone(), project.map(Path::to_path_buf));
if !fired.contains(&entry) {
if fired.len() >= MAX_FIRED_ACTIVATIONS {
fired.remove(0);
}
fired.push(entry);
}
}
let targets: Vec<_> = self
.plugins
.read()
@@ -3096,8 +3111,12 @@ impl PluginHost {
meta.pending = pending;
meta.status = if plugin.manifest().wasm.is_some() { PluginStatus::Inactive } else { PluginStatus::Static };
}
let eager = plugin.manifest().activation.contains(&ActivationEvent::StartupFinished)
&& self.startup_finished.load(Ordering::Acquire);
let eager = (plugin.manifest().activation.contains(&ActivationEvent::StartupFinished)
&& self.startup_finished.load(Ordering::Acquire))
|| self.fired_activations.lock().iter().any(|(event, project)| {
(plugin.dev_root.is_none() || plugin.dev_root == *project)
&& plugin.manifest().activation.iter().any(|a| activation_matches(a, event))
});
if eager {
let _ = self.ensure_active(plugin, None);
}
@@ -3725,6 +3744,9 @@ fn counts(m: &Manifest) -> Vec<ContributionCount> {
m.declaration_counts().into_iter().map(|(point, count)| ContributionCount { point, count }).collect()
}
/// How many fired activation events [`PluginHost::activation_event`] remembers (oldest dropped first).
const MAX_FIRED_ACTIVATIONS: usize = 512;
fn activation_matches(declared: &ActivationEvent, fired: &ActivationEvent) -> bool {
match (declared, fired) {
(ActivationEvent::Language(a), ActivationEvent::Language(b)) => a == b || a == "*",
+2
Переглянути файл
@@ -773,6 +773,8 @@ impl Host {
let weak = Arc::downgrade(&project);
project.agents.set_git_enabled_hook(Arc::new(move || weak.upgrade().is_some_and(|p| p.git_enabled())));
}
// Before anything starts a language server or a tool in the project; a trusted project only.
crate::xcode_env::apply(&project);
self.insert_project(window, project.clone());
for (key, text, dirty) in &carried {
let _ = project.documents.restore_untitled_buffer(key, text, *dirty);
+2
Переглянути файл
@@ -276,6 +276,8 @@ impl crate::Host {
}
project.lsp.set_execution_allowed(false);
}
// Before anything runs `git` (a `/usr/bin` shim that follows `DEVELOPER_DIR`): set or cleared.
crate::xcode_env::apply(&project);
project.repos();
if trusted {
if let Some(cmd) = self.environment.project_opened(&project.root, &project.sink) {
+49
Переглянути файл
@@ -0,0 +1,49 @@
//! The project's Xcode (`languages.swift.xcode`): every child started in the project gets it as
//! `DEVELOPER_DIR` through [`ide_core::project_env`] — sourcekit-lsp, `xcodebuild` and `xcrun` of
//! runs, tests, coverage and debugging, and terminals.
use crate::project::Project;
use ide_core::settings::SwiftSettings;
use std::path::PathBuf;
/// The `DEVELOPER_DIR` a project's children get. Only a trusted project's: the setting lives in the
/// repository (`.openidea/settings.toml`), and the `/usr/bin` shims (`git`, `xcrun`, `clang`, …)
/// run `$DEVELOPER_DIR/usr/bin/<tool>`, so an untrusted one could point them at its own binaries.
fn developer_dir(trusted: bool, swift: &SwiftSettings) -> Option<PathBuf> {
trusted.then(|| swift.developer_dir()).flatten()
}
/// Applies the project's Xcode to its environment, or clears it for an untrusted project; returns
/// whether it changed.
pub fn apply(project: &Project) -> bool {
let trusted = project.is_trusted() && !project.light;
let dir = developer_dir(trusted, &project.settings.effective().languages.swift).map(Into::into);
let root = ide_core::project_env::set_developer_dir(&project.root, dir.clone());
let worktrees = ide_core::project_env::set_developer_dir(project.agents.worktrees_dir(), dir);
root || worktrees
}
/// [`apply`], then restarts a running sourcekit-lsp when the Xcode changed.
pub async fn apply_and_restart(project: &Project) {
if !apply(project) {
return;
}
for server in project.lsp.servers().into_iter().filter(|s| s.name == "sourcekit-lsp") {
if let Err(e) = project.lsp.restart(server.id).await {
tracing::warn!("restarting sourcekit-lsp for the new Xcode: {e}");
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn only_a_trusted_project_gets_its_xcode() {
let swift = SwiftSettings { xcode: "./x.app".into() };
assert_eq!(developer_dir(false, &swift), None, "untrusted: the repository's own binaries must not run");
assert_eq!(developer_dir(true, &swift), Some("./x.app/Contents/Developer".into()));
assert_eq!(developer_dir(true, &SwiftSettings::default()), None);
}
}
+10 -3
Переглянути файл
@@ -1166,8 +1166,12 @@ async fn agent_commands_run_in_named_tabs_and_report_what_the_user_did() {
assert_eq!(stopped["state"], "stoppedByAgent", "{stopped}");
assert!(stopped.get("interventions").is_none());
// The user's Stop, rerun and closing the tab are reported with their time.
h.json("run_command", json!({"name": "server", "command": "sleep 30", "timeout": 0})).await;
// The user's Stop, rerun and closing the tab are reported with their time. A stop waits for the command
// itself: a Ctrl+C while the login shell still reads its profile can be taken by a profile command that
// handles it, and the shell then runs the command anyway.
let ready = json!({"name": "server", "command": "echo ready; sleep 30", "pattern": "(?m)^ready", "timeout": 10000});
let ready = h.json("run_command", ready).await;
assert_eq!((&ready["waitEnded"], &ready["state"]), (&json!("matched"), &json!("running")), "{ready}");
ide_host::ops::run::run_stop(&h.host, "main", agent_process(&h, "_agent_server")).unwrap();
let stop = h.json("wait_for_run", json!({"name": "server", "timeout": 10000})).await;
assert!(stop["interventions"][0]["message"].as_str().unwrap().starts_with("The user stopped this command at"));
@@ -1217,7 +1221,10 @@ async fn agent_commands_run_in_named_tabs_and_report_what_the_user_did() {
assert_eq!(head["output"], "one\n<<<...content truncated...>>>\n", "{head}");
// Ctrl+C stops the command as stop_run does; terminal keys have no meaning on pipes.
h.json("run_command", json!({"name": "interrupt", "command": "sleep 30", "timeout": 0})).await;
let ready =
json!({"name": "interrupt", "command": "echo ready; sleep 30", "pattern": "(?m)^ready", "timeout": 10000});
let ready = h.json("run_command", ready).await;
assert_eq!((&ready["waitEnded"], &ready["state"]), (&json!("matched"), &json!("running")), "{ready}");
let key = h.error("send_run_input", json!({"name": "interrupt", "keys": ["Up"]})).await;
assert!(key.contains("runs on pipes"), "{key}");
h.json("send_run_input", json!({"name": "interrupt", "keys": ["Ctrl+C"]})).await;
+22
Переглянути файл
@@ -1590,6 +1590,28 @@ fn misbehave_with_language(dir: &Path) -> PathBuf {
pkg
}
/// A language activation fired before the plugin was there (a remote server gets the desktop's
/// packages after the window opened its files; a plugin installed with such a file open)
/// activates it once it loads; one that never fired doesn't.
#[test]
fn plugins_loaded_after_their_activation_event_fired_activate() {
use ide_extension::ActivationEvent;
let tmp = tempfile::tempdir().unwrap();
let host = Arc::new(
PluginHost::new(tmp.path().join("plugins"), Arc::new(|_: Option<&str>, _| {}), Limits::default()).unwrap(),
);
host.load_all();
host.startup_finished();
host.activation_event(&ActivationEvent::Language("other".into()), None);
host.install_from_dir(&misbehave_with_language(tmp.path()), &Consent::all()).unwrap();
assert_eq!(host.info_of("misbehave").unwrap().status, PluginStatus::Inactive);
host.uninstall("misbehave").unwrap();
host.activation_event(&ActivationEvent::Language("mis".into()), None);
host.install_from_dir(&misbehave_with_language(tmp.path()), &Consent::all()).unwrap();
assert!(eventually(|| host.info_of("misbehave").is_ok_and(|i| i.status == PluginStatus::Active)));
}
/// Edit-path calls stop waiting at the soft deadline (the result is
/// dropped, the instance kept) and are interrupted at the hard one.
#[test]
+121 -15
Переглянути файл
@@ -2,6 +2,7 @@
//! speak (a WebSocket): direct, or through an HTTP proxy's `CONNECT` tunnel.
use base64::Engine;
use hyper_util::client::proxy::matcher::Matcher;
use ide_core::proxy_settings::ProxyRoute;
use ide_core::{IdeError, IdeResult};
use std::time::Duration;
@@ -10,30 +11,68 @@ use tokio::net::TcpStream;
const CONNECT_TIMEOUT: Duration = Duration::from_secs(30);
/// The PAC lookup of the system proxy settings; none outside macOS.
#[cfg(target_os = "macos")]
const SYSTEM_PAC: fn(&str) -> Option<ProxyRoute> = crate::system_pac_route;
#[cfg(not(target_os = "macos"))]
const SYSTEM_PAC: fn(&str) -> Option<ProxyRoute> = |_| None;
/// A connection to `url`'s host and port, through the proxy System Settings › HTTP Proxy
/// (or, in Auto mode, the system) routes that host to.
pub async fn connect(url: &reqwest::Url) -> IdeResult<TcpStream> {
let route = ide_core::proxy_settings::proxy().route(url.host_str());
connect_with(url, route, SYSTEM_PAC, Matcher::from_system).await
}
/// The URI the system proxy settings are asked about: the scheme reqwest would use (`ws` → `http`).
fn system_uri(url: &reqwest::Url) -> IdeResult<http::Uri> {
let host = url.host_str().ok_or_else(|| IdeError::invalid("the URL has no host"))?;
let port = url.port_or_known_default().ok_or_else(|| IdeError::invalid("the URL has no port"))?;
let target = if host.contains(':') { format!("[{host}]:{port}") } else { format!("{host}:{port}") };
let proxy = match ide_core::proxy_settings::proxy().route(Some(host)) {
let scheme = if url.scheme() == "wss" || url.scheme() == "https" { "https" } else { "http" };
format!("{scheme}://{target}/").parse().map_err(|_| IdeError::invalid("invalid host"))
}
/// `connect` with the proxy settings' `route`, the PAC lookup and the system matcher injected.
async fn connect_with(
url: &reqwest::Url,
route: ProxyRoute,
pac: impl FnOnce(&str) -> Option<ProxyRoute> + Send + 'static,
matcher: impl FnOnce() -> Matcher,
) -> IdeResult<TcpStream> {
let host = url.host_str().ok_or_else(|| IdeError::invalid("the URL has no host"))?;
let port = url.port_or_known_default().ok_or_else(|| IdeError::invalid("the URL has no port"))?;
let target = if host.contains(':') { format!("[{host}]:{port}") } else { format!("{host}:{port}") };
let proxy = match route {
ProxyRoute::Direct => None,
ProxyRoute::Via(via) => Some(via),
ProxyRoute::System => {
// The system proxy of the scheme reqwest would use (`ws` → `http`).
let scheme = if url.scheme() == "wss" || url.scheme() == "https" { "https" } else { "http" };
let uri: http::Uri =
format!("{scheme}://{target}/").parse().map_err(|_| IdeError::invalid("invalid host"))?;
hyper_util::client::proxy::matcher::Matcher::from_system().intercept(&uri).map(|intercept| {
let auth =
intercept.raw_auth().map(|(user, password)| format!("{user}:{password}@")).unwrap_or_default();
let uri = intercept.uri();
format!(
"{}://{auth}{}",
uri.scheme_str().unwrap_or("http"),
uri.authority().map(|a| a.as_str()).unwrap_or_default()
)
})
let uri = system_uri(url)?;
// On macOS the resolver may run the PAC script (`dnsResolve`), so it stays off the async threads. A
// script still loading answers with the matcher's route.
let probe = uri.to_string();
#[cfg(target_os = "macos")]
let pac = tokio::task::spawn_blocking(move || pac(&probe))
.await
.map_err(|error| IdeError::unavailable(format!("proxy lookup failed: {error}")))?;
// Nothing to evaluate outside macOS: no hop to the blocking pool.
#[cfg(not(target_os = "macos"))]
let pac = pac(&probe);
match pac {
Some(ProxyRoute::Via(via)) if via.starts_with("http://") => Some(via),
Some(ProxyRoute::Direct) => None,
// No PAC applies, or it names a proxy this tunnel cannot speak to (SOCKS): the matcher's route.
_ => matcher().intercept(&uri).map(|intercept| {
let auth =
intercept.raw_auth().map(|(user, password)| format!("{user}:{password}@")).unwrap_or_default();
let uri = intercept.uri();
format!(
"{}://{auth}{}",
uri.scheme_str().unwrap_or("http"),
uri.authority().map(|a| a.as_str()).unwrap_or_default()
)
}),
}
}
};
let connecting = async {
@@ -157,6 +196,73 @@ mod tests {
assert!(error.message.contains("needs a login"), "{}", error.message);
}
use std::sync::{Arc, Mutex};
fn matcher_via(address: &str) -> impl FnOnce() -> Matcher {
let address = address.to_owned();
move || Matcher::builder().all(format!("http://{address}")).build()
}
/// The CONNECT line a proxy was asked for, or `None` when nothing connected within a moment.
async fn asked(task: tokio::task::JoinHandle<String>) -> Option<String> {
tokio::time::timeout(Duration::from_millis(300), task).await.ok().map(|head| head.unwrap())
}
#[tokio::test]
async fn the_pac_route_wins_over_the_matcher_and_ws_is_looked_up_as_http() {
let (pac_proxy, pac_asked) = proxy("HTTP/1.1 200 Connection established\r\n\r\n").await;
let (matcher_proxy, matcher_asked) = proxy("HTTP/1.1 200 Connection established\r\n\r\n").await;
let seen = Arc::new(Mutex::new(String::new()));
let recorded = Arc::clone(&seen);
let pac = move |probe: &str| {
*recorded.lock().unwrap() = probe.to_owned();
Some(ProxyRoute::Via(format!("http://{pac_proxy}")))
};
let url = reqwest::Url::parse("ws://pac-target.invalid:8080/s").unwrap();
connect_with(&url, ProxyRoute::System, pac, matcher_via(&matcher_proxy)).await.unwrap();
assert_eq!(*seen.lock().unwrap(), "http://pac-target.invalid:8080/");
assert!(asked(pac_asked).await.unwrap().starts_with("CONNECT pac-target.invalid:8080 HTTP/1.1\r\n"));
assert_eq!(asked(matcher_asked).await, None, "the matcher's proxy must not be used");
}
#[tokio::test]
async fn wss_is_looked_up_as_https() {
let (pac_proxy, _) = proxy("HTTP/1.1 200 Connection established\r\n\r\n").await;
let seen = Arc::new(Mutex::new(String::new()));
let recorded = Arc::clone(&seen);
let pac = move |probe: &str| {
*recorded.lock().unwrap() = probe.to_owned();
Some(ProxyRoute::Via(format!("http://{pac_proxy}")))
};
let url = reqwest::Url::parse("wss://pac-target.invalid/s").unwrap();
connect_with(&url, ProxyRoute::System, pac, || Matcher::builder().build()).await.unwrap();
assert_eq!(*seen.lock().unwrap(), "https://pac-target.invalid:443/");
}
#[tokio::test]
async fn a_resolved_direct_route_skips_the_matchers_proxy() {
let (matcher_proxy, matcher_asked) = proxy("HTTP/1.1 200 Connection established\r\n\r\n").await;
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let url = reqwest::Url::parse(&format!("ws://{}/s", listener.local_addr().unwrap())).unwrap();
connect_with(&url, ProxyRoute::System, |_| Some(ProxyRoute::Direct), matcher_via(&matcher_proxy))
.await
.unwrap();
tokio::time::timeout(Duration::from_millis(300), listener.accept())
.await
.expect("no direct connection")
.unwrap();
assert_eq!(asked(matcher_asked).await, None, "the matcher's proxy must not be used");
}
#[tokio::test]
async fn a_socks_pac_route_keeps_the_matchers_route() {
let (matcher_proxy, matcher_asked) = proxy("HTTP/1.1 200 Connection established\r\n\r\n").await;
let url = reqwest::Url::parse("ws://pac-target.invalid:8080/s").unwrap();
let pac = |_: &str| Some(ProxyRoute::Via("socks5h://127.0.0.1:1080".into()));
connect_with(&url, ProxyRoute::System, pac, matcher_via(&matcher_proxy)).await.unwrap();
assert!(asked(matcher_asked).await.unwrap().starts_with("CONNECT pac-target.invalid:8080 HTTP/1.1\r\n"));
}
#[test]
fn proxy_credentials_are_percent_decoded() {
assert_eq!(percent_decode("a%40b%3Ac"), "a@b:c");
+73
Переглянути файл
@@ -2811,6 +2811,79 @@ impl LspManager {
Ok(ts_file_moves::file_references(&result))
}
/// Runs vtsls' own `command` for `doc`. typescript-language-server, TypeScript 7 and the
/// Vue / Astro servers have none of these commands: they need vtsls.
async fn vtsls_command(
&self,
doc: DocId,
command: &str,
arguments: impl FnOnce(&DocSnap, &Target) -> Option<Value>,
cancel: Option<&CancellationToken>,
) -> IdeResult<(Target, Value)> {
let snap = self.snapshot(doc)?;
let t = self
.ready_targets(&snap.servers, |c| c.commands().iter().any(|c| c == command))
.await
.into_iter()
.find(|t| t.server.name == "vtsls")
.ok_or_else(|| IdeError::unavailable("This needs the vtsls TypeScript language server"))?;
let arguments =
arguments(&snap, &t).ok_or_else(|| IdeError::invalid(format!("invalid `{command}` arguments")))?;
let params = json!({ "command": command, "arguments": arguments });
let result = self.call(&t, "workspace/executeCommand", params, cancel, LONG_TIMEOUT).await?;
Ok((t, result))
}
/// Go to Source Definition: the JavaScript implementation of what `pos` refers to, not its
/// `.d.ts` declaration (vtsls' `typescript.goToSourceDefinition`).
pub async fn source_definition(&self, doc: DocId, pos: Pos, cancel: CancellationToken) -> IdeResult<Vec<Location>> {
let (t, result) = self
.vtsls_command(
doc,
"typescript.goToSourceDefinition",
|snap, t| Some(json!([snap.uri, snap.position(t, pos)])),
Some(&cancel),
)
.await?;
let locs: Vec<lsp::Location> = serde_json::from_value::<Option<_>>(result)
.map_err(|e| IdeError::internal(format!("typescript.goToSourceDefinition: {e}")))?
.unwrap_or_default();
let conv = self.conv(t.enc());
Ok(locs.iter().filter_map(|l| conv.location(l)).collect())
}
/// Opens the `tsconfig.json` / `jsconfig.json` of `doc`'s project, or the TS Server log:
/// vtsls answers with `window/showDocument` (or a message when there is none).
pub async fn open_typescript_file(&self, doc: DocId, what: TypeScriptFile) -> IdeResult<()> {
let (command, with_uri) = match what {
TypeScriptFile::ProjectConfig => {
let snap = self.snapshot(doc)?;
let js = snap.language.as_str().starts_with("javascript");
(if js { "javascript.goToProjectConfig" } else { "typescript.goToProjectConfig" }, true)
}
TypeScriptFile::ServerLog => ("typescript.openTsServerLog", false),
};
self.vtsls_command(doc, command, |snap, _| Some(if with_uri { json!([snap.uri]) } else { json!([]) }), None)
.await?;
Ok(())
}
/// The files tsserver suggests for vtsls' Move to File `command` (from a code action).
pub async fn move_to_file_targets(
&self,
doc: DocId,
command: Command,
cancel: CancellationToken,
) -> IdeResult<Vec<PathBuf>> {
let snap = self.snapshot(doc)?;
let request = ts_file_moves::move_to_file_suggestions_request(&snap.path, &command.arguments)
.ok_or_else(|| IdeError::invalid("invalid Move to File command"))?;
let (_, result) = self
.vtsls_command(doc, ts_file_moves::COMMAND, |_, _| request.get("arguments").cloned(), Some(&cancel))
.await?;
Ok(ts_file_moves::move_to_file_suggestions(&result))
}
/// Whether a server of `doc` (`server`, when given) provides the command `name`. Code actions
/// can carry commands other editors' extensions run themselves after the edit (vtsls'
/// `_typescript.didOrganizeImports`): no server provides those.
+46
Переглянути файл
@@ -87,10 +87,56 @@ pub(crate) fn file_references(result: &Value) -> Vec<ide_core::Location> {
.collect()
}
/// The `typescript.tsserverRequest` arguments asking where the selection of vtsls' Move to File
/// command (`_typescript.moveToFileRefactoring` with `[action, uri, range]`, run with the target
/// file appended) can go.
pub(crate) fn move_to_file_suggestions_request(file: &std::path::Path, arguments: &[Value]) -> Option<Value> {
let range: lsp_types::Range = serde_json::from_value(arguments.get(2)?.clone()).ok()?;
// tsserver: 1-based lines and UTF-16 offsets; vtsls speaks UTF-16.
Some(json!({
"command": COMMAND,
"arguments": ["getMoveToRefactoringFileSuggestions", {
"file": file,
"startLine": range.start.line + 1,
"startOffset": range.start.character + 1,
"endLine": range.end.line + 1,
"endOffset": range.end.character + 1,
}],
}))
}
/// The files tsserver suggests in its `getMoveToRefactoringFileSuggestions` answer.
pub(crate) fn move_to_file_suggestions(result: &Value) -> Vec<PathBuf> {
let body = result.get("body").unwrap_or(result);
serde_json::from_value(body.get("files").cloned().unwrap_or_default()).unwrap_or_default()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn asks_tsserver_where_the_move_to_file_selection_can_go() {
let action = json!({ "name": "Move to file", "kind": "refactor.move.file" });
let range = json!({ "start": { "line": 6, "character": 16 }, "end": { "line": 8, "character": 1 } });
let request = move_to_file_suggestions_request(
std::path::Path::new("/p/src/util.ts"),
&[action.clone(), json!("file:///p/src/util.ts"), range],
)
.unwrap();
assert_eq!(
request["arguments"],
json!(["getMoveToRefactoringFileSuggestions", {
"file": "/p/src/util.ts", "startLine": 7, "startOffset": 17, "endLine": 9, "endOffset": 2,
}])
);
assert!(move_to_file_suggestions_request(std::path::Path::new("/p/a.ts"), &[action]).is_none());
let answer =
json!({ "success": true, "body": { "newFileName": "/p/src/greet.ts", "files": ["/p/src/app.ts"] } });
assert_eq!(move_to_file_suggestions(&answer), vec![PathBuf::from("/p/src/app.ts")]);
assert!(move_to_file_suggestions(&json!({ "success": false })).is_empty());
}
#[test]
fn converts_tsserver_file_references() {
let result = json!({ "success": true, "body": { "symbolName": "\"./Hello.vue\"", "refs": [
+8
Переглянути файл
@@ -109,6 +109,14 @@ pub struct Signature {
pub parameters: Vec<(u32, u32)>,
}
/// A file vtsls opens for a document: its project's configuration or the TS Server log.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum TypeScriptFile {
ProjectConfig,
ServerLog,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum GotoKind {
+129
Переглянути файл
@@ -969,6 +969,135 @@ async fn bundler_path_aliases_resolve_below_tsconfig_paths() {
tokio::time::timeout(Duration::from_secs(10), mgr.shutdown_all()).await.unwrap();
}
/// vtsls' own commands (#6922): Go to Source Definition opens a library's JavaScript instead
/// of its `.d.ts`, Go to Project Configuration and Open TS Server Log answer with
/// `window/showDocument`, JSDoc `{@link}` in hovers is a `file://…#L1,1` link, and Move to File
/// suggests the project's files and moves a function with its imports in one applied edit. Set
/// `OPENIDEA_TEST_NPM_TOOLS` to a dir with `npm i @vtsls/[email protected] typescript@6`.
#[tokio::test(flavor = "multi_thread")]
#[ignore = "requires @vtsls/language-server and typescript@6 (OPENIDEA_TEST_NPM_TOOLS)"]
async fn vtsls_commands_open_sources_configs_logs_and_move_to_file() {
let tools = std::path::PathBuf::from(std::env::var("OPENIDEA_TEST_NPM_TOOLS").expect("OPENIDEA_TEST_NPM_TOOLS"));
let dir = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(dir.path()).unwrap();
for dir in ["src", "node_modules/greeting"] {
std::fs::create_dir_all(root.join(dir)).unwrap();
}
let files = [
("package.json", "{\"name\":\"app\",\"private\":true}"),
("tsconfig.json", "{\"files\":[],\"references\":[{\"path\":\"./src/tsconfig.app.json\"}]}"),
(
"src/tsconfig.app.json",
"{\"compilerOptions\":{\"strict\":true,\"composite\":true,\"module\":\"ESNext\",\"moduleResolution\":\"Bundler\"},\"include\":[\"./**/*.ts\"]}",
),
(
"node_modules/greeting/package.json",
"{\"name\":\"greeting\",\"main\":\"index.js\",\"types\":\"index.d.ts\"}",
),
("node_modules/greeting/index.d.ts", "export declare function shout(s: string): string;\n"),
("node_modules/greeting/index.js", "export function shout(s) {\n return s.toUpperCase();\n}\n"),
(
"src/main.ts",
"import { shout } from \"greeting\";\nimport { greet, Greeter } from \"./util\";\n\n/** Uses {@link Greeter} to say hello. */\nexport function hello(name: string) {\n return shout(greet(name));\n}\n\nexport const g = new Greeter();\n",
),
(
"src/util.ts",
"export class Greeter {\n greet(name: string) {\n return `Hello, ${name}`;\n }\n}\n\nexport function greet(name: string) {\n return new Greeter().greet(name);\n}\n",
),
("src/strings.ts", "export const upper = (s: string) => s.toUpperCase();\n"),
("src/app.ts", "import { greet } from \"./util\";\n\nconsole.log(greet(\"app\"));\n"),
];
for (path, text) in files {
std::fs::write(root.join(path), text).unwrap();
}
// The IDE's settings hook: Move to File on, a TypeScript 6 lib, the log on.
let init = serde_json::json!({
"vtsls": { "enableMoveToFileCodeAction": true, "autoUseWorkspaceTsdk": true },
"typescript": {
"tsdk": tools.join("node_modules/typescript/lib").to_string_lossy(),
"tsserver": { "log": "verbose" },
},
});
let ts = lang("typescript", "ts", npm_server(&tools, "vtsls", "vtsls", Some(init)));
let (mgr, events) = manager(&root, LanguageRegistry::from_configs(vec![ts]));
let applied: Arc<Mutex<Vec<ide_core::WorkspaceEdit>>> = Arc::default();
mgr.set_apply_edit_hook(Box::new({
let applied = applied.clone();
move |edit| {
applied.lock().push(edit);
true
}
}));
let open = |path: &str| {
let doc = DocId::next();
let file = root.join(path);
mgr.did_open(doc, &file, &LanguageId::new("typescript"), 1, &std::fs::read_to_string(&file).unwrap());
doc
};
let (main, util) = (open("src/main.ts"), open("src/util.ts"));
// `shout`: Go to Declaration is the `.d.ts`, Go to Source Definition the `.js`.
let at = Pos::new(0, 10);
// The syntax server answers with the import itself until the project is loaded.
let dts = |d: &ide_core::Location| d.path.to_string_lossy().ends_with("greeting/index.d.ts");
let declaration = retry("declaration", Duration::from_secs(90), || {
let mgr = mgr.clone();
async move { mgr.goto(main, at, GotoKind::Definition).await.ok().filter(|d| d.iter().any(dts)) }
})
.await;
assert!(declaration.iter().all(dts), "{declaration:?}");
let source = mgr.source_definition(main, at, Default::default()).await.unwrap();
assert_eq!(source.len(), 1, "{source:?}");
assert_eq!(*source[0].path, *root.join("node_modules/greeting/index.js"));
assert_eq!(source[0].range.start, Pos::new(0, 16));
let shown = |events: &Events, suffix: &str| {
events
.lock()
.iter()
.any(|e| matches!(e, IdeEvent::LspShowDocument { path: Some(path), .. } if path.to_string_lossy().ends_with(suffix)))
};
mgr.open_typescript_file(main, ide_lsp::types::TypeScriptFile::ProjectConfig).await.unwrap();
retry("tsconfig.app.json shown", Duration::from_secs(10), || {
let found = shown(&events, "src/tsconfig.app.json").then_some(());
async move { found }
})
.await;
mgr.open_typescript_file(main, ide_lsp::types::TypeScriptFile::ServerLog).await.unwrap();
retry("tsserver.log shown", Duration::from_secs(10), || {
let found = shown(&events, "tsserver.log").then_some(());
async move { found }
})
.await;
let hover = mgr.hover(main, Pos::new(4, 17), Default::default()).await.unwrap();
let hover = format!("{hover:?}");
assert!(hover.contains("src/util.ts#L1%2C1"), "{hover}");
// Move to File on `greet`: tsserver suggests the other files, the move updates the importers.
let caret = Pos::new(6, 16);
let actions = mgr.code_actions(util, Range::new(caret, caret), vec!["refactor.move".into()]).await.unwrap();
let command = actions
.iter()
.find_map(|a| a.command.clone().filter(|c| c.command == "_typescript.moveToFileRefactoring"))
.unwrap_or_else(|| panic!("no Move to File: {actions:?}"));
let targets = mgr.move_to_file_targets(util, command.clone(), Default::default()).await.unwrap();
let strings = root.join("src/strings.ts");
assert!(targets.contains(&strings) && targets.contains(&root.join("src/app.ts")), "{targets:?}");
let mut moving = command;
moving.arguments.push(serde_json::json!(strings));
mgr.execute_command(util, moving).await.unwrap();
let edits = applied.lock().clone();
assert_eq!(edits.len(), 1, "{edits:?}");
let edit = format!("{:?}", edits[0]);
for file in ["src/util.ts", "src/strings.ts", "src/app.ts", "src/main.ts"] {
assert!(edit.contains(&*root.join(file).to_string_lossy()), "{file}: {edit}");
}
assert!(edit.contains("export function greet(name: string)"), "{edit}");
assert!(edit.contains("import { greet } from \\\"./strings\\\""), "{edit}");
tokio::time::timeout(Duration::from_secs(10), mgr.shutdown_all()).await.unwrap();
}
/// CSS Modules Kit (`@css-modules-kit/ts-plugin`) on vtsls, which serves the `.module.css`
/// files too (`languages: ["css"]`): definition and completion from TSX, references and rename
/// from the stylesheet (#6071), with the settings hook's own plugin configuration. Exactly the
+55 -4
Переглянути файл
@@ -1,6 +1,6 @@
//! Xcode schemes: one configuration per scheme that builds its app and runs it on the iOS
//! Simulator or the Mac (see [`crate::xcode::prepare`]). A workspace next to the projects builds them all,
//! so its schemes and theirs are built through it.
//! so its schemes and theirs are built through it, as is the workspace of a CocoaPods project.
use super::{ConfigExt, config};
use crate::RunConfig;
@@ -8,10 +8,12 @@ use crate::xcode::{XcodeScheme, schemes};
use std::path::Path;
/// A folder holding an Xcode project or workspace, other than the `ios/` / `macos/` host app
/// of a Flutter or React Native project, which that project's own tooling runs.
/// of a Flutter or React Native project, which that project's own tooling runs, and a CocoaPods
/// `Pods/` folder.
pub(super) fn is_project(dir: &Path) -> bool {
let hosted = dir.parent().is_some_and(|p| p.join("pubspec.yaml").is_file() || p.join("package.json").is_file());
!hosted
&& !crate::xcode::is_pods_dir(dir)
&& std::fs::read_dir(dir).is_ok_and(|entries| {
entries.flatten().any(|e| e.path().extension().is_some_and(|x| x == "xcodeproj" || x == "xcworkspace"))
})
@@ -19,9 +21,13 @@ pub(super) fn is_project(dir: &Path) -> bool {
pub(super) fn detect(dir: &Path, out: &mut Vec<RunConfig>) {
let found = schemes(dir);
let workspace = found.iter().map(|s| &s.container).find(|c| c.extension().is_some_and(|x| x == "xcworkspace"));
let workspace = found
.iter()
.map(|s| s.container.clone())
.find(|c| c.extension().is_some_and(|x| x == "xcworkspace"))
.or_else(|| crate::xcode::pods_workspace(dir));
for scheme in &found {
let container = workspace.unwrap_or(&scheme.container);
let container = workspace.as_ref().unwrap_or(&scheme.container);
let container = container.strip_prefix(dir).unwrap_or(container).to_string_lossy().into_owned();
out.push(scheme_config(scheme, &container));
}
@@ -77,4 +83,49 @@ mod tests {
assert_eq!(app.env["API_HOST"], "localhost:8080");
assert!(!app.extras.params.contains_key(crate::xcode::SIMULATOR_PARAM));
}
#[test]
fn a_cocoapods_project_builds_and_tests_through_its_workspace() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
let scheme = std::fs::read_to_string(
Path::new(env!("CARGO_MANIFEST_DIR"))
.join("tests/fixtures/xcode/App.xcodeproj/xcshareddata/xcschemes/App.xcscheme"),
)
.unwrap();
for dir in ["App.xcodeproj", "Pods/Pods.xcodeproj"] {
let schemes = root.join(dir).join("xcshareddata/xcschemes");
std::fs::create_dir_all(&schemes).unwrap();
std::fs::write(schemes.join("App.xcscheme"), &scheme).unwrap();
}
// `pod install`'s workspace has no schemes of its own.
std::fs::create_dir(root.join("App.xcworkspace")).unwrap();
let args = |out: &[RunConfig]| out.iter().map(|c| c.args.join(" ")).collect::<Vec<_>>();
let mut out = Vec::new();
detect(root, &mut out);
assert_eq!(args(&out), ["-project App.xcodeproj -scheme App -configuration Staging"]);
// Without a Podfile, a `Pods/` folder is just another project.
assert!(is_project(&root.join("Pods")));
std::fs::write(root.join("Podfile"), "").unwrap();
assert!(is_project(root) && !is_project(&root.join("Pods")));
let mut out = Vec::new();
detect(root, &mut out);
assert_eq!(args(&out), ["-workspace App.xcworkspace -scheme App -configuration Staging"]);
let mut tests = Vec::new();
super::super::xcode_test::detect(root, &mut tests);
assert_eq!(args(&tests), ["test -workspace App.xcworkspace -scheme App"]);
// A leftover workspace that sorts first: the one named after the project still wins.
std::fs::create_dir(root.join("Aardvark.xcworkspace")).unwrap();
let mut out = Vec::new();
detect(root, &mut out);
assert_eq!(args(&out), ["-workspace App.xcworkspace -scheme App -configuration Staging"]);
assert_eq!(crate::xcode::pods_workspace(root), Some(root.join("App.xcworkspace")));
// Without a workspace named after a project, the first by name.
std::fs::remove_dir(root.join("App.xcworkspace")).unwrap();
std::fs::create_dir(root.join("Old.xcworkspace")).unwrap();
assert_eq!(crate::xcode::pods_workspace(root), Some(root.join("Aardvark.xcworkspace")));
}
}
+7 -2
Переглянути файл
@@ -1,4 +1,5 @@
//! Xcode test configurations: `xcodebuild test` for each scheme whose `TestAction` has tests.
//! Xcode test configurations: `xcodebuild test` for each scheme whose `TestAction` has tests,
//! through the CocoaPods workspace when the project has one.
//! The simulator destination and the result bundle are added at launch (`xcode::prepare_test`).
use super::{ConfigExt, config};
@@ -6,11 +7,15 @@ use crate::RunConfig;
use std::path::Path;
pub(super) fn detect(root: &Path, out: &mut Vec<RunConfig>) {
// With a Podfile every scheme is built through the Pods workspace, assuming one app project
// per folder: the workspace `pod install` writes links that project's targets.
let pods = crate::xcode::pods_workspace(root);
for scheme in crate::xcode::schemes(root) {
if !scheme.has_tests {
continue;
}
let Some(container) = scheme.container.file_name().and_then(|n| n.to_str()) else { continue };
let path = pods.as_ref().unwrap_or(&scheme.container);
let Some(container) = path.file_name().and_then(|n| n.to_str()) else { continue };
let flag = if container.ends_with(".xcworkspace") { "-workspace" } else { "-project" };
out.push(
config(
+11 -6
Переглянути файл
@@ -67,8 +67,12 @@ pub fn parse_list(json: &str) -> IdeResult<Vec<IosSimulator>> {
Ok(devices.into_iter().map(|(_, d)| d).collect())
}
fn run(program: &str, args: &[&str]) -> IdeResult<String> {
/// `dir`, inside a project, picks the project's Xcode (`DEVELOPER_DIR`).
fn run_in(dir: Option<&Path>, program: &str, args: &[&str]) -> IdeResult<String> {
let mut cmd = Command::new(program);
if let Some(dir) = dir {
cmd.current_dir(dir);
}
prepare(&mut cmd).args(args);
let out = cmd.output().map_err(|e| IdeError::unavailable(format!("could not run {program}: {e}")))?;
if out.status.success() {
@@ -79,22 +83,23 @@ fn run(program: &str, args: &[&str]) -> IdeResult<String> {
}
/// The available iOS simulators, sorted as [`parse_list`] does.
pub fn list() -> IdeResult<Vec<IosSimulator>> {
parse_list(&run("xcrun", &["simctl", "list", "devices", "available", "--json"])?)
/// The available iOS simulators of the Xcode the project at `root` uses.
pub fn list(root: &Path) -> IdeResult<Vec<IosSimulator>> {
parse_list(&run_in(Some(root), "xcrun", &["simctl", "list", "devices", "available", "--json"])?)
}
/// Boots a simulator; returns once `simctl` has it booted.
pub fn boot(udid: &str) -> IdeResult<()> {
run("xcrun", &["simctl", "boot", udid]).map(drop)
run_in(None, "xcrun", &["simctl", "boot", udid]).map(drop)
}
pub fn shutdown(udid: &str) -> IdeResult<()> {
run("xcrun", &["simctl", "shutdown", udid]).map(drop)
run_in(None, "xcrun", &["simctl", "shutdown", udid]).map(drop)
}
/// Brings Simulator.app to the front, which shows the booted simulators.
pub fn open_app() -> IdeResult<()> {
run("open", &["-a", "Simulator"]).map(drop)
run_in(None, "open", &["-a", "Simulator"]).map(drop)
}
#[cfg(test)]
+43 -8
Переглянути файл
@@ -46,6 +46,29 @@ pub fn schemes(root: &Path) -> Vec<XcodeScheme> {
containers.iter().flat_map(|c| container_schemes(c)).collect()
}
/// The `.xcworkspace` `pod install` wrote next to the app's project, when `root` has a `Podfile`:
/// the one named after an `.xcodeproj` in `root`, else the first by name (a leftover workspace
/// may sit beside it). The project alone doesn't link the pods, so its schemes are built through
/// this workspace, which usually has no schemes of its own. The frontend picks the same one
/// (`podsWorkspace` in `src/features/run/cocoapodsActions.ts`).
pub fn pods_workspace(root: &Path) -> Option<PathBuf> {
if !root.join("Podfile").is_file() {
return None;
}
let mut dirs: Vec<PathBuf> = fs::read_dir(root).ok()?.flatten().map(|e| e.path()).filter(|p| p.is_dir()).collect();
dirs.sort();
let has_ext = |p: &Path, ext: &str| p.extension().is_some_and(|e| e == ext);
let projects: Vec<_> = dirs.iter().filter(|p| has_ext(p, "xcodeproj")).filter_map(|p| p.file_stem()).collect();
let workspaces: Vec<&PathBuf> = dirs.iter().filter(|p| has_ext(p, "xcworkspace")).collect();
let named = workspaces.iter().find(|w| w.file_stem().is_some_and(|s| projects.contains(&s)));
named.or(workspaces.first()).map(|w| (*w).clone())
}
/// The `Pods/` folder of a CocoaPods project: its `Pods.xcodeproj` is generated, not the app.
pub fn is_pods_dir(dir: &Path) -> bool {
dir.file_name().is_some_and(|n| n == "Pods") && dir.parent().is_some_and(|p| p.join("Podfile").is_file())
}
fn container_schemes(container: &Path) -> Vec<XcodeScheme> {
let mut out: Vec<XcodeScheme> = Vec::new();
let mut add = |dir: PathBuf, shared: bool| {
@@ -155,16 +178,21 @@ fn resolve(reference: &str, container: &Path) -> PathBuf {
/// Completes an `xcodebuild test` launch: a simulator destination unless the configuration names
/// one, and a fresh `-resultBundlePath` under `bundles` (xcodebuild refuses an existing one). The
/// bundles of this configuration's earlier runs are removed.
pub fn prepare_test(config: &mut crate::RunConfig, bundles: &Path) -> std::io::Result<()> {
/// bundles of this configuration's earlier runs are removed. Run with Coverage names the bundle
/// itself in [`RESULT_BUNDLE_PARAM`].
pub fn prepare_test(config: &mut crate::RunConfig, dir: &Path, bundles: &Path) -> std::io::Result<()> {
if !config.args.iter().any(|a| a == "-destination")
&& let Some(udid) = default_simulator()
&& let Some(udid) = default_simulator(dir)
{
config.args.extend(["-destination".to_owned(), format!("id={udid}")]);
}
if let Some(at) = config.args.iter().position(|a| a == "-resultBundlePath") {
config.args.drain(at..(at + 2).min(config.args.len()));
}
if let Some(bundle) = config.extras.params.get(RESULT_BUNDLE_PARAM).cloned() {
config.args.extend(["-resultBundlePath".to_owned(), bundle]);
return Ok(());
}
let prefix: String = config.id.chars().map(|c| if c.is_ascii_alphanumeric() { c } else { '_' }).collect();
fs::create_dir_all(bundles)?;
for entry in fs::read_dir(bundles)?.flatten() {
@@ -178,10 +206,11 @@ pub fn prepare_test(config: &mut crate::RunConfig, bundles: &Path) -> std::io::R
Ok(())
}
/// The booted iOS simulator, otherwise the first iPhone of the newest iOS runtime.
pub fn default_simulator() -> Option<String> {
/// The booted iOS simulator, otherwise the first iPhone of the newest iOS runtime. `dir` (inside
/// the project) picks the project's Xcode.
pub fn default_simulator(dir: &Path) -> Option<String> {
let mut cmd = std::process::Command::new("xcrun");
cmd.args(["simctl", "list", "devices", "available", "-j"]);
cmd.args(["simctl", "list", "devices", "available", "-j"]).current_dir(dir);
let out = ide_core::process::prepare(&mut cmd).output().ok()?;
pick_simulator(&String::from_utf8_lossy(&out.stdout))
}
@@ -211,6 +240,8 @@ fn pick_simulator(json: &str) -> Option<String> {
/// [`default_simulator`]: the one place a device selector can feed its choice into.
/// [`MAC`] runs an app that supports both on the Mac instead.
pub const SIMULATOR_PARAM: &str = "simulator";
/// The result bundle an `xcodebuild test` launch writes, when the caller reads it afterwards.
pub const RESULT_BUNDLE_PARAM: &str = "resultBundle";
/// Set (to anything but empty) by Debug: the app is launched suspended
/// (`simctl launch --wait-for-debugger`) until the debugger attaches to the pid simctl prints.
@@ -380,7 +411,7 @@ pub fn destination(dir: &Path, params: &BTreeMap<String, String>, derived_data:
}
let udid = match Some(simulator.trim()).filter(|s| !s.is_empty() && *s != MAC) {
Some(udid) => udid.to_owned(),
None => default_simulator().ok_or_else(|| IdeError::unavailable("No iOS simulator is available"))?,
None => default_simulator(dir).ok_or_else(|| IdeError::unavailable("No iOS simulator is available"))?,
};
Ok(format!("id={udid}"))
}
@@ -531,12 +562,16 @@ mod tests {
allow_parallel: false,
extras: Default::default(),
};
prepare_test(&mut config, dir.path()).unwrap();
prepare_test(&mut config, dir.path(), dir.path()).unwrap();
assert_eq!(config.args[..3], ["test", "-destination", "id=X"]);
assert_eq!(config.args[3], "-resultBundlePath");
assert!(config.args[4].contains("xcode_test_A-") && config.args[4].ends_with(".xcresult"));
assert_eq!(config.args.len(), 5);
assert!(!old.exists() && other.exists());
config.extras.params.insert(RESULT_BUNDLE_PARAM.into(), "/cov/r.xcresult".into());
prepare_test(&mut config, dir.path(), dir.path()).unwrap();
assert_eq!(config.args[3..], ["-resultBundlePath", "/cov/r.xcresult"]);
}
#[test]
+25 -1
Переглянути файл
@@ -6,7 +6,7 @@ use crate::exec::{path_with, search_path, which};
use crate::npm::{has_ts_api, native_typescript, own_typescript};
use crate::{angular, astro, godot, pinned, vue};
use crate::{bin_dir, exe, venv_of};
use ide_core::settings::{InspectionLevel, InspectionSettings, LanguageServerSettings, Settings};
use ide_core::settings::{InspectionLevel, InspectionSettings, LanguageServerSettings, Settings, TsServerLog};
use ide_core::version_managers::Tool;
use ide_core::{IdeError, IdeResult};
use ide_language::{LanguageConfig, LanguageServerConfig};
@@ -1508,6 +1508,14 @@ pub fn configure_server(cfg: &mut LanguageServerConfig, root: &Path, server_root
if name == "vtsls" && memory > 0 {
merge_init_options(cfg, json!({ "typescript": { "tsserver": { "maxTsServerMemory": memory } } }));
}
if name == "vtsls" {
// Move to File asks the IDE for the target file (vtsls hides the action by default).
merge_init_options(cfg, json!({ "vtsls": { "enableMoveToFileCodeAction": true } }));
let log = s.languages.typescript.tsserver_log;
if log != TsServerLog::Off {
merge_init_options(cfg, json!({ "typescript": { "tsserver": { "log": log } } }));
}
}
if name == "vtsls"
&& cfg.tsserver_project
&& !server_root.ancestors().any(|d| d.join("tsconfig.json").is_file() || d.join("jsconfig.json").is_file())
@@ -2778,6 +2786,22 @@ mod maven_linkage_tests {
assert_eq!(options.pointer("/typescript/tsserver/maxTsServerMemory"), Some(&json!(6144)));
}
#[test]
fn vtsls_offers_move_to_file_and_logs_only_when_asked() {
let tmp = tempfile::tempdir().unwrap();
let mut s = Settings::default();
let options = |s: &Settings| {
let mut cfg = custom_server("vtsls", &LanguageServerSettings::default());
configure_server(&mut cfg, tmp.path(), tmp.path(), s);
serde_json::to_value(cfg.initialization_options).unwrap()
};
let off = options(&s);
assert_eq!(off.pointer("/vtsls/enableMoveToFileCodeAction"), Some(&json!(true)));
assert!(off.pointer("/typescript/tsserver/log").is_none());
s.languages.typescript.tsserver_log = TsServerLog::Verbose;
assert_eq!(options(&s).pointer("/typescript/tsserver/log"), Some(&json!("verbose")));
}
#[test]
fn vtsls_probes_the_tsconfig_plugins_but_not_its_global_ones() {
let tmp = tempfile::tempdir().unwrap();
+53 -1
Переглянути файл
@@ -33,6 +33,7 @@ pub fn detect(kind: SdkKind, root: Option<&Path>) -> Vec<Sdk> {
SdkKind::Zig => zig(),
SdkKind::Dotnet => dotnet(),
SdkKind::Flutter => crate::flutter::detect(),
SdkKind::Xcode => xcode(),
};
if let Some(root) = root {
pinned_first(&mut out, kind, root);
@@ -54,7 +55,8 @@ fn tool_of(kind: SdkKind) -> Option<Tool> {
| SdkKind::Rust
| SdkKind::TypeScript
| SdkKind::Dotnet
| SdkKind::Flutter => None,
| SdkKind::Flutter
| SdkKind::Xcode => None,
}
}
@@ -1219,6 +1221,56 @@ fn zig() -> Vec<Sdk> {
})
}
/// Xcodes in `/Applications` and `~/Applications` (any name: `Xcode-beta.app`, `Xcode_16.4.app`),
/// for `languages.swift.xcode`; `path` is the `.app`.
fn xcode() -> Vec<Sdk> {
if !cfg!(target_os = "macos") {
return Vec::new();
}
let dirs = [Some(PathBuf::from("/Applications")), home_dir().map(|h| h.join("Applications"))];
let mut apps: Vec<PathBuf> = dirs
.into_iter()
.flatten()
.flat_map(|d| subdirs(&d))
.filter(|app| app.extension() == Some(OsStr::new("app")))
.filter(|app| app.join("Contents/Developer/usr/bin/xcodebuild").is_file())
.collect();
apps.sort();
apps.into_iter()
.map(|app| {
let version = std::fs::read_to_string(app.join("Contents/version.plist"))
.ok()
.and_then(|plist| plist_string(&plist, "CFBundleShortVersionString"));
let stem = app.file_stem().unwrap_or_default().to_string_lossy().into_owned();
Sdk {
name: match &version {
Some(v) => format!("{stem} {v}"),
None => stem,
},
path: app.clone().into(),
version,
source: "system".to_owned(),
home: Some(app.join("Contents/Developer").into()),
extra: None,
}
})
.collect()
}
/// The `<string>` after `<key>key</key>` of an XML property list.
fn plist_string(plist: &str, key: &str) -> Option<String> {
let rest = &plist[plist.find(&format!("<key>{key}</key>"))?..];
let value = &rest[rest.find("<string>")? + "<string>".len()..];
Some(value[..value.find("</string>")?].trim().to_owned()).filter(|v| !v.is_empty())
}
#[test]
fn reads_xcodes_version_plist() {
let plist = "<dict>\n\t<key>BuildVersion</key>\n\t<string>7</string>\n\t<key>CFBundleShortVersionString</key>\n\t<string>26.1</string>\n</dict>";
assert_eq!(plist_string(plist, "CFBundleShortVersionString").as_deref(), Some("26.1"));
assert_eq!(plist_string(plist, "CFBundleVersion"), None);
}
/// The SDKs `dotnet --list-sdks` reports, newest first: only the `dotnet` that runs
/// `dotnet new` can use them.
fn dotnet() -> Vec<Sdk> {
+2
Переглянути файл
@@ -66,6 +66,8 @@ pub enum SdkKind {
Dotnet,
/// Flutter SDK roots.
Flutter,
/// `Xcode.app` bundles.
Xcode,
}
/// One installed interpreter / toolchain.
+57 -15
Переглянути файл
@@ -464,11 +464,16 @@ fn renamed_from(
Ok(None)
}
/// The log index, locked only around reads and writes: Git runs without it, so commit
/// details and one-commit queries need not wait for a long history walk.
fn lock(index: &std::sync::Mutex<crate::log_index::LogIndex>) -> std::sync::MutexGuard<'_, crate::log_index::LogIndex> {
index.lock().unwrap_or_else(|p| p.into_inner())
}
pub(crate) fn log(r: &Repo, q: &LogQuery, cancel: &CancellationToken) -> IdeResult<Vec<Commit>> {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
let mut index = r.log_index.lock().unwrap_or_else(|p| p.into_inner());
let result = if q.summary_only {
let mut all = q.clone();
all.skip = 0;
@@ -483,14 +488,19 @@ pub(crate) fn log(r: &Repo, q: &LogQuery, cancel: &CancellationToken) -> IdeResu
repo.shallow_commits().map_err(gx)?.map(|ids| ids.iter().copied().collect::<Vec<_>>()).unwrap_or_default();
let shallow: HashSet<ObjectId> = shallow_vec.iter().copied().collect();
let key = format!("{}:{generation}:{shallow_vec:?}", serde_json::to_string(&all).map_err(gx)?);
let cached = index.views.get(&key).cloned();
let cached = lock(&r.log_index).views.get(&key).cloned();
let view = if let Some(cached) = cached {
cached
} else {
// Immutable metadata is reused across roots, filters, merges and ref changes.
all.request = q.request;
let rows =
std::sync::Arc::new(crate::log_index::IndexedView::new(log_indexed_rows(r, &all, cancel, &mut index)?));
let rows = std::sync::Arc::new(crate::log_index::IndexedView::new(log_indexed_rows(
r,
&all,
cancel,
&r.log_index,
)?));
let mut index = lock(&r.log_index);
if index.views.len() >= 4 {
index.views.clear();
}
@@ -512,6 +522,7 @@ pub(crate) fn log(r: &Repo, q: &LogQuery, cancel: &CancellationToken) -> IdeResu
let retain = q.retain_until.as_ref().and_then(|id| find_pos(id)).map(|i| i + 1).unwrap_or(0);
let limit = if q.limit == 0 { usize::MAX } else { (q.limit as usize).max(retain.saturating_sub(start)) };
let total = view.rows.len() as u32;
let mut index = lock(&r.log_index);
let db = index.db().cloned();
let txn = db.as_ref().and_then(|db| db.begin_read().ok());
let table = txn.as_ref().and_then(|t| t.open_table(crate::log_index::COMMITS).ok());
@@ -538,9 +549,9 @@ pub(crate) fn log(r: &Repo, q: &LogQuery, cancel: &CancellationToken) -> IdeResu
}
Ok(result)
} else {
log_indexed(r, q, cancel, &mut index)
log_indexed(r, q, cancel, &r.log_index)
};
index.flush();
lock(&r.log_index).flush();
result
}
@@ -640,7 +651,7 @@ fn log_indexed(
r: &Repo,
q: &LogQuery,
cancel: &CancellationToken,
index: &mut crate::log_index::LogIndex,
shared: &std::sync::Mutex<crate::log_index::LogIndex>,
) -> IdeResult<Vec<Commit>> {
let repo = r.gix()?;
let shallow: HashSet<ObjectId> =
@@ -676,6 +687,8 @@ fn log_indexed(
&& q.since_ms.is_none()
&& q.until_ms.is_none()
{
let mut guard = lock(shared);
let index = &mut *guard;
update_head_reachable(&repo, index, cancel)?;
let id = tips[0];
let record = index.get(&repo, id)?;
@@ -706,7 +719,9 @@ fn log_indexed(
commit.message_truncated = false;
return Ok(vec![commit]);
}
let rows = log_indexed_rows(r, q, cancel, index)?;
let rows = log_indexed_rows(r, q, cancel, shared)?;
let mut guard = lock(shared);
let index = &mut *guard;
let db = index.db().cloned();
let txn = db.as_ref().and_then(|db| db.begin_read().ok());
let table = txn.as_ref().and_then(|t| t.open_table(crate::log_index::COMMITS).ok());
@@ -724,7 +739,7 @@ fn log_indexed_rows(
r: &Repo,
q: &LogQuery,
cancel: &CancellationToken,
index: &mut crate::log_index::LogIndex,
shared: &std::sync::Mutex<crate::log_index::LogIndex>,
) -> IdeResult<Vec<crate::log_index::IndexedRow>> {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
@@ -775,7 +790,7 @@ fn log_indexed_rows(
}
}
}
Some(sort_subset(&repo, ids, q.order, q.first_parent, &shallow, cancel, &index.nodes)?)
Some(sort_shared(&repo, ids, q, &shallow, cancel, shared)?)
} else {
None
};
@@ -802,14 +817,17 @@ fn log_indexed_rows(
};
let authors: Vec<_> =
q.author.iter().chain(&q.authors).map(|a| a.trim().to_lowercase()).filter(|a| !a.is_empty()).collect();
update_head_reachable(&repo, index, cancel)?;
let mut range_ids_set = range_ids.as_ref().map(|ids| ids.iter().copied().collect::<HashSet<_>>());
type Walk<'a> = Box<dyn Iterator<Item = IdeResult<ObjectId>> + 'a>;
let walk: Walk<'_> = if let Some(ids) = range_ids {
Box::new(ids.into_iter().map(Ok))
} else if q.summary_only {
let ids = index.graph(&repo, &tips, &shallow, q.first_parent, cancel)?;
Box::new(sort_subset(&repo, ids, q.order, q.first_parent, &shallow, cancel, &index.nodes)?.into_iter().map(Ok))
// One guard for both: a concurrent query with another shallow set resets `nodes`.
let mut guard = lock(shared);
let ids = guard.graph(&repo, &tips, &shallow, q.first_parent, cancel)?;
let sorted = sort_subset(&repo, ids, q.order, q.first_parent, &shallow, cancel, &guard.nodes)?;
drop(guard);
Box::new(sorted.into_iter().map(Ok))
} else if repo.is_shallow().unwrap_or(false) || q.request.is_some() {
// The process can be interrupted even during indegree preparation. Git also
// respects shallow boundaries while retaining a topological order.
@@ -866,7 +884,7 @@ fn log_indexed_rows(
LogOrder::Topo | LogOrder::Standard => topo::Sorting::TopoOrder,
LogOrder::Date => topo::Sorting::DateOrder,
};
let topo = topo::Builder::from_iters(&repo.objects, tips, None::<Vec<ObjectId>>)
let topo = topo::Builder::from_iters(&repo.objects, tips.clone(), None::<Vec<ObjectId>>)
.sorting(sorting)
.parents(if q.first_parent { Parents::First } else { Parents::All })
.with_commit_graph(graph)
@@ -876,11 +894,20 @@ fn log_indexed_rows(
};
let walk: Walk<'_> = if q.order == LogOrder::Standard {
let ids = walk.collect::<IdeResult<Vec<_>>>()?;
Box::new(sort_subset(&repo, ids, q.order, q.first_parent, &shallow, cancel, &index.nodes)?.into_iter().map(Ok))
Box::new(sort_shared(&repo, ids, q, &shallow, cancel, shared)?.into_iter().map(Ok))
} else {
walk
};
let text = q.text.as_deref().map(|t| TextFilter::new(r, &scopes, q, t, cancel)).transpose()?.flatten();
let mut guard = lock(shared);
let index = &mut *guard;
// Under the guard that builds the rows: a query run meanwhile (after a branch switch)
// may have moved the shared set to another HEAD.
update_head_reachable(&repo, index, cancel)?;
// A query started before a shallow change may have reset `nodes` to its older set.
if index.shallow != shallow {
index.ensure_nodes(&repo, &tips, &shallow, cancel)?;
}
let db = index.db().cloned();
let txn = db.as_ref().and_then(|db| db.begin_read().ok());
let table = txn.as_ref().and_then(|t| t.open_table(crate::log_index::COMMITS).ok());
@@ -952,6 +979,21 @@ fn log_indexed_rows(
Ok(out)
}
/// Sorts with the shared nodes only when they were built for this query's shallow set.
fn sort_shared(
repo: &gix::Repository,
ids: Vec<ObjectId>,
q: &LogQuery,
shallow: &HashSet<ObjectId>,
cancel: &CancellationToken,
shared: &std::sync::Mutex<crate::log_index::LogIndex>,
) -> IdeResult<Vec<ObjectId>> {
let guard = lock(shared);
let empty = HashMap::new();
let nodes = if &guard.shallow == shallow { &guard.nodes } else { &empty };
sort_subset(repo, ids, q.order, q.first_parent, shallow, cancel, nodes)
}
/// A ready-node stack gives incoming merge parents priority, while child counts
/// prevent an ancestor shared with another branch from moving ahead of its children.
fn sort_subset(
+116 -5
Переглянути файл
@@ -20,7 +20,12 @@ pub(crate) fn gx(e: impl std::fmt::Display) -> IdeError {
}
pub(crate) struct Cache {
repo: gix::ThreadSafeRepository,
/// `None` after the repository was replaced or went away. gitoxide memory-maps packs, and
/// reading a mapping whose volume was unmounted raises SIGBUS, so that handle is never reused.
repo: Option<gix::ThreadSafeRepository>,
/// The git and common directories `repo` was opened from.
dirs: [PathBuf; 2],
handles: Option<DirHandles>,
files: [PathBuf; 4],
stamp: Vec<Option<(SystemTime, u64)>>,
/// `objects/pack` directory and its modification time. An external
@@ -49,6 +54,49 @@ fn stamp(files: &[PathBuf]) -> Vec<Option<(SystemTime, u64)>> {
.collect()
}
/// Tells whether the repository's directories are still the ones its handle was opened from.
///
/// Comparing paths is not enough: a remounted volume can have the same device, inodes and
/// modification times. A descriptor opened before the unmount stays invalid after it.
#[cfg(unix)]
struct DirHandles([std::fs::File; 2]);
#[cfg(unix)]
impl DirHandles {
fn open(dirs: &[PathBuf; 2]) -> Option<Self> {
let mut options = std::fs::OpenOptions::new();
options.read(true);
// Any other descriptor makes a normal unmount (Eject) fail because the volume is busy.
#[cfg(target_os = "macos")]
std::os::unix::fs::OpenOptionsExt::custom_flags(&mut options, libc::O_EVTONLY);
Some(Self([options.open(&dirs[0]).ok()?, options.open(&dirs[1]).ok()?]))
}
fn is_current(&self, dirs: &[PathBuf; 2]) -> bool {
use std::os::unix::fs::MetadataExt;
self.0.iter().zip(dirs).all(|(held, dir)| match (held.metadata(), std::fs::metadata(dir)) {
(Ok(held), Ok(now)) => (held.dev(), held.ino()) == (now.dev(), now.ino()),
_ => false,
})
}
}
// ponytail: existence only, because an open directory handle blocks renaming it on Windows.
// A volume that returns between two calls goes unnoticed; compare file ids if that matters.
#[cfg(not(unix))]
struct DirHandles;
#[cfg(not(unix))]
impl DirHandles {
fn open(dirs: &[PathBuf; 2]) -> Option<Self> {
Self.is_current(dirs).then_some(Self)
}
fn is_current(&self, dirs: &[PathBuf; 2]) -> bool {
dirs.iter().all(|dir| dir.is_dir())
}
}
/// The pack directory's modification time: adding or removing a pack file
/// updates it. `None` when the directory can't be read.
fn pack_stamp(pack_dir: &Path) -> Option<SystemTime> {
@@ -77,7 +125,16 @@ pub(crate) fn discover(path: &Path) -> IdeResult<Option<Repo>> {
let common_dir = absolute(repo.common_dir())?;
let files = cache_files(&git_dir, &common_dir);
let pack_dir = common_dir.join("objects").join("pack");
let cache = Cache { stamp: stamp(&files), files, repo: ts, pack_stamp: pack_stamp(&pack_dir), pack_dir };
let dirs = [git_dir.clone(), common_dir];
let cache = Cache {
stamp: stamp(&files),
files,
repo: Some(ts),
handles: DirHandles::open(&dirs),
dirs,
pack_stamp: pack_stamp(&pack_dir),
pack_dir,
};
Ok(Some(Repo {
execution_allowed: std::sync::atomic::AtomicBool::new(false),
git_executable: std::sync::RwLock::new(crate::opening_git_executable()),
@@ -141,6 +198,8 @@ impl Repo {
/// A thread-local gitoxide handle; reopened when configuration or packed refs change.
/// gitoxide's packed-ref snapshot only reloads for a newer mtime, which a replacement may preserve.
/// A volume lost after this returns can still raise SIGBUS in the caller: gitoxide can't read
/// packs without mapping them.
pub(crate) fn gix(&self) -> IdeResult<gix::Repository> {
let _scope = self.execution_scope();
self.check_valid()?;
@@ -149,12 +208,20 @@ impl Repo {
.map_err(gx);
}
let mut cache = self.inner.lock().unwrap_or_else(|p| p.into_inner());
if !cache.handles.as_ref().is_some_and(|handles| handles.is_current(&cache.dirs)) {
cache.repo = None;
// Before the repository is opened, so that losing the volume meanwhile is noticed.
cache.handles = DirHandles::open(&cache.dirs);
if cache.handles.is_none() {
return Err(self.stale_error());
}
}
let now = stamp(&cache.files);
let pack_now = pack_stamp(&cache.pack_dir);
if now != cache.stamp || pack_now != cache.pack_stamp {
if cache.repo.is_none() || now != cache.stamp || pack_now != cache.pack_stamp {
match gix::ThreadSafeRepository::open(&self.git_dir) {
Ok(fresh) => {
cache.repo = fresh;
cache.repo = Some(fresh);
cache.stamp = now;
cache.pack_stamp = pack_now;
}
@@ -163,11 +230,14 @@ impl Repo {
cache.stamp = now;
cache.pack_stamp = pack_now;
self.check_valid()?;
if cache.repo.is_none() {
return Err(gx(e));
}
tracing::warn!("reopening repository failed: {e}");
}
}
}
let mut repo = cache.repo.to_thread_local();
let mut repo = cache.repo.as_ref().ok_or_else(|| self.stale_error())?.to_thread_local();
repo.object_cache_size_if_unset(4 * 1024 * 1024);
Ok(repo)
}
@@ -577,3 +647,44 @@ pub(crate) fn is_ignored(repo: &gix::Repository, rel: &str) -> IdeResult<bool> {
pub(crate) fn to_string(b: &BStr) -> String {
b.to_str_lossy().into_owned()
}
#[cfg(all(test, unix))]
mod tests {
use super::*;
use std::process::Command;
use std::sync::Arc;
fn run(cmd: &mut Command) {
assert!(cmd.status().unwrap().success(), "{cmd:?}");
}
/// What a remounted volume looks like: every path and modification time is the same, but
/// the files that the old handle mapped are gone. `tests/volume_loss.rs` does it for real.
#[test]
fn a_replaced_repository_is_reopened_even_when_its_stamps_are_the_same() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().join("repo");
let copy = tmp.path().join("copy");
run(Command::new("git").args(["init", "-q"]).arg(&root));
let repo = discover(&root).unwrap().unwrap();
repo.set_execution_allowed(true);
let store = || repo.gix().unwrap().objects.store();
let stamps = || {
let cache = repo.inner.lock().unwrap();
(stamp(&cache.files), pack_stamp(&cache.pack_dir))
};
let (first, before) = (store(), stamps());
assert!(Arc::ptr_eq(&first, &store()), "an unchanged repository keeps its handle");
run(Command::new("cp").arg("-pR").arg(&root).arg(&copy));
std::fs::rename(&root, tmp.path().join("old")).unwrap();
assert!(repo.gix().is_err());
assert!(repo.gix().is_err());
std::fs::rename(&copy, &root).unwrap();
assert_eq!(stamps(), before, "the stamps must not be what triggers the reopen");
let second = store();
assert!(!Arc::ptr_eq(&first, &second), "the handle to the replaced repository was reused");
assert!(Arc::ptr_eq(&second, &store()), "it is reopened once");
}
}
+79
Переглянути файл
@@ -0,0 +1,79 @@
//! A long file history walk must not hold the log index while Git runs: commit details and
//! one-commit queries (inline blame, the blame popup) share that index.
#![cfg(unix)]
use ide_vcs::{LogQuery, Repo};
use std::os::unix::fs::PermissionsExt;
use std::path::Path;
use std::process::Command;
use std::time::{Duration, Instant};
fn git(dir: &Path, args: &[&str]) -> String {
let out = Command::new("git")
.current_dir(dir)
.args([
"-c",
"init.defaultBranch=main",
"-c",
"user.name=T",
"-c",
"user.email=t@e",
"-c",
"commit.gpgsign=false",
])
.args(args)
.output()
.unwrap();
assert!(out.status.success(), "{args:?}: {}", String::from_utf8_lossy(&out.stderr));
String::from_utf8_lossy(&out.stdout).trim().to_string()
}
#[test]
fn details_and_one_commit_queries_do_not_wait_for_a_file_history_walk() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path().join("repo");
std::fs::create_dir(&dir).unwrap();
git(&dir, &["init", "-q"]);
for i in 0..3 {
std::fs::write(dir.join("file"), format!("{i}")).unwrap();
git(&dir, &["add", "-A"]);
git(&dir, &["commit", "-qm", &format!("c{i}")]);
}
// A git whose path-limited history walks take seconds.
let real = String::from_utf8(Command::new("sh").args(["-c", "command -v git"]).output().unwrap().stdout).unwrap();
let started = tmp.path().join("walk-started");
let wrapper = tmp.path().join("slow-git");
std::fs::write(
&wrapper,
format!(
"#!/bin/sh\ncase \" $* \" in *\" --full-history \"*) : > '{}'; sleep 3;; esac\nexec '{}' \"$@\"\n",
started.display(),
real.trim()
),
)
.unwrap();
std::fs::set_permissions(&wrapper, std::fs::Permissions::from_mode(0o755)).unwrap();
let repo = Repo::discover(&dir).unwrap().unwrap();
repo.set_execution_allowed(true);
repo.set_git_executable(Some(&wrapper));
std::thread::scope(|scope| {
let walk = scope.spawn(|| {
repo.log(&LogQuery { path: Some("file".into()), follow: true, ..Default::default() }).unwrap().len()
});
let deadline = Instant::now() + Duration::from_secs(20);
while !started.exists() {
assert!(Instant::now() < deadline, "the history walk never started");
std::thread::sleep(Duration::from_millis(20));
}
let asked = Instant::now();
let details = repo.log_details("HEAD").unwrap();
let head = repo.log(&LogQuery { branch: Some("HEAD".into()), limit: 1, ..Default::default() }).unwrap();
let waited = asked.elapsed();
println!("queries waited {waited:?}");
assert_eq!(details.message, "c2");
assert_eq!(head.len(), 1);
assert!(!walk.is_finished(), "the walk ended before the queries ran; the test proves nothing");
assert!(waited < Duration::from_secs(2), "queries waited {waited:?} for the walk");
assert_eq!(walk.join().unwrap(), 3);
});
}
+139
Переглянути файл
@@ -0,0 +1,139 @@
//! Status after the repository's volume disappears. A stale memory-mapped pack index raises
//! SIGBUS there, which kills the process instead of failing the call.
#![cfg(target_os = "macos")]
use ide_vcs::Repo;
use std::path::{Path, PathBuf};
use std::process::{Command, Output};
fn run(cmd: &mut Command) {
let out = cmd.output().unwrap();
assert!(out.status.success(), "{cmd:?}: {}", String::from_utf8_lossy(&out.stderr));
}
fn git(dir: &Path, args: &[&str]) {
run(Command::new("git")
.current_dir(dir)
.args(["-c", "user.name=t", "-c", "[email protected]", "-c", "commit.gpgsign=false"])
.args(args));
}
/// A repository whose objects are all packed, with one staged change so that status has
/// to read the `HEAD` tree.
fn packed_repo(dir: &Path, files: usize) {
std::fs::create_dir_all(dir).unwrap();
git(dir, &["init", "-q"]);
for i in 0..files {
std::fs::write(dir.join(format!("f{i}")), format!("{i}\n")).unwrap();
}
git(dir, &["add", "."]);
git(dir, &["commit", "-qm", "init"]);
git(dir, &["repack", "-adq"]);
git(dir, &["pack-refs", "--all"]);
std::fs::write(dir.join("f0"), "changed\n").unwrap();
git(dir, &["add", "f0"]);
}
/// An APFS disk image mounted in a temporary directory, detached when dropped.
struct Image {
tmp: tempfile::TempDir,
}
impl Image {
fn new() -> Self {
let image = Self { tmp: tempfile::tempdir().unwrap() };
std::fs::create_dir(image.mount()).unwrap();
run(Command::new("hdiutil")
.args(["create", "-quiet", "-size", "200m", "-fs", "APFS", "-volname", "openidea-test"])
.arg(image.file()));
image.attach();
image
}
fn file(&self) -> PathBuf {
self.tmp.path().join("t.dmg")
}
fn mount(&self) -> PathBuf {
self.tmp.path().join("mnt")
}
fn attach(&self) {
run(Command::new("hdiutil")
.args(["attach", "-nobrowse", "-quiet", "-mountpoint"])
.arg(self.mount())
.arg(self.file()));
}
fn force_detach(&self) {
run(Command::new("hdiutil").args(["detach", "-force", "-quiet"]).arg(self.mount()));
}
/// Unmounts like Eject does: refused while a process keeps the volume busy.
fn unmount(&self) -> Output {
Command::new("diskutil").arg("unmount").arg(self.mount()).output().unwrap()
}
}
impl Drop for Image {
fn drop(&mut self) {
// After a normal unmount the image is still attached, and only a mounted volume can
// be detached by its path.
let _ = Command::new("hdiutil")
.args(["attach", "-nobrowse", "-quiet", "-mountpoint"])
.arg(self.mount())
.arg(self.file())
.output();
let _ = Command::new("hdiutil").args(["detach", "-force", "-quiet"]).arg(self.mount()).output();
}
}
/// Run with `cargo test -p ide-vcs --test volume_loss -- --ignored`: needs `hdiutil`.
#[test]
#[ignore = "mounts and force-detaches a disk image"]
fn a_force_detached_volume_does_not_crash_status() {
let image = Image::new();
let root = image.mount().join("repo");
packed_repo(&root, 5000);
// Start with cold pages, as after a real reconnect.
image.force_detach();
image.attach();
let repo = Repo::discover(&root).unwrap().unwrap();
repo.set_execution_allowed(true);
assert_eq!(repo.status().unwrap().len(), 1);
image.force_detach();
for _ in 0..2 {
assert!(repo.status().is_err());
assert!(repo.head().is_err());
}
image.attach();
assert_eq!(repo.status().unwrap().len(), 1);
// Gone and back between two calls: same path, same modification times.
image.force_detach();
image.attach();
assert_eq!(repo.status().unwrap().len(), 1);
assert!(repo.head().unwrap().1.is_some());
}
/// Only the descriptors: this reads nothing, so gitoxide has not mapped any packs yet.
#[test]
#[ignore = "mounts and unmounts a disk image"]
fn the_directory_descriptors_do_not_block_a_normal_unmount() {
let image = Image::new();
let root = image.mount().join("repo");
packed_repo(&root, 3);
image.force_detach();
image.attach();
let repo = Repo::discover(&root).unwrap().unwrap();
repo.set_execution_allowed(true);
let out = image.unmount();
assert!(out.status.success(), "{}{}", String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr));
assert!(repo.status().is_err());
image.attach();
assert_eq!(repo.status().unwrap().len(), 1);
}
+1
Переглянути файл
@@ -24,6 +24,7 @@ globset.workspace = true
uuid.workspace = true
zip.workspace = true
encoding_rs.workspace = true
quick-xml = "0.42"
[target.'cfg(windows)'.dependencies]
winreg = "0.56"
+344 -5
Переглянути файл
@@ -162,6 +162,127 @@ fn is_missing(path: &Path) -> bool {
path.is_absolute() && !text.contains("://") && !wsl && !path.exists()
}
fn folder_name(path: &Path) -> String {
path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| path.display().to_string())
}
/// What importing a JetBrains IDE's recent projects did (or, as a preview, would do).
#[derive(Clone, Debug, Default, PartialEq, Serialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct JetBrainsRecentImport {
/// Projects added to the recent projects.
pub imported: u32,
/// Projects left out because their folder no longer exists.
pub missing: u32,
/// Project groups added.
pub groups: u32,
}
/// A recent project as a JetBrains IDE keeps it in `options/recentProjects.xml`.
#[derive(Debug, Default, PartialEq)]
struct JetBrainsRecent {
path: String,
name: Option<String>,
opened_at_ms: f64,
/// Opened but not listed (LightEdit, a file opened alone): the IDE does not show it.
hidden: bool,
}
#[derive(Debug, Default, PartialEq)]
struct JetBrainsGroup {
name: String,
paths: Vec<String>,
expanded: bool,
}
/// The `RecentProjectsManager` state: `additionalInfo` entries (path → `RecentProjectMetaInfo`) and
/// `groups` (`ProjectGroup` with `name`, `expanded` and its `projects`).
fn parse_jetbrains_recent(xml: &str) -> (Vec<JetBrainsRecent>, Vec<JetBrainsGroup>) {
use quick_xml::{Reader, XmlVersion, events::Event};
let mut reader = Reader::from_str(xml);
let (mut projects, mut groups) = (Vec::new(), Vec::new());
let mut project: Option<JetBrainsRecent> = None;
let mut group: Option<JetBrainsGroup> = None;
loop {
let (tag, empty) = match reader.read_event() {
Ok(Event::Start(tag)) => (tag, false),
Ok(Event::Empty(tag)) => (tag, true),
Ok(Event::End(tag)) => {
match tag.local_name().as_ref() {
"entry" => projects.extend(project.take()),
"ProjectGroup" => groups.extend(group.take()),
_ => {}
}
continue;
}
Ok(Event::Eof) | Err(_) => break,
_ => continue,
};
let attr = |key: &str| {
tag.attributes()
.flatten()
.find(|a| a.key.as_ref() == key)
.and_then(|a| a.normalized_value(XmlVersion::Implicit1_0).ok().map(|v| v.into_owned()))
};
match tag.local_name().as_ref() {
"entry" if !empty && group.is_none() => {
project = attr("key").map(|path| JetBrainsRecent { path, ..Default::default() });
}
"RecentProjectMetaInfo" => {
if let Some(p) = &mut project {
p.hidden = attr("hidden").as_deref() == Some("true");
}
}
"ProjectGroup" if !empty => group = Some(JetBrainsGroup::default()),
"option" => {
let (name, value) = (attr("name"), attr("value"));
if let Some(g) = &mut group {
match (name.as_deref(), value) {
(Some("name"), Some(v)) => g.name = v,
(Some("expanded"), Some(v)) => g.expanded = v == "true",
// `<option name="projects"><list><option value="…"/>`.
(None, Some(v)) => g.paths.push(v),
_ => {}
}
} else if let Some(p) = &mut project {
match (name.as_deref(), value) {
(Some("customProjectName"), Some(v)) => p.name = Some(v),
// Older IDEs.
(Some("displayName"), Some(v)) if p.name.is_none() => p.name = Some(v),
(Some("projectOpenTimestamp" | "activationTimestamp"), Some(v)) => {
p.opened_at_ms = p.opened_at_ms.max(v.parse().unwrap_or(0.0));
}
_ => {}
}
}
}
_ => {}
}
}
(projects, groups)
}
/// A path of `recentProjects.xml`: `$USER_HOME$` is `home`, `$APPLICATION_CONFIG_DIR$` the IDE's settings
/// folder `config`; Windows paths are stored with `/`. `None` for other path variables or a relative path.
fn expand_jetbrains_path(raw: &str, home: Option<&Path>, config: &Path) -> Option<PathBuf> {
let (base, rest) = if let Some(rest) = raw.strip_prefix("$USER_HOME$") {
(Some(home?), rest)
} else if let Some(rest) = raw.strip_prefix("$APPLICATION_CONFIG_DIR$") {
(Some(config), rest)
} else {
(None, raw)
};
if rest.contains('$') {
return None;
}
let rest = if cfg!(windows) { rest.replace('/', "\\") } else { rest.to_owned() };
let path = match base {
Some(base) => base.join(rest.trim_start_matches(['/', '\\'])),
None => PathBuf::from(rest),
};
path.is_absolute().then_some(path)
}
impl RecentProjects {
pub fn load(config_dir: &Path) -> Self {
let file = config_dir.join("recent.json");
@@ -208,8 +329,7 @@ impl RecentProjects {
pub fn touch(&self, path: &Path, branch: Option<String>) -> IdeResult<()> {
let mut items = self.items.lock();
items.retain(|p| p.path != path);
let name =
path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| path.display().to_string());
let name = folder_name(path);
items.insert(0, RecentProject { path: path.into(), name, opened_at_ms: now_ms(), branch, missing: false });
cap(&mut items, &self.groups.lock());
self.persist(&items)
@@ -219,9 +339,7 @@ impl RecentProjects {
pub fn rename(&self, path: &Path, name: Option<&str>) -> IdeResult<()> {
let mut items = self.items.lock();
let Some(item) = items.iter_mut().find(|p| p.path == path) else { return Ok(()) };
let name = name.map(str::to_owned).unwrap_or_else(|| {
path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| path.display().to_string())
});
let name = name.map(str::to_owned).unwrap_or_else(|| folder_name(path));
if item.name == name {
return Ok(());
}
@@ -247,6 +365,91 @@ impl RecentProjects {
Ok(())
}
/// Adds the recent projects and project groups of a JetBrains IDE (`xml`: its
/// `options/recentProjects.xml`; `config`: its settings folder). Projects already recent keep their
/// entry, folders that are gone are left out, and the groups made here are kept: an imported group
/// whose name is taken gets a number, and one whose projects are all grouped already is not added.
/// `dry_run` only counts.
pub fn import_jetbrains(
&self,
xml: &str,
home: Option<&Path>,
config: &Path,
dry_run: bool,
) -> IdeResult<JetBrainsRecentImport> {
let (projects, jetbrains_groups) = parse_jetbrains_recent(xml);
let mut summary = JetBrainsRecentImport::default();
let mut items = self.items.lock();
let mut groups = self.groups.lock();
let mut new_items = items.clone();
let mut added = Vec::new();
for p in projects.into_iter().filter(|p| !p.hidden) {
let Some(path) = expand_jetbrains_path(&p.path, home, config).filter(|path| !is_missing(path)) else {
summary.missing += 1;
continue;
};
if new_items.iter().any(|i| i.path == path) {
continue;
}
let name = p.name.filter(|n| !n.trim().is_empty()).unwrap_or_else(|| folder_name(&path));
new_items.push(RecentProject {
path: path.as_path().into(),
name,
opened_at_ms: p.opened_at_ms,
branch: None,
missing: false,
});
added.push(path);
}
new_items.sort_by(|a, b| b.opened_at_ms.total_cmp(&a.opened_at_ms));
let mut new_groups = groups.clone();
for g in jetbrains_groups {
let base = g.name.trim().to_owned();
if base.is_empty() {
continue;
}
let mut name = base.clone();
for n in 2.. {
if !new_groups.iter().any(|existing| existing.name == name) {
break;
}
name = format!("{base} {n}");
}
let paths = g
.paths
.iter()
.filter_map(|raw| expand_jetbrains_path(raw, home, config))
.filter(|path| new_items.iter().any(|i| i.path == *path))
.map(|path| path.as_path().into())
.collect();
new_groups.push(RecentProjectGroup { name, paths, expanded: g.expanded });
}
// Existing groups are normalized already, so they keep their place and their projects.
let mut new_groups = normalize(new_groups);
let existing = groups.len();
let mut index = 0;
new_groups.retain(|g| {
index += 1;
index <= existing || !g.paths.is_empty()
});
cap(&mut new_items, &new_groups);
summary.imported = added.iter().filter(|p| new_items.iter().any(|i| i.path == **p)).count() as u32;
summary.groups = (new_groups.len() - existing) as u32;
if dry_run {
return Ok(summary);
}
if summary.imported > 0 {
self.persist(&new_items)?;
*items = new_items;
}
if summary.groups > 0 {
write_json(&self.groups_file, &new_groups)?;
*groups = new_groups;
}
Ok(summary)
}
pub fn paths(&self) -> Vec<PathBuf> {
self.list().into_iter().map(|p| p.path.into_path_buf()).collect()
}
@@ -344,6 +547,142 @@ mod tests {
assert_eq!(recent.list().len(), 1);
}
const JETBRAINS_RECENT: &str = r#"<application>
<component name="RecentProjectsManager">
<option name="additionalInfo">
<map>
<entry key="$USER_HOME$/code/alpha">
<value>
<RecentProjectMetaInfo frameTitle="alpha – main.rs" projectWorkspaceId="w1">
<option name="activationTimestamp" value="1700000005000" />
<option name="colorInfo"><RecentProjectColorInfo associatedIndex="1" /></option>
<option name="customProjectName" value="Alpha Service" />
<option name="projectOpenTimestamp" value="1700000001000" />
</RecentProjectMetaInfo>
</value>
</entry>
<entry key="$USER_HOME$/code/beta">
<value>
<RecentProjectMetaInfo>
<option name="displayName" value="beta-old-name" />
<option name="projectOpenTimestamp" value="1700000003000" />
</RecentProjectMetaInfo>
</value>
</entry>
<entry key="$USER_HOME$/code/gone">
<value><RecentProjectMetaInfo /></value>
</entry>
<entry key="$APPLICATION_CONFIG_DIR$/light-edit">
<value><RecentProjectMetaInfo hidden="true" /></value>
</entry>
<entry key="$PROJECT_DIR$/x">
<value><RecentProjectMetaInfo /></value>
</entry>
</map>
</option>
<option name="groups">
<list>
<ProjectGroup>
<option name="expanded" value="true" />
<option name="name" value="Work" />
<option name="projects">
<list>
<option value="$USER_HOME$/code/alpha" />
<option value="$USER_HOME$/code/gone" />
</list>
</option>
</ProjectGroup>
<ProjectGroup>
<option name="name" value="Empty" />
</ProjectGroup>
</list>
</option>
<option name="lastOpenedProject" value="$USER_HOME$/code/alpha" />
</component>
</application>"#;
#[test]
fn parses_jetbrains_recent_projects_and_groups() {
let (projects, groups) = parse_jetbrains_recent(JETBRAINS_RECENT);
assert_eq!(projects.len(), 5);
assert_eq!(
projects[0],
JetBrainsRecent {
path: "$USER_HOME$/code/alpha".into(),
name: Some("Alpha Service".into()),
opened_at_ms: 1700000005000.0,
hidden: false,
}
);
assert_eq!(projects[1].name.as_deref(), Some("beta-old-name"));
assert!(projects[3].hidden);
assert_eq!(
groups,
vec![
JetBrainsGroup {
name: "Work".into(),
paths: vec!["$USER_HOME$/code/alpha".into(), "$USER_HOME$/code/gone".into()],
expanded: true,
},
JetBrainsGroup { name: "Empty".into(), paths: vec![], expanded: false },
]
);
}
#[test]
fn expands_jetbrains_path_variables() {
let (home, config) = (Path::new("/home/me"), Path::new("/cfg/IDE"));
assert_eq!(expand_jetbrains_path("$USER_HOME$/a/b", Some(home), config), Some(home.join("a").join("b")));
assert_eq!(expand_jetbrains_path("$APPLICATION_CONFIG_DIR$/x", Some(home), config), Some(config.join("x")));
assert_eq!(expand_jetbrains_path("$USER_HOME$", Some(home), config), Some(home.to_path_buf()));
assert_eq!(expand_jetbrains_path("$USER_HOME$/a", None, config), None);
assert_eq!(expand_jetbrains_path("$PROJECT_DIR$/a", Some(home), config), None);
assert_eq!(expand_jetbrains_path("relative/a", Some(home), config), None);
#[cfg(windows)]
assert_eq!(expand_jetbrains_path("C:/Users/me/a", Some(home), config), Some(PathBuf::from(r"C:\Users\me\a")));
}
#[test]
fn jetbrains_import_merges_without_touching_existing_groups() {
let tmp = tempfile::tempdir().unwrap();
let home = tmp.path().join("home");
for p in ["code/alpha", "code/beta", "mine"] {
std::fs::create_dir_all(home.join(p)).unwrap();
}
let (alpha, beta, mine) = (home.join("code/alpha"), home.join("code/beta"), home.join("mine"));
let cfg = tmp.path().join("config");
let recent = RecentProjects::load(&cfg);
recent.touch(&mine, None).unwrap();
recent.touch(&beta, None).unwrap();
let own = RecentProjectGroup { name: "Work".into(), paths: vec![mine.as_path().into()], expanded: true };
recent.set_groups(vec![own.clone()]).unwrap();
let ide = tmp.path().join("IDE");
let preview = recent.import_jetbrains(JETBRAINS_RECENT, Some(&home), &ide, true).unwrap();
let expected = JetBrainsRecentImport { imported: 1, missing: 2, groups: 1 };
assert_eq!(preview, expected);
assert_eq!(recent.list().len(), 2, "a preview changes nothing");
assert_eq!(recent.import_jetbrains(JETBRAINS_RECENT, Some(&home), &ide, false).unwrap(), expected);
let reloaded = RecentProjects::load(&cfg);
let list = reloaded.list();
let item = |p: &Path| list.iter().find(|i| i.path.as_ref() == p).unwrap();
assert_eq!(item(&alpha).name, "Alpha Service");
assert_eq!(item(&alpha).opened_at_ms, 1700000005000.0);
// Already recent: keeps its own entry.
assert_eq!(item(&beta).name, "beta");
assert_eq!(list.len(), 3);
// The group made here stays; the imported one gets a free name and only the imported projects.
let imported =
RecentProjectGroup { name: "Work 2".into(), paths: vec![alpha.as_path().into()], expanded: true };
assert_eq!(reloaded.groups(), vec![own.clone(), imported.clone()]);
// Importing again adds nothing.
let again = recent.import_jetbrains(JETBRAINS_RECENT, Some(&home), &ide, false).unwrap();
assert_eq!(again, JetBrainsRecentImport { imported: 0, missing: 2, groups: 0 });
assert_eq!(RecentProjects::load(&cfg).groups(), vec![own, imported]);
}
fn write_head(git_dir: &Path, contents: &str) {
std::fs::create_dir_all(git_dir).unwrap();
std::fs::write(git_dir.join("HEAD"), contents).unwrap();
+1
Переглянути файл
@@ -39,6 +39,7 @@ If the coverage tool is missing, a notification names it and offers **Install**,
| Node.js | `node`, `npx`, `tsx`, `ts-node` programs | `c8` |
| Python | scripts, modules, pytest | coverage.py (`coverage run --branch`) in the project's interpreter |
| Ruby | rspec, minitest, rake, rails and plain scripts | SimpleCov (in the Gemfile for Bundler projects) |
| Swift (Xcode) | Xcode test configurations (`xcodebuild test`) | `-enableCodeCoverage YES`, read from the result bundle with `xcrun xccov` |
Not supported:
+2
Переглянути файл
@@ -145,6 +145,8 @@ Tab placement, the tab limit and what happens when it is reached, the preview ta
With tabs placed left or right, the tab column is as wide as its longest name, up to a limit. Drag the column's inner edge (or focus it and press `←` / `→`) to change the limit; it applies to every editor group and is remembered.
Double-click a tab, or the empty part of the tab strip, to maximize the editor: all tool windows are hidden, and doing it again brings them back. Double-clicking a preview tab keeps it open as a regular tab instead.
## Split editors
| Action | macOS | Windows / Linux |
+16 -4
Переглянути файл
@@ -67,16 +67,24 @@ Open the folder that contains `buildServer.json` (or `.bsp/`) as the project, or
- **Classic groups**: a new file must be added to a target in Xcode (**File › Add Files to…**, or drag it into the group). When a new `.swift`, `.m`, `.h` or other source file isn't named in `project.pbxproj`, the IDE says so, with **Open in Xcode**.
- **[XcodeGen](https://github.com/yonaskolb/XcodeGen) (`project.yml`) and [Tuist](https://tuist.dev) (`Project.swift`)**: the project is generated from the spec, so after files change the IDE offers to regenerate it (`xcodegen generate` or `tuist generate --no-open`) in the Run tool window. **Regenerate Xcode Project** in **Find Action** (`⌘⇧A` / `Ctrl+Shift+A`), or in the context menu of `project.yml` and `Project.swift`, runs it any time.
### CocoaPods
In a project with a `Podfile`, the schemes of the `.xcodeproj` build through the `.xcworkspace` that `pod install` writes next to it, for run and test configurations alike, and the `Pods/` folder gets no run configurations of its own. Right-click the `Podfile`, or use **Build › Xcode** or **Find Action**:
- **Pod Install** runs `pod install`; **Pod Update** runs `pod update`.
Both run in the **Run** tool window in the folder of the `Podfile`, with the `pod` on your `PATH`; the IDE does not install CocoaPods. When the run succeeds, run configurations are detected again, and a `buildServer.json` that xcode-build-server generated for the project is generated again for the workspace. When `Pods/Manifest.lock` is missing or differs from `Podfile.lock` as the project opens, the IDE offers **Pod Install**.
### Several Xcode versions
To run sourcekit-lsp from a specific Xcode, set `DEVELOPER_DIR` in the server's environment: in **Settings › Languages & Frameworks › Language Servers**, select sourcekit-lsp and add it under **Startup › Environment variables**, or in `settings.toml`:
To use a specific Xcode in a project, choose it under **Xcode** in **Settings › Languages & Frameworks › Swift** (the list shows the Xcodes in `/Applications` and `~/Applications`), or in the project's `settings.toml`:
```toml
[languageServers.sourcekit-lsp]
env = { DEVELOPER_DIR = "/Applications/Xcode-beta.app/Contents/Developer" }
[languages.swift]
xcode = "/Applications/Xcode-beta.app"
```
Set it per project to use a different Xcode in each. It applies to sourcekit-lsp only; to build or run with the same Xcode, set `DEVELOPER_DIR` in the run configuration's environment variables too.
Everything the IDE starts in the project gets it as `DEVELOPER_DIR`: sourcekit-lsp, `xcodebuild` (run, test, Clean Build Folder), `simctl`, lldb-dap, coverage reports and new terminals. It also overrides a `DEVELOPER_DIR` from `.envrc`. Changing it restarts sourcekit-lsp. Empty uses the Xcode chosen with `xcode-select`.
## Formatting
@@ -100,6 +108,10 @@ Each scheme of a `.xcodeproj` or `.xcworkspace` in the project root gets an **Xc
- **macOS apps** are built with `-destination 'platform=macOS'`, and the app's executable (`<App>.app/Contents/MacOS/<App>`) runs directly: its output shows in the Run console, and **Stop** quits it. No simulator is booted.
- **Apps that support both** run on the simulator. Set **Simulator** to `macos` to run them on the Mac instead.
### Coverage of Xcode tests
**Run › Run with Coverage** on an Xcode test configuration runs `xcodebuild test -enableCodeCoverage YES` and reads the result bundle with `xcrun xccov`. The [Coverage](/en/guide/coverage) tool window and the editor gutter show the app and framework sources of the project; files that only test targets (`.xctest` bundles) compile and files outside the project, such as the SDK and DerivedData, are left out. Covered lines with a region that never ran (an `if` whose `else` was skipped) are marked partial.
### Debugging
Debugging uses lldb-dap. On macOS the IDE finds Xcode's copy through `xcrun -f lldb-dap`; elsewhere it comes with the Swift toolchain on `PATH`.
+1
Переглянути файл
@@ -35,6 +35,7 @@ description: "使用覆盖率运行配置,在编辑器、项目视图和覆盖
| Node.js | `node`、`npx`、`tsx`、`ts-node` 程序 | `c8` |
| Python | 脚本、模块、pytest | 项目解释器中的 coverage.py(`coverage run --branch`) |
| Ruby | rspec、minitest、rake、rails 和普通脚本 | SimpleCov(Bundler 项目需写在 Gemfile 中) |
| Swift(Xcode) | Xcode 测试配置(`xcodebuild test`) | `-enableCodeCoverage YES`,用 `xcrun xccov` 读取结果包 |
暂不支持:
+2
Переглянути файл
@@ -143,6 +143,8 @@ description: "多光标与选区、行编辑、剪贴板历史、代码折叠、
标签页放在左侧或右侧时,标签页列的宽度随最长的名称变化,但不超过一个上限。拖动该列靠近编辑器的边缘(或聚焦后按 `←` / `→`)可以调整上限;调整对所有编辑器组生效,并会被记住。
双击标签页或标签页栏的空白处可以最大化编辑器:隐藏所有工具窗口,再双击一次即恢复。双击预览标签页则会把它转为常规标签页。
## 拆分编辑器
| 操作 | macOS | Windows / Linux |
+16 -4
Переглянути файл
@@ -67,16 +67,24 @@ sourcekit-lsp 读不了 `.xcodeproj` 和 `.xcworkspace`。没有构建服务器
- **传统的组**:新文件需要在 Xcode 中加入 target(**File › Add Files to…**,或拖进对应的组)。新建的 `.swift`、`.m`、`.h` 等源文件没有出现在 `project.pbxproj` 中时,IDE 会提示,并提供 **在 Xcode 中打开**。
- **[XcodeGen](https://github.com/yonaskolb/XcodeGen)(`project.yml`)和 [Tuist](https://tuist.dev)(`Project.swift`)**:项目由配置文件生成,所以文件变更后 IDE 会提示重新生成(`xcodegen generate` 或 `tuist generate --no-open`),在运行工具窗口中执行。也可以随时通过 **查找操作**(`⌘⇧A` / `Ctrl+Shift+A`)或 `project.yml`、`Project.swift` 的右键菜单中的 **重新生成 Xcode 项目** 来运行。
### CocoaPods
项目里有 `Podfile` 时,`.xcodeproj` 的 scheme 会通过 `pod install` 在旁边生成的 `.xcworkspace` 构建,运行配置和测试配置都是如此;`Pods/` 文件夹不会单独生成运行配置。右键 `Podfile`,或者在 **构建 › Xcode**、查找操作中执行:
- **安装 Pods**执行 `pod install`;**更新 Pods**执行 `pod update`。
两者都在 `Podfile` 所在目录执行,使用 `PATH` 上的 `pod`,输出显示在运行工具窗口;IDE 不会自动安装 CocoaPods。运行成功后会重新检测运行配置;如果 xcode-build-server 之前是针对项目生成的 `buildServer.json`,会改为针对 workspace 重新生成。打开项目时如果 `Pods/Manifest.lock` 缺失或与 `Podfile.lock` 不一致,IDE 会提示运行**安装 Pods**。
### 多个 Xcode 版本
要让 sourcekit-lsp 使用某个特定的 Xcode,在服务器的环境中设置 `DEVELOPER_DIR`:在 **设置 › 语言和框架 › 语言服务器** 中选中 sourcekit-lsp,在 **启动 › 环境变量** 中添加;或者写在 `settings.toml` 中:
要让项目使用某个特定的 Xcode,在 **设置 › 语言和框架 › Swift** 的 **Xcode** 中选择(列表显示 `/Applications` 和 `~/Applications` 中的 Xcode),或者写在项目的 `settings.toml` 中:
```toml
[languageServers.sourcekit-lsp]
env = { DEVELOPER_DIR = "/Applications/Xcode-beta.app/Contents/Developer" }
[languages.swift]
xcode = "/Applications/Xcode-beta.app"
```
按项目设置即可让每个项目使用不同的 Xcode。它只对 sourcekit-lsp 生效;要用同一个 Xcode 构建或运行,在运行配置的环境变量里也设置 `DEVELOPER_DIR`。
IDE 在项目中启动的所有进程都会以 `DEVELOPER_DIR` 得到它:sourcekit-lsp、`xcodebuild`(运行、测试、Clean Build Folder)、`simctl`、lldb-dap、覆盖率报告和新开的终端。它也会覆盖 `.envrc` 中的 `DEVELOPER_DIR`。修改后会重启 sourcekit-lsp。留空则使用 `xcode-select` 选择的 Xcode。
## 格式化
@@ -100,6 +108,10 @@ env = { DEVELOPER_DIR = "/Applications/Xcode-beta.app/Contents/Developer" }
- **macOS App** 用 `-destination 'platform=macOS'` 构建,然后直接运行 App 的可执行文件(`<App>.app/Contents/MacOS/<App>`):输出显示在运行控制台里,**停止** 会退出 App。不会启动模拟器。
- **同时支持两者的 App** 在模拟器上运行。把 **模拟器** 设为 `macos` 就改在 Mac 上运行。
### Xcode 测试的覆盖率
对 Xcode 测试配置使用 **运行 › 使用覆盖率运行**,IDE 会执行 `xcodebuild test -enableCodeCoverage YES`,再用 `xcrun xccov` 读取结果包。[覆盖率](/zh/guide/coverage)工具窗口和编辑器边栏只显示项目中 App 和框架的源文件;只由测试目标(`.xctest` 包)编译的文件和项目之外的文件(例如 SDK 和 DerivedData)不计入。已执行、但其中有一段代码没有执行的行(例如跳过了 `else` 的 `if`)标为部分覆盖。
### 调试
调试使用 lldb-dap。在 macOS 上,IDE 通过 `xcrun -f lldb-dap` 找到 Xcode 中的副本;其他平台使用 `PATH` 上 Swift 工具链自带的副本。
+113
Переглянути файл
@@ -99,3 +99,116 @@ test("File History opens its revision and compares only that file with the worki
.poll(async () => ipcCalls(page, "vcs_file_at"))
.toContainEqual({ path: `${ROOT}/src/old-name.ts`, rev: REVISION });
});
test("File History creates and copies a patch for only the selected changed file", async ({ workbench: page }) => {
const parent = "b".repeat(40);
const selectedPath = "src/selected.ts";
const otherPath = "src/other.ts";
const patch = `diff --git a/${selectedPath} b/${selectedPath}\n`;
await stubDesktop(page);
await page.evaluate(
async ({ root, path, revision, parent, selectedPath, otherPath }) => {
const h = window.__ipc.handlers;
h.vcs_roots = () => [{ root, head: "main", headCommit: revision, operation: null }];
h.vcs_branch_info = () => ({
head: "main",
headCommit: revision,
upstream: null,
ahead: 0,
behind: 0,
operation: null,
});
h.vcs_branches = () => [];
h.vcs_status = () => [];
h.vcs_log = ({ query }) =>
(query as { path?: string }).path
? [
{
id: revision,
shortId: revision.slice(0, 8),
parents: [parent],
refs: [],
author: "Author",
email: "[email protected]",
timeMs: 1,
summary: "Export selected history file",
message: "Export selected history file",
historyPath: selectedPath,
},
]
: [];
h.vcs_log_refs = () => ({});
h.vcs_log_users = () => ["Author <[email protected]>"];
h.vcs_log_details_batch = () => [];
h.vcs_commit_files = () => [
{ path: selectedPath, kind: "modified", oldPath: null },
{ path: otherPath, kind: "modified", oldPath: null },
];
h.vcs_create_patch = ({ source }) => {
const paths = (source as { paths?: string[] }).paths ?? [];
return paths.map((entry) => `diff --git a/${entry} b/${entry}\n`).join("");
};
h.vcs_write_patch = () => null;
h.clipboard_write_text = () => null;
const projectModule = "/src/platform/project.ts";
const { useProject } = await import(/* @vite-ignore */ projectModule);
useProject.setState((state: { settings: Record<string, unknown> }) => ({
settings: {
...state.settings,
vcs: { confirmation: { onPatchCreated: "no" } },
},
}));
const storeModule = "/src/features/vcs/store.ts";
const { useVcs } = await import(/* @vite-ignore */ storeModule);
useVcs.setState({ available: true, root, repo: root, roots: [root], branchesLoaded: true, statusLoaded: true });
const contextModule = "/src/platform/context.ts";
const { setContext } = await import(/* @vite-ignore */ contextModule);
setContext("vcsAvailable", true);
const actionsModule = "/src/platform/actions.ts";
const { executeAction } = await import(/* @vite-ignore */ actionsModule);
await executeAction("vcs.showHistory", { path });
},
{ root: ROOT, path: `${ROOT}/${selectedPath}`, revision: REVISION, parent, selectedPath, otherPath },
);
const row = page.getByRole("listbox", { name: "Commits" }).getByRole("option", {
name: /Export selected history file/,
});
await expect(row).toBeVisible();
await row.click();
const tree = page.getByRole("tree", { name: "Changed files" });
const selected = tree.getByText("selected.ts", { exact: true });
await expect(selected).toBeVisible();
await expect(tree.getByText("other.ts", { exact: true })).toBeVisible();
const toolbar = page.getByRole("toolbar", { name: "Changed files" });
const create = toolbar.getByRole("button", { name: "Create Patch…", exact: true });
await expect(create).toBeDisabled();
await selected.click();
await expect(create).toBeEnabled();
await create.click();
const dialog = page.getByRole("dialog", { name: "Create Patch", exact: true });
await expect(dialog.getByRole("textbox", { name: "Base directory" })).toHaveValue(ROOT);
const destination = await dialog.getByRole("textbox", { name: "Patch file" }).inputValue();
expect(destination).toBe(`${ROOT}/Export_selected_history_file.patch`);
await dialog.getByRole("button", { name: "Create", exact: true }).click();
const source = { from: "revisions", before: parent, after: REVISION, paths: [selectedPath] };
await expect.poll(() => ipcCalls(page, "vcs_create_patch")).toEqual([{ repo: ROOT, base: ROOT, source }]);
await expect
.poll(() => ipcCalls(page, "vcs_write_patch"))
.toEqual([expect.objectContaining({ path: destination, patch })]);
await selected.click({ button: "right" });
await page
.getByRole("menu", { name: "Context menu" })
.getByRole("menuitem", { name: "Copy as Patch to Clipboard", exact: true })
.click();
await expect.poll(() => ipcCalls(page, "clipboard_write_text")).toEqual([{ text: patch }]);
await expect
.poll(() => ipcCalls(page, "vcs_create_patch"))
.toEqual([
{ repo: ROOT, base: ROOT, source },
{ repo: ROOT, base: null, source },
]);
});
+87
Переглянути файл
@@ -202,6 +202,93 @@ test("File Structure prefers matches inside the caret symbol", async ({ workbenc
await expect(tree.getByRole("treeitem", { name: "load", exact: true })).toHaveAttribute("aria-selected", "false");
});
test("File Structure auto-enables temporary filters without saving them", async ({ workbench: page }) => {
await openFromTree(page, "build.gradle.kts");
await stubDesktop(page);
await page.evaluate(async () => {
const optionsPath = "/src/features/search/structure/store.ts";
const { useStructureOptions } = await import(/* @vite-ignore */ optionsPath);
useStructureOptions.setState({ showFields: false, showNonPublic: false, showInherited: false, narrowDown: true });
const range = { start: { line: 0, col: 0 }, end: { line: 1, col: 1 } };
const symbol = (name: string, kind: string, visibility?: string) => ({
name,
kind,
visibility,
range,
selection_range: range,
children: [],
});
window.__ipc.handlers.doc_outline = () => [
{
...symbol("Container", "class"),
children: [
symbol("hiddenField", "field"),
symbol("hiddenMethod", "method", "private"),
symbol("visible", "method"),
],
},
];
window.__ipc.handlers.lsp_type_hierarchy = () => [];
const actionsPath = "/src/platform/actions.ts";
const { executeAction } = await import(/* @vite-ignore */ actionsPath);
await executeAction("navigate.fileStructure");
});
const dialog = page.getByRole("dialog", { name: "File Structure" });
const filter = dialog.getByRole("textbox", { name: "Filter symbols" });
const tree = dialog.getByRole("tree", { name: "Symbols" });
const fields = dialog.getByRole("checkbox", { name: "Show fields" });
const nonPublic = dialog.getByRole("checkbox", { name: "Show non-public" });
const readOptions = () =>
page.evaluate(async () => {
const path = "/src/features/search/structure/store.ts";
const { useStructureOptions } = await import(/* @vite-ignore */ path);
const { showFields, showNonPublic, showInherited } = useStructureOptions.getState();
return { showFields, showNonPublic, showInherited };
});
await expect(fields).not.toBeChecked();
await expect(nonPublic).not.toBeChecked();
await filter.fill("hiddenField");
await expect(fields).toBeChecked();
await expect(nonPublic).not.toBeChecked();
await expect(tree.getByRole("treeitem", { name: "hiddenField", selected: true })).toBeVisible();
expect(await readOptions()).toEqual({ showFields: false, showNonPublic: false, showInherited: false });
await nonPublic.check();
expect(await readOptions()).toEqual({ showFields: false, showNonPublic: true, showInherited: false });
const saved = await page.evaluate(() => localStorage.getItem("openidea.structure.options.v1"));
await filter.press("End");
await filter.press("Backspace");
await expect(filter).toHaveValue("hiddenFiel");
await expect(fields).not.toBeChecked();
await expect(nonPublic).toBeChecked();
await expect(tree.getByRole("treeitem", { name: "hiddenField", exact: true })).toBeHidden();
expect(await readOptions()).toEqual({ showFields: false, showNonPublic: true, showInherited: false });
await filter.fill("hiddenField");
await expect(fields).toBeChecked();
await fields.uncheck();
await expect(fields).not.toBeChecked();
await filter.press("Escape");
await expect(filter).toHaveValue("");
await expect(fields).not.toBeChecked();
await filter.press("Escape");
await expect(dialog).toBeHidden();
expect(await readOptions()).toEqual({ showFields: false, showNonPublic: true, showInherited: false });
expect(await page.evaluate(() => localStorage.getItem("openidea.structure.options.v1"))).toBe(saved);
await page.evaluate(async () => {
const path = "/src/platform/actions.ts";
const { executeAction } = await import(/* @vite-ignore */ path);
await executeAction("navigate.fileStructure");
});
await expect(dialog).toBeVisible();
await expect(dialog.getByRole("checkbox", { name: "Show fields" })).not.toBeChecked();
await expect(dialog.getByRole("checkbox", { name: "Show non-public" })).toBeChecked();
expect(await page.evaluate(() => localStorage.getItem("openidea.structure.options.v1"))).toBe(saved);
});
test("F4 jumps to the filtered File Structure symbol", async ({ workbench: page }) => {
await openFromTree(page, "build.gradle.kts");
await stubDesktop(page);
+46
Переглянути файл
@@ -43,3 +43,49 @@ test("Show Usages distinguishes same-named files without losing the line or snip
await expect(checkout.getByTitle("/dev/acme-api/packages/checkout/src/Routes.ts", { exact: true })).toBeVisible();
await expect(rows.filter({ hasText: "Worker.ts" }).getByText("src", { exact: true })).toHaveCount(0);
});
test("Show Usages resizes from its corner, the list fills it, and it reopens at that size", async ({
workbench: page,
}) => {
await page.setViewportSize({ width: 1200, height: 800 });
const show = () =>
page.evaluate(async () => {
const usages = "/src/features/code-insight/usages.ts";
const { useUsagesPopup } = await import(/* @vite-ignore */ usages);
const path = "/dev/app/src/Main.ts";
useUsagesPopup.setState({
open: true,
anchor: { x: 30, y: 60 },
symbol: "run",
groups: [
{
path,
usages: Array.from({ length: 40 }, (_, line) => ({ path, line, col: 0, endCol: 3, text: "run();" })),
},
],
});
});
await show();
const popup = page.getByRole("dialog", { name: "Usages", exact: true });
const list = popup.getByRole("listbox", { name: "Usages" });
const before = (await popup.boundingBox())!;
const listBefore = (await list.boundingBox())!;
const corner = (await popup.getByRole("separator", { name: "Resize" }).boundingBox())!;
await page.mouse.move(corner.x + corner.width / 2, corner.y + corner.height / 2);
await page.mouse.down();
await page.mouse.move(corner.x + 200, corner.y + 150, { steps: 5 });
await page.mouse.up();
const after = (await popup.boundingBox())!;
expect(after.width).toBeGreaterThan(before.width + 150);
expect(after.height).toBeGreaterThan(before.height + 100);
// The list, not empty space, takes the added height.
expect((await list.boundingBox())!.height).toBeGreaterThan(listBefore.height + 100);
await page.screenshot({ path: test.info().outputPath("usages-resized.png") });
await page.keyboard.press("Escape");
await expect(popup).toHaveCount(0);
await show();
const reopened = (await popup.boundingBox())!;
expect(Math.abs(reopened.width - after.width)).toBeLessThanOrEqual(1);
expect(Math.abs(reopened.height - after.height)).toBeLessThanOrEqual(1);
});
+12
Переглянути файл
@@ -0,0 +1,12 @@
import "../src/styles/tokens.css";
import { EditorView } from "@codemirror/view";
import { syntaxHighlighting } from "@codemirror/language";
import { openideaHighlightStyle } from "../src/editor/core/cm/highlight";
import { vueLanguage } from "../src/editor/core/cm/vue";
document.documentElement.dataset.theme = new URLSearchParams(location.search).get("theme") ?? "dark";
new EditorView({
parent: document.body,
doc: '<template>\n <div><Icon /><el-input v-model="x"></el-input></div>\n</template>\n',
extensions: [vueLanguage(), syntaxHighlighting(openideaHighlightStyle)],
});
+9
Переглянути файл
@@ -0,0 +1,9 @@
<!doctype html>
<html>
<head>
<meta charset="UTF-8" />
</head>
<body>
<script type="module" src="./vueHighlight.fixture.ts"></script>
</body>
</html>
+14
Переглянути файл
@@ -0,0 +1,14 @@
import { expect, test } from "@playwright/test";
for (const [theme, custom, tag] of [
["dark", "rgb(47, 186, 163)", "rgb(213, 183, 120)"],
["light", "rgb(178, 29, 191)", "rgb(0, 51, 179)"],
] as const) {
test(`Vue component tags have the custom tag colour (${theme})`, async ({ page }) => {
await page.goto(`/e2e/vueHighlight.html?theme=${theme}`);
const line = page.locator(".cm-line").nth(1);
await expect(line.getByText("Icon", { exact: true })).toHaveCSS("color", custom);
await expect(line.getByText("el-input", { exact: true }).first()).toHaveCSS("color", custom);
await expect(line.getByText("div", { exact: true }).first()).toHaveCSS("color", tag);
});
}
+1
Переглянути файл
@@ -60,6 +60,7 @@
"--syn-escape": "#7fd1c4",
"--syn-regexp": "#7fd1c4",
"--syn-tag": "#e0a46e",
"--syn-custom-tag": "#8fd4c9",
"--syn-attribute": "#9fc0e8",
"--syn-todo": "#7fd1c4",
"--syn-link": "#6fc3df",
+2 -1
Переглянути файл
@@ -333,7 +333,7 @@ a token.
<!-- BEGIN GENERATED TOKEN REFERENCE: pnpm gen:theme-docs -->
272 themeable tokens: 126 in the UI theme file, 146 in the editor colour scheme file.
273 themeable tokens: 126 in the UI theme file, 147 in the editor colour scheme file.
### Surfaces (UI theme)
@@ -482,6 +482,7 @@ a token.
| `--syn-escape` | `#cf8e6d` | `#0037a6` |
| `--syn-regexp` | `#42c3d4` | `#264eff` |
| `--syn-tag` | `#d5b778` | `#0033b3` |
| `--syn-custom-tag` | `#2fbaa3` | `#b21dbf` |
| `--syn-attribute` | `#bcbec4` | `#174ad4` |
| `--syn-todo` | `#8bb33d` | `#008dde` |
| `--syn-link` | `#548af7` | `#006dcc` |
+2
Переглянути файл
@@ -26,6 +26,8 @@ impl ApplicationFocus {
pub fn changed(app: &tauri::AppHandle, focused: bool) {
let generation = app.state::<ApplicationFocus>().changed(focused);
if focused {
#[cfg(target_os = "macos")]
crate::window_groups::detach_deferred(app);
return;
}
let app = app.clone();
+31
Переглянути файл
@@ -382,6 +382,36 @@ pub async fn settings_list_jetbrains_ides() -> IdeResult<Vec<ide_host::plugins::
.map_err(|e| IdeError::internal(e.to_string()))?
}
/// Import Recent Projects from JetBrains IDE: merges the recent projects and project groups of the IDE
/// whose settings folder is `path` (nothing when it has none); `dry_run` only counts them.
#[desktop_command(trust = always)]
#[tauri::command]
#[specta::specta]
pub async fn recent_import_jetbrains(
state: State<'_, AppState>,
path: PathBuf,
dry_run: bool,
) -> IdeResult<ide_workspace::recent::JetBrainsRecentImport> {
let app = state.app.clone();
tauri::async_runtime::spawn_blocking(move || {
let xml = match std::fs::read_to_string(path.join("options").join("recentProjects.xml")) {
Ok(xml) => xml,
Err(e) if matches!(e.kind(), std::io::ErrorKind::NotFound | std::io::ErrorKind::NotADirectory) => {
return Ok(Default::default());
}
Err(e) => return Err(e.into()),
};
let state = app.state::<AppState>();
let summary = state.recent.import_jetbrains(&xml, dirs::home_dir().as_deref(), &path, dry_run)?;
if summary.imported > 0 {
crate::jump_list::refresh(&state.app, state.recent.list());
}
Ok(summary)
})
.await
.map_err(|e| IdeError::internal(e.to_string()))?
}
pub(crate) fn project_current(window: Window) -> Option<ProjectInfo> {
let state = window.state::<AppState>();
state.project(window.label()).ok().filter(|p| !p.light).map(|p| project_info(&p))
@@ -466,6 +496,7 @@ ide_command::desktop_domain!(
log_frontend,
project_rename,
project_trust_add_location,
recent_import_jetbrains,
recent_project_groups,
recent_projects,
remove_recent_project,
+10
Переглянути файл
@@ -114,6 +114,16 @@ pub fn sync_tab_group(
})
}
pub fn fullscreen_in_background(window: &WebviewWindow) -> bool {
let target = window.clone();
on_main(window, move || {
let active =
MainThreadMarker::new().is_some_and(|mtm| objc2_app_kit::NSApplication::sharedApplication(mtm).isActive());
!active && native(&target).is_some_and(|w| w.styleMask().contains(objc2_app_kit::NSWindowStyleMask::FullScreen))
})
.unwrap_or(false)
}
/// Takes `window` out of its tab group into a window of its own; in full screen, a Space of its own.
pub fn move_tab_to_new_window(window: &WebviewWindow) -> tauri::Result<()> {
let target = window.clone();
+1
Переглянути файл
@@ -1533,6 +1533,7 @@ mod tests {
"file.exportSettings",
"file.importSettings",
"file.importJetBrainsSettings",
"file.importJetBrainsRecentProjects",
"file.syncSettings",
"file.togglePowerSave",
"macro.startRecording",
+18
Переглянути файл
@@ -201,9 +201,19 @@ pub fn merge(app: &AppHandle, caller: &str) -> IdeResult<()> {
select(app, caller, caller)
}
#[cfg(target_os = "macos")]
static DEFERRED_DETACH: parking_lot::Mutex<Vec<String>> = parking_lot::Mutex::new(Vec::new());
pub fn detach(app: &AppHandle, caller: &str) -> IdeResult<()> {
let err = |e: tauri::Error| IdeError::internal(e.to_string());
let state = app.state::<WindowsState>();
#[cfg(target_os = "macos")]
if state.groups.lock().group(caller).is_some()
&& app.get_webview_window(caller).is_some_and(|w| crate::macos::fullscreen_in_background(&w))
{
DEFERRED_DETACH.lock().push(caller.to_owned());
return Ok(());
}
let Some(next) = state.groups.lock().detach(caller) else {
changed(app);
return Ok(());
@@ -234,6 +244,14 @@ pub fn detach(app: &AppHandle, caller: &str) -> IdeResult<()> {
Ok(())
}
#[cfg(target_os = "macos")]
pub fn detach_deferred(app: &AppHandle) {
let labels = std::mem::take(&mut *DEFERRED_DETACH.lock());
for label in labels {
let _ = detach(app, &label);
}
}
pub fn destroyed(app: &AppHandle, caller: &str) {
let Some(state) = app.try_state::<WindowsState>() else { return };
let next = state.groups.lock().detach(caller);
+4
Переглянути файл
@@ -440,6 +440,8 @@ lsp_java_move_destinations trusted project_host bin
lsp_java_source_types trusted project_host bindings async
lsp_library_sources trusted project_host bindings async
lsp_message_request_answer trusted project_host bindings sync
lsp_move_to_file_targets trusted project_host bindings async
lsp_open_typescript_file trusted project_host bindings async
lsp_prepare_rename trusted project_host bindings async
lsp_prepare_type_hierarchy trusted project_host bindings async
lsp_references trusted project_host bindings async
@@ -458,6 +460,7 @@ lsp_signature_info trusted project_host bin
lsp_snapshot_completion trusted project_host bindings async
lsp_snapshot_diagnostics trusted project_host bindings async
lsp_source_action_text trusted project_host bindings async
lsp_source_definition trusted project_host bindings async
lsp_stop trusted project_host bindings async
lsp_switch_source_header trusted project_host bindings async
lsp_type_hierarchy trusted project_host bindings async
@@ -613,6 +616,7 @@ pypi_search outside_restricted project_host bin
python_requirements trusted project_host bindings async
python_route_sources trusted desktop bindings async
recent_files always project_host bindings sync
recent_import_jetbrains always desktop bindings async
recent_project_groups always desktop bindings sync
recent_projects always desktop bindings async
redo_workspace_edit always project_host bindings async
+105 -7
Переглянути файл
@@ -1145,6 +1145,13 @@ export const commands = {
* language server runs: the question waits in that process, a remote project's server included.
*/
lspMessageRequestAnswer: (id: number, choice: string | null) => typedError<null, IdeError>(__TAURI_INVOKE("lsp_message_request_answer", { id, choice })),
/**
* The files tsserver suggests for vtsls' Move to File code action `command`. Cancel with
* `cancel_request(request)`.
*/
lspMoveToFileTargets: (request: RequestId, doc: DocId, command: Command) => typedError<IpcPath[], IdeError>(__TAURI_INVOKE("lsp_move_to_file_targets", { request, doc, command })),
/** Has vtsls open the document's `tsconfig.json` / `jsconfig.json` or the TS Server log. */
lspOpenTypescriptFile: (doc: DocId, what: TypeScriptFile) => typedError<null, IdeError>(__TAURI_INVOKE("lsp_open_typescript_file", { doc, what })),
lspPrepareRename: (doc: DocId, pos: Pos) => typedError<{
start: Pos,
end: Pos,
@@ -1208,6 +1215,11 @@ export const commands = {
lspSnapshotCompletion: (path: string, text: string, pos: Pos, request: RequestId) => typedError<CompletionItem[], IdeError>(__TAURI_INVOKE("lsp_snapshot_completion", { path, text, pos, request })),
lspSnapshotDiagnostics: (path: string, text: string, request: RequestId) => typedError<Diagnostic[], IdeError>(__TAURI_INVOKE("lsp_snapshot_diagnostics", { path, text, request })),
lspSourceActionText: (path: string, text: string, kind: string, request: RequestId) => typedError<TextEdit[], IdeError>(__TAURI_INVOKE("lsp_source_action_text", { path, text, kind, request })),
/**
* Go to Source Definition (vtsls): the JavaScript implementation of the symbol at `pos`
* instead of its `.d.ts`. Cancel with `cancel_request(request)`.
*/
lspSourceDefinition: (request: RequestId, doc: DocId, pos: Pos) => typedError<Location[], IdeError>(__TAURI_INVOKE("lsp_source_definition", { request, doc, pos })),
/** Stops a language server; it starts again when a file it serves is opened. */
lspStop: (server: ServerId) => typedError<null, IdeError>(__TAURI_INVOKE("lsp_stop", { server })),
/**
@@ -1744,6 +1756,11 @@ export const commands = {
pythonRouteSources: () => typedError<RouteSource[], IdeError>(__TAURI_INVOKE("python_route_sources")),
/** Recently opened files, most recent first (⌘E). */
recentFiles: () => typedError<IpcPath[], IdeError>(__TAURI_INVOKE("recent_files")),
/**
* Import Recent Projects from JetBrains IDE: merges the recent projects and project groups of the IDE
* whose settings folder is `path` (nothing when it has none); `dry_run` only counts them.
*/
recentImportJetbrains: (path: string, dryRun: boolean) => typedError<JetBrainsRecentImport, IdeError>(__TAURI_INVOKE("recent_import_jetbrains", { path, dryRun })),
/** The welcome screen's project groups. */
recentProjectGroups: () => __TAURI_INVOKE<RecentProjectGroup[]>("recent_project_groups"),
recentProjects: () => __TAURI_INVOKE<RecentProject[]>("recent_projects"),
@@ -5865,7 +5882,9 @@ export type CoverageReportSpec =
/** Every JaCoCo XML report (Maven `target/site/jacoco`, Gradle `build/reports/jacoco`) under `dir`. */
{ kind: "jacoco"; dir: IpcPath } |
/** The tool's raw data is exported to lcov by `argv` first (coverage.py: `… -m coverage lcov -o <lcov>`). */
{ kind: "exported"; runner: string; argv: string[]; cwd: IpcPath; env: { [key in string]: string }; lcov: IpcPath };
{ kind: "exported"; runner: string; argv: string[]; cwd: IpcPath; env: { [key in string]: string }; lcov: IpcPath } |
/** An Xcode result bundle, read with `xcrun xccov`; only files under `root` are kept. */
{ kind: "xccov"; bundle: IpcPath; root: IpcPath };
/** One coverage run's report. */
export type CoverageSuite = {
@@ -10141,6 +10160,16 @@ export type JdkVendor = {
name: string,
};
/** What importing a JetBrains IDE's recent projects did (or, as a preview, would do). */
export type JetBrainsRecentImport = {
/** Projects added to the recent projects. */
imported: number,
/** Projects left out because their folder no longer exists. */
missing: number,
/** Project groups added. */
groups: number,
};
/**
* A JetBrains IDE's settings folder or exported archive: every
* entry name, and the text of the entries OpenIDEA maps (the frontend does the mapping).
@@ -10620,7 +10649,9 @@ export type LanguageServerSettings_Serialize = {
codeActionKinds?: string[] | null,
};
export type LanguagesSettings = {
export type LanguagesSettings = LanguagesSettings_Serialize | LanguagesSettings_Deserialize;
export type LanguagesSettings_Deserialize = {
/** Explicit plugin formatter, by language id. Empty entries use the normal formatter policy. */
pluginFormatters?: { [key in string]: string },
python?: PythonSettings,
@@ -10628,7 +10659,7 @@ export type LanguagesSettings = {
php?: PhpSettings,
rust?: RustSettings,
go?: GoSettings,
typescript?: TypeScriptSettings,
typescript?: TypeScriptSettings_Deserialize,
prettier?: ExternalFormatterSettings,
oxfmt?: ExternalFormatterSettings,
biome?: ExternalFormatterSettings,
@@ -10642,6 +10673,32 @@ export type LanguagesSettings = {
arduino?: ArduinoSettings,
zig?: ZigSettings,
flutter?: FlutterSettings,
swift?: SwiftSettings,
};
export type LanguagesSettings_Serialize = {
/** Explicit plugin formatter, by language id. Empty entries use the normal formatter policy. */
pluginFormatters: { [key in string]: string },
python: PythonSettings,
node: NodeSettings,
php: PhpSettings,
rust: RustSettings,
go: GoSettings,
typescript: TypeScriptSettings_Serialize,
prettier: ExternalFormatterSettings,
oxfmt: ExternalFormatterSettings,
biome: ExternalFormatterSettings,
/** dprint formats every file its configuration covers: `languages` is unused. */
dprint: ExternalFormatterSettings,
ruff: ExternalFormatterSettings,
black: ExternalFormatterSettings,
java: JavaSettings,
ruby: RubySettings,
markdown: MarkdownSettings,
arduino: ArduinoSettings,
zig: ZigSettings,
flutter: FlutterSettings,
swift: SwiftSettings,
};
export type LargeCommitFile = {
@@ -14457,7 +14514,9 @@ export type SdkKind = "python" | "node" |
/** .NET SDKs of the `dotnet` on the search path; `version` is what `global.json` pins. */
"dotnet" |
/** Flutter SDK roots. */
"flutter";
"flutter" |
/** `Xcode.app` bundles. */
"xcode";
/**
* IDEA's search context: matches anywhere, only in, or outside comments and
@@ -14718,7 +14777,7 @@ export type Settings_Deserialize = {
/** System Settings › HTTP Proxy (global only). */
proxy?: ProxySettings,
/** Interpreters / toolchains per language (Python, Node.js, Rust, Go, TypeScript). */
languages?: LanguagesSettings,
languages?: LanguagesSettings_Deserialize,
/** Project Structure: source / test / resource / excluded folders (project-relative). */
projectStructure?: ProjectStructureSettings,
/** Version Control (Git, Commit, Confirmation, Issue Navigation). */
@@ -14799,7 +14858,7 @@ export type Settings_Serialize = {
/** System Settings › HTTP Proxy (global only). */
proxy: ProxySettings,
/** Interpreters / toolchains per language (Python, Node.js, Rust, Go, TypeScript). */
languages: LanguagesSettings,
languages: LanguagesSettings_Serialize,
/** Project Structure: source / test / resource / excluded folders (project-relative). */
projectStructure: ProjectStructureSettings,
/** Version Control (Git, Commit, Confirmation, Issue Navigation). */
@@ -15408,6 +15467,14 @@ export type StubLink = {
export type SubmoduleRollbackSource = "head" | "index";
export type SwiftSettings = {
/**
* The Xcode (`Xcode.app` or its `Contents/Developer`) whose tools the project's sourcekit-lsp,
* `xcodebuild`, `xcrun` and terminals use, as `DEVELOPER_DIR`. Empty = the `xcode-select` one.
*/
xcode?: string,
};
export type SymbolFilter = "all" |
/** Go to Class (⌘O): classes, interfaces, structs, enums, traits, type aliases. */
"types";
@@ -15952,7 +16019,15 @@ export type TrustStatus = {
decided: boolean,
};
export type TypeScriptSettings = {
/** tsserver's log verbosity, as vtsls' `typescript.tsserver.log` spells it. */
export type TsServerLog = "off" | "terse" | "normal" | "requestTime" | "verbose";
/** A file vtsls opens for a document: its project's configuration or the TS Server log. */
export type TypeScriptFile = "projectConfig" | "serverLog";
export type TypeScriptSettings = TypeScriptSettings_Serialize | TypeScriptSettings_Deserialize;
export type TypeScriptSettings_Deserialize = {
/**
* `bundled` (the server's own TypeScript), `workspace` (`node_modules/typescript`),
* or a path to a TypeScript `lib` directory.
@@ -15964,6 +16039,8 @@ export type TypeScriptSettings = {
* vtsls default 3072 dies in a GC death spiral), else unset (vtsls default).
*/
tsserverMaxMemory?: number,
/** tsserver's log (`typescript.tsserver.log`). TypeScript: Open TS Server Log opens it. */
tsserverLog?: TsServerLog,
/**
* Problems › TypeScript project errors: the project's own `tsc --watch` per root
* `tsconfig.json` reports the errors of files that are not open.
@@ -15971,6 +16048,27 @@ export type TypeScriptSettings = {
watchProblems?: boolean,
};
export type TypeScriptSettings_Serialize = {
/**
* `bundled` (the server's own TypeScript), `workspace` (`node_modules/typescript`),
* or a path to a TypeScript `lib` directory.
*/
version: string,
/**
* tsserver heap limit in MB. `0` = automatic: 8192 when vtsls hosts the Vue
* plugin (hybrid mode; a Vue project's program alone needs ~3 GiB, and the
* vtsls default 3072 dies in a GC death spiral), else unset (vtsls default).
*/
tsserverMaxMemory: number,
/** tsserver's log (`typescript.tsserver.log`). TypeScript: Open TS Server Log opens it. */
tsserverLog: TsServerLog,
/**
* Problems › TypeScript project errors: the project's own `tsc --watch` per root
* `tsconfig.json` reports the errors of files that are not open.
*/
watchProblems: boolean,
};
/** A misspelt word. */
export type Typo = {
/** UTF-16 range of the word. */
+26
Переглянути файл
@@ -0,0 +1,26 @@
import { describe, expect, it } from "vitest";
import { ensureSyntaxTree } from "@codemirror/language";
import { EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { isCustomTagName } from "./customTags";
import { vueLanguage } from "./vue";
describe("Vue custom tag names", () => {
it("are PascalCase or hyphenated names", () => {
expect(["Icon", "el-input", "router-view", "MyButton"].map(isCustomTagName)).toEqual([true, true, true, true]);
expect(["div", "template", "span", "slot"].map(isCustomTagName)).toEqual([false, false, false, false]);
});
it("get their own colour in templates, opening and closing tags alike", () => {
const doc = `<template>\n <div><Icon /><el-input v-model="x"></el-input></div>\n</template>\n<script setup>\nconst a = 1 < 2\n</script>\n`;
const view = new EditorView({
state: EditorState.create({ doc, extensions: vueLanguage() }),
parent: document.body,
});
ensureSyntaxTree(view.state, doc.length, 5000);
view.dispatch({}); // let the plugin see the finished tree
const marked = [...view.dom.querySelectorAll(".cm-customTagName")].map((el) => el.textContent);
view.destroy();
expect(marked).toEqual(["Icon", "el-input", "el-input"]);
});
});
+52
Переглянути файл
@@ -0,0 +1,52 @@
/**
* WebStorm's "Custom tag name" colour: component tags in Vue templates (`<Icon>`, `<el-input>`)
* stand apart from HTML elements (`--syn-custom-tag`, the tag colour when a theme has none).
*/
import { syntaxTree } from "@codemirror/language";
import { RangeSetBuilder } from "@codemirror/state";
import { Decoration, EditorView, ViewPlugin, type DecorationSet, type ViewUpdate } from "@codemirror/view";
const customTag = Decoration.mark({ class: "cm-customTagName" });
/** A component, not an HTML element: PascalCase (`Icon`), or a custom-element name with a hyphen. */
export function isCustomTagName(name: string): boolean {
return /^[A-Z]/.test(name) || name.includes("-");
}
function decorations(view: EditorView): DecorationSet {
const builder = new RangeSetBuilder<Decoration>();
const tree = syntaxTree(view.state);
for (const { from, to } of view.visibleRanges) {
tree.iterate({
from,
to,
enter: (node) => {
if (node.name !== "TagName") return;
if (isCustomTagName(view.state.sliceDoc(node.from, node.to))) builder.add(node.from, node.to, customTag);
},
});
}
return builder.finish();
}
const plugin = ViewPlugin.fromClass(
class {
decorations: DecorationSet;
constructor(view: EditorView) {
this.decorations = decorations(view);
}
update(update: ViewUpdate) {
if (update.docChanged || update.viewportChanged || syntaxTree(update.state) !== syntaxTree(update.startState))
this.decorations = decorations(update.view);
}
},
{ decorations: (p) => p.decorations },
);
/** Colours component tag names in a template (the syntax highlighting's tag span inside included). */
export const customTagNames = [
plugin,
EditorView.baseTheme({
".cm-customTagName, .cm-customTagName *": { color: "var(--syn-custom-tag, var(--syn-tag))" },
}),
];
+42 -2
Переглянути файл
@@ -1,12 +1,12 @@
import { EditorSelection, EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { insertNewlineAndIndent } from "@codemirror/commands";
import { LanguageDescription, type Language } from "@codemirror/language";
import { LanguageDescription, indentUnit, type Language } from "@codemirror/language";
import { describe, expect, it } from "vitest";
import { getIndentation } from "@codemirror/language";
import { highlightTree, tagHighlighter, tags as t } from "@lezer/highlight";
import { logWarning } from "./highlight";
import { fencedCodeMode, findLanguageDescription, loadSupport } from "./languages";
import { commentTokens, fencedCodeMode, findLanguageDescription, loadSupport } from "./languages";
describe("language modes", () => {
it("highlights Julia declarations, calls, types, macros and literals without semantic tokens", async () => {
@@ -765,3 +765,43 @@ describe("language modes", () => {
expect(found).not.toContain("yes:keyword");
});
});
describe("Slint indentation", () => {
it("indents element blocks by their braces under the C highlighting mode", async () => {
const support = await loadSupport(findLanguageDescription("C", "/p/app.slint")!);
const slint = commentTokens({
id: "slint",
name: "Slint",
extensions: ["slint"],
uiMode: "C",
lineComment: "//",
blockComment: ["/*", "*/"],
indent: { tabSize: 4, insertSpaces: true },
});
const enter = (doc: string, at = doc.length) => {
const view = new EditorView({
state: EditorState.create({
doc,
selection: EditorSelection.cursor(at),
extensions: [support!, slint, indentUnit.of(" ")],
}),
parent: document.body,
});
insertNewlineAndIndent(view);
const out = view.state.doc.toString();
view.destroy();
return out;
};
const app = "export component App inherits Window {";
expect(enter(app)).toBe(`${app}\n `);
expect(enter(`${app}}`, app.length)).toBe(`${app}\n \n}`);
expect(enter(`${app}\n width: 100px;`)).toBe(`${app}\n width: 100px;\n `);
// After a child element closes, the next line stays at the child's level.
expect(enter(`${app}\n Text {\n text: "hi";\n }`)).toBe(
`${app}\n Text {\n text: "hi";\n }\n `,
);
expect(enter(`${app}\n Text {\n }\n Rectangle {`)).toBe(
`${app}\n Text {\n }\n Rectangle {\n `,
);
});
});
+8 -1
Переглянути файл
@@ -740,6 +740,13 @@ const NO_INDENT_LANGS = new Set([
"gitattributes",
]);
/**
* Languages highlighted by a borrowed mode whose own indentation doesn't fit them: Slint's
* element blocks (`Text { … }` without a `;`) read as unfinished C statements, so Enter after
* one lands at the wrong column. These use the brace-based fallback indentation instead.
*/
const BRACE_INDENT_OVER_MODE = new Set(["slint"]);
function opensBlock(code: string, language: string | undefined): boolean {
if (!code) return false;
if (/[{([]$/.test(code)) return true;
@@ -779,7 +786,7 @@ function indentationCode(text: string, lineComment: string | undefined): string
*/
export function fallbackIndent(language?: string): Extension {
return indentService.of((cx, pos) => {
if (cx.state.facet(languageFacet)) return undefined;
if (cx.state.facet(languageFacet) && !BRACE_INDENT_OVER_MODE.has(language ?? "")) return undefined;
const lineComment = cx.state.languageDataAt<{ line?: string }>("commentTokens", pos)[0]?.line;
const stripComment = (text: string) => indentationCode(text, lineComment);
+3 -1
Переглянути файл
@@ -9,6 +9,7 @@ import { html } from "@codemirror/lang-html";
import { lessLanguage } from "@codemirror/lang-less";
import { sassLanguage } from "@codemirror/lang-sass";
import { vue } from "@codemirror/lang-vue";
import { customTagNames } from "./customTags";
import { VERSIONED_SCRIPT_TYPES } from "./htmlScripts";
/**
@@ -41,5 +42,6 @@ export function vueLanguage(): LanguageSupport {
],
});
const language = (base.language as LRLanguage).configure({ props: [indentNodeProp.add({ Element: elementIndent })] });
return vue({ base: new LanguageSupport(language, base.support) });
const support = vue({ base: new LanguageSupport(language, base.support) });
return new LanguageSupport(support.language, [support.support, customTagNames]);
}
+8 -3
Переглянути файл
@@ -627,10 +627,14 @@ describe("EditorController", () => {
expect(openFilePaths(useTabs.getState())).toEqual(["/p/a.ts"]);
});
it("offers Find Usages immediately before Go To in the editor context menu", async () => {
ctrl = new EditorController(createMemoryBackend({ "/p/a.ts": "one\n" }));
// Go to Source Definition is vtsls': only in JavaScript and TypeScript files.
it.each([
["/p/a.ts", ["navigate.sourceDefinition"]],
["/p/a.py", []],
])("offers Find Usages immediately before Go To in the editor context menu (%s)", async (path, typescript) => {
ctrl = new EditorController(createMemoryBackend({ [path]: "one\n" }));
ctrl.start();
await ctrl.openFile("/p/a.ts", { focus: false });
await ctrl.openFile(path, { focus: false });
const slot = ctrl.activeSlot!;
const host = document.createElement("div");
document.body.appendChild(host);
@@ -646,6 +650,7 @@ describe("EditorController", () => {
"navigate.declaration",
"navigate.implementation",
"navigate.typeDeclaration",
...typescript,
"navigate.superMethod",
"navigate.relatedSymbol",
"navigate.gotoTest",
+3
Переглянути файл
@@ -1007,6 +1007,9 @@ export class EditorController implements SlotHost {
{ kind: "action", action: "navigate.declaration", label: "Declaration or Usages" },
{ kind: "action", action: "navigate.implementation", label: "Implementation(s)" },
{ kind: "action", action: "navigate.typeDeclaration", label: "Type Declaration" },
...(/^(java|type)script(react)?$/.test(slot.model.getMeta()?.language ?? "")
? [{ kind: "action" as const, action: "navigate.sourceDefinition", label: "Source Definition" }]
: []),
{ kind: "action", action: "navigate.superMethod", label: "Super Method" },
{ kind: "action", action: "navigate.relatedSymbol", label: "Related Symbol…" },
{ kind: "action", action: "navigate.gotoTest", label: "Test" },
+2
Переглянути файл
@@ -399,6 +399,8 @@ function PaneView({ paneId }: { paneId: string }) {
onCloseOthers={(id) => void ctrl.closeOthers(paneId, id)}
onTogglePin={(id) => ctrl.togglePin(paneId, id)}
closeOnShiftClick
// IDEA: a double click on the strip's empty part maximizes the editor, as on a tab.
onBlankDoubleClick={() => void executeAction("toolwindow.hideAll")}
onDoubleClick={(id) => {
// IDEA: a preview tab becomes a regular one; any other tab maximizes the editor.
if (pane.tabs.find((t) => t.id === id)?.preview) ctrl.keepTab(paneId, id);
+13
Переглянути файл
@@ -1,4 +1,5 @@
/** Actions of the LSP editor layer (ids from keymaps/intellij-macos.ts). */
import { gotoSourceDefinition, openProjectConfig, openTsServerLog, TYPESCRIPT_WHEN } from "./typescriptCommands";
import { generateActionIcon, isGenerateAction } from "./generate";
import type { EditorView } from "@codemirror/view";
import { executeAction, registerActions, type Action } from "@/platform/actions";
@@ -435,6 +436,18 @@ export function registerLspActions(): () => void {
editorAction("navigate.typeDeclaration", "Go to Type Declaration", "Navigate", (v) =>
gotoTargets(v, "typeDefinition"),
),
editorAction("navigate.sourceDefinition", "Go to Source Definition", "Navigate", gotoSourceDefinition, {
when: `${EDITOR_WHEN} && (${TYPESCRIPT_WHEN})`,
keywords: ["implementation", "javascript", "node_modules", "d.ts"],
}),
editorAction("typescript.goToProjectConfig", "Go to Project Configuration", "TypeScript", openProjectConfig, {
when: `${EDITOR_WHEN} && (${TYPESCRIPT_WHEN})`,
keywords: ["tsconfig", "jsconfig"],
}),
editorAction("typescript.openTsServerLog", "Open TS Server Log", "TypeScript", openTsServerLog, {
when: `${EDITOR_WHEN} && (${TYPESCRIPT_WHEN})`,
keywords: ["tsserver", "vtsls", "log"],
}),
editorAction("navigate.nextError", "Next Highlighted Error", "Navigate", (v) => gotoDiagnostic(v, 1)),
editorAction("navigate.prevError", "Previous Highlighted Error", "Navigate", (v) => gotoDiagnostic(v, -1)),
editorAction("code.showErrorDescription", "Error Description", "View", showErrorDescription, {
+2
Переглянути файл
@@ -1,3 +1,4 @@
import { MOVE_TO_FILE_COMMAND, moveToFile } from "./typescriptCommands";
import { serverCodeLenses } from "./serverCodeLens";
/**
* LSP-backed editor features: completion, diagnostics, hover / quick docs,
@@ -134,6 +135,7 @@ export function activate(): () => void {
registerOverlay({ id: "editor-lsp.extractInterfaceDialog", component: ExtractInterfaceDialog }),
registerOverlay({ id: "editor-lsp.memberChooser", component: MemberChooserDialog }),
registerClientCommand(JAVA_REFACTORING_COMMAND, runJavaRefactoringCommand),
registerClientCommand(MOVE_TO_FILE_COMMAND, moveToFile),
registerEditorBanner(outsideProjectBanner),
registerStatusItem({ id: "editor-lsp.usagesStatus", align: "left", priority: 10, component: UsagesStatus }),
// IDEA's Documentation tool window: right side, listed once F1 moved documentation there.
+51
Переглянути файл
@@ -0,0 +1,51 @@
import { describe, expect, it, vi } from "vitest";
import type { Command } from "@/bindings";
const lspMoveToFileTargets = vi.fn(async (_request: number, _doc: number, _command: Command) => ({
status: "ok" as const,
data: ["/p/src/util.ts", "/p/src/strings.ts", "/p/src/app.ts"],
}));
const lspExecuteCommand = vi.fn(async (_doc: number, _command: Command) => ({ status: "ok" as const, data: null }));
vi.mock("@/platform/ipc", async (orig) => {
const actual = await orig<typeof import("@/platform/ipc")>();
return { ...actual, isTauri: () => true, commands: { ...actual.commands, lspMoveToFileTargets, lspExecuteCommand } };
});
vi.mock("@/editor/api", async (orig) => ({
...(await orig<typeof import("@/editor/api")>()),
whenSynced: async () => {},
}));
const popups: { items: { label: string; run: () => void }[] }[] = [];
vi.mock("./popupStore", async (orig) => ({
...(await orig<typeof import("./popupStore")>()),
caretAnchor: () => ({ x: 0, y: 0 }),
openPopup: (p: (typeof popups)[number]) => popups.push(p),
}));
vi.mock("./lsp", async (orig) => ({
...(await orig<typeof import("./lsp")>()),
docOf: () => ({ doc: 7, path: "/p/src/util.ts", language: "typescript" }),
}));
const { moveToFile } = await import("./typescriptCommands");
describe("Move to File", () => {
it("offers tsserver's files but the source, then runs the command with the chosen one", async () => {
const action = { name: "Move to file", kind: "refactor.move.file" };
const range = { start: { line: 6, character: 16 }, end: { line: 6, character: 16 } };
const args = [action, "file:///p/src/util.ts", range];
const view = { state: { selection: { main: { head: 0 } } } } as never;
expect(await moveToFile(view, args)).toBe(true);
expect(lspMoveToFileTargets.mock.calls[0]![2].arguments).toEqual(args);
const items = popups[0]!.items;
expect(items.map((i) => i.label)).toEqual(["strings.ts", "app.ts", "Choose File…"]);
items[0]!.run();
await vi.waitFor(() => expect(lspExecuteCommand).toHaveBeenCalled());
expect(lspExecuteCommand.mock.calls[0]).toEqual([
7,
{
title: "Move to file",
command: "_typescript.moveToFileRefactoring",
arguments: [...args, "/p/src/strings.ts"],
},
]);
});
});
+162
Переглянути файл
@@ -0,0 +1,162 @@
/**
* vtsls' own TypeScript commands (`workspace/executeCommand`): Go to Source Definition, Go to
* Project Configuration, Open TS Server Log and the target file of Move to File. vtsls opens the
* configuration and the log itself (`window/showDocument`). typescript-language-server, TypeScript 7
* and the Vue / Astro servers have none of them.
*/
import type { EditorView } from "@codemirror/view";
import type { Command, Location } from "@/bindings";
import { whenSynced } from "@/editor/api";
import { tx } from "@/platform/i18n";
import { call, commands, isCancelled, nextRequestId } from "@/platform/ipc";
import { basename, dirname, relativePath, useProject } from "@/platform/project";
import { choosePath } from "@/platform/choosePath";
import { fileIconName } from "@/ui";
import { confirm } from "@/workbench/messages";
import { notifications } from "@/workbench/contributions";
import { showHint } from "./hint";
import { docOf, isUnavailable, lspRequest, reportLspError } from "./lsp";
import { locationItems, navigateTo } from "./navigation";
import { caretAnchor, openPopup } from "./popupStore";
import { offsetToPos } from "./positions";
export const TYPESCRIPT_LANGUAGES = ["typescript", "typescriptreact", "javascript", "javascriptreact"];
export const TYPESCRIPT_WHEN = TYPESCRIPT_LANGUAGES.map((id) => `editorLangId == ${id}`).join(" || ");
export const MOVE_TO_FILE_COMMAND = "_typescript.moveToFileRefactoring";
function report(view: EditorView, e: unknown) {
if (isUnavailable(e)) showHint(view, "This needs the vtsls TypeScript language server", { tone: "error" });
else reportLspError(view, e, true);
}
/** Navigate › Source Definition: the library's JavaScript instead of its `.d.ts`. */
export async function gotoSourceDefinition(view: EditorView) {
const ctx = docOf(view);
if (!ctx) return;
const head = view.state.selection.main.head;
let locs: Location[];
try {
await whenSynced(view);
const pos = offsetToPos(view.state.doc, head);
locs = await lspRequest(() => commands.lspSourceDefinition(nextRequestId(), ctx.doc, pos));
} catch (e) {
report(view, e);
return;
}
if (!locs.length) {
showHint(view, "Cannot find source definition", { tone: "error" });
return;
}
if (locs.length === 1) {
await navigateTo(locs[0]!);
return;
}
openPopup({
kind: "list",
anchor: caretAnchor(view, head),
title: tx("Choose Source Definition"),
items: await locationItems(locs),
});
}
/** Opens the `tsconfig.json` / `jsconfig.json` the file belongs to. */
export async function openProjectConfig(view: EditorView) {
const ctx = docOf(view);
if (!ctx) return;
try {
await lspRequest(() => commands.lspOpenTypescriptFile(ctx.doc, "projectConfig"));
} catch (e) {
report(view, e);
}
}
/** Opens the TS Server log, after offering to turn logging on (which restarts vtsls). */
export async function openTsServerLog(view: EditorView) {
const ctx = docOf(view);
if (!ctx) return;
const level = useProject.getState().settings?.languages?.typescript?.tsserverLog ?? "off";
if (level === "off") {
const ok = await confirm({
title: "Open TS Server Log",
message: tx("TS Server logging is off. Turn on verbose logging (typescript.tsserver.log) and restart vtsls?"),
ok: "Enable Logging",
});
if (!ok) return;
try {
const settings = await call(commands.settingsSet("global", "languages.typescript.tsserverLog", '"verbose"'));
useProject.setState({ settings });
} catch (e) {
reportLspError(view, e, true);
return;
}
notifications().notify({
level: "info",
title: "TS Server logging is on",
body: tx("vtsls restarts with logging. Run Open TS Server Log again to open the log."),
});
return;
}
try {
await lspRequest(() => commands.lspOpenTypescriptFile(ctx.doc, "serverLog"));
} catch (e) {
report(view, e);
}
}
/**
* vtsls' Move to File code action (`[action, uri, range]`): asks for the target file, tsserver's
* suggestions first, then runs the command with it appended. vtsls applies the moves and import
* updates as one workspace edit (one Undo).
*/
export async function moveToFile(view: EditorView, args: readonly unknown[]): Promise<boolean> {
const ctx = docOf(view);
if (!ctx) return false;
const command = (target?: string): Command => ({
title: "Move to file",
command: MOVE_TO_FILE_COMMAND,
// The arguments are JSON values (the bindings type them as strings).
arguments: (target === undefined ? args : [...args, target]) as string[],
});
let files: string[];
try {
await whenSynced(view);
files = await lspRequest(() => commands.lspMoveToFileTargets(nextRequestId(), ctx.doc, command()));
} catch (e) {
report(view, e);
return true;
}
const move = async (target: string) => {
try {
await whenSynced(view);
await lspRequest(() => commands.lspExecuteCommand(ctx.doc, command(target)));
} catch (e) {
if (!isCancelled(e)) report(view, e);
}
};
const root = useProject.getState().project?.root ?? "";
openPopup({
kind: "list",
anchor: caretAnchor(view, view.state.selection.main.head),
title: tx("Move to File"),
items: [
...files
.filter((f) => f !== ctx.path)
.map((f, i) => ({
id: `${i}`,
label: basename(f),
detail: relativePath(root, f),
icon: fileIconName(basename(f), f),
run: () => void move(f),
})),
{
id: "choose",
label: tx("Choose File…"),
run: () =>
void choosePath({ directory: false, title: tx("Move to File"), defaultPath: dirname(ctx.path) }).then((f) => {
if (f && f !== ctx.path) void move(f);
}),
},
],
});
return true;
}
+16 -5
Переглянути файл
@@ -162,7 +162,7 @@ describe("Agents selection", () => {
vi.mocked(openTask).mockClear();
context("two");
expect(selectedTasks()).toEqual(["one", "two", "three"]);
expect(screen.getByRole("menuitem", { name: "Delete (3)…" })).toBeTruthy();
expect(screen.getByRole("menuitem", { name: /^Delete \(3\)…/ })).toBeTruthy();
expect(openTask).not.toHaveBeenCalled();
});
@@ -298,9 +298,20 @@ describe("Agents docked view", () => {
setup();
expect(screen.queryByRole("button", { name: "Open in Editor" })).toBeNull();
select("two");
expect(openTask).toHaveBeenCalledWith("two");
expect(openTask).toHaveBeenCalledWith("two", { focus: false });
expect(dockTask).not.toHaveBeenCalled();
});
it("keeps focus in the list when a click opens a task, so Delete deletes that task", async () => {
setup();
const tree = screen.getByRole("tree", { name: "Agent tasks" });
tree.focus();
select("two");
expect(openTask).toHaveBeenCalledWith("two", { focus: false });
// The shortcut runs the action without an argument: it takes the list's selection.
await taskActions.find((a) => a.id === "agents.deleteTasks")!.run({ ctx: {}, arg: undefined });
await waitFor(() => expect(deleteTask).toHaveBeenCalledExactlyOnceWith("two", false));
});
});
describe("Agents bulk actions", () => {
@@ -311,7 +322,7 @@ describe("Agents bulk actions", () => {
select("one");
select("three", { shiftKey: true });
context("two");
fireEvent.click(screen.getByRole("menuitem", { name: "Delete (3)…" }));
fireEvent.click(screen.getByRole("menuitem", { name: /^Delete \(3\)…/ }));
await waitFor(() => expect(deleteTask).toHaveBeenCalledTimes(3));
expect(confirmChecked).toHaveBeenCalledTimes(1);
expect(confirmChecked).toHaveBeenCalledWith(
@@ -329,7 +340,7 @@ describe("Agents bulk actions", () => {
select("one");
select("two", { shiftKey: true });
context("four");
fireEvent.click(screen.getByRole("menuitem", { name: "Delete…" }));
fireEvent.click(screen.getByRole("menuitem", { name: /^Delete…/ }));
await waitFor(() => expect(deleteTask).toHaveBeenCalledExactlyOnceWith("four", false));
});
@@ -784,6 +795,6 @@ describe("Agents pinned and grouped tasks", () => {
expect(openTask).not.toHaveBeenCalled();
fireEvent.pointerUp(window, { button: 0, clientX: 10, clientY: 104 });
fireEvent.click(sourceSpan, { button: 0 });
expect(openTask).toHaveBeenCalledWith("two");
expect(openTask).toHaveBeenCalledWith("two", { focus: false });
});
});
+44 -10
Переглянути файл
@@ -52,8 +52,8 @@ import {
openHome,
pinTasks,
refreshExternalSessions,
reorderTask,
reorderTaskGroup,
reorderTasks,
showImportSessions,
useAgents,
} from "./store";
@@ -238,6 +238,8 @@ export function AgentsView() {
searchingRef.current = matches !== null;
}, [matches]);
const cancelDragRef = useRef<(() => void) | undefined>(undefined);
/** Every task the current drag carries, in list order; set when it starts. */
const draggedIdsRef = useRef<string[]>([]);
const [tasksEl, setTasksEl] = useState<HTMLDivElement | null>(null);
const [dropIndicator, setDropIndicator] = useState<DropIndicator | null>(null);
useEffect(() => {
@@ -266,11 +268,18 @@ export function AgentsView() {
const { tasks, organize } = useAgents.getState();
const source = tasks.get(data.payload);
if (!source) return null;
// Dragging a selected task moves the whole selection.
const ids = draggedIdsRef.current.includes(source.id) ? draggedIdsRef.current : [source.id];
const sources = ids.flatMap((id) => {
const task = tasks.get(id);
return task ? [task] : [];
});
const sourceIds = sources.map((t) => t.id);
if (targetKey === PINNED_SECTION) {
return {
indicator: { kind: "section", key: targetKey } as DropIndicator,
apply: () => pinTasks([source.id], true),
apply: () => pinTasks(sourceIds, true),
};
}
if (targetKey.startsWith("ug:")) {
@@ -278,23 +287,33 @@ export function AgentsView() {
if (!organize.groups.some((g) => g.id === groupId)) return null;
return {
indicator: { kind: "section", key: targetKey } as DropIndicator,
apply: () => moveTasksToGroup([source.id], groupId),
apply: () => moveTasksToGroup(sourceIds, groupId),
};
}
if (targetKey.startsWith("g:")) {
if (sectionOfTask(source, organize) === targetKey) return null;
if (statusSection(taskGroupStatus(source)) !== targetKey) return null;
// A status group takes the tasks of its status that are elsewhere.
const movable = sources.filter(
(t) => sectionOfTask(t, organize) !== targetKey && statusSection(taskGroupStatus(t)) === targetKey,
);
if (!movable.length) return null;
return {
indicator: { kind: "section", key: targetKey } as DropIndicator,
apply: () => moveTasksToStatusGroup([source.id]),
apply: () => moveTasksToStatusGroup(movable.map((t) => t.id)),
};
}
if (searchingRef.current) return null;
const target = tasks.get(targetKey);
if (!target || !canReorderTask(source, target, organize)) return null;
if (!target || sourceIds.includes(target.id)) return null;
const movable = sources.filter((t) => canReorderTask(t, target, organize));
if (!movable.length) return null;
return {
indicator: { kind: "row", key: targetKey, position } as DropIndicator,
apply: () => reorderTask(source.id, target.id, position),
apply: () =>
reorderTasks(
movable.map((t) => t.id),
target.id,
position,
),
};
};
const update = () => {
@@ -383,11 +402,26 @@ export function AgentsView() {
setHistoryOpen(false);
void executeAction("agents.openTask", task);
};
// A click or arrow key in the list opens the session but keeps focus in the list, so its
// shortcuts (Delete) still act on the selection; Enter and double-click focus the session.
const previewTask = (task: string) => {
if (inline) showTask(task);
else void executeAction("agents.openTask", { task, focus: false });
};
const dockedTitle = docked ? (tasks.get(docked)?.title ?? docked) : null;
const dragTask = (e: ReactPointerEvent<HTMLElement>, task: string, source: HTMLElement = e.currentTarget) => {
suppressClickRef.current = false;
if (e.button !== 0 || e.ctrlKey || e.metaKey || e.shiftKey) return;
cancelDragRef.current?.();
// A selected row drags the whole selection, in list order.
const current = selectedRef.current;
draggedIdsRef.current =
current.size > 1 && current.has(task)
? roots
.flatMap((n) => (n.kind === "group" ? n.group.tasks : n.kind === "task" ? [n.task] : n.tasks))
.map((t) => t.id)
.filter((id, i, all) => current.has(id) && all.indexOf(id) === i)
: [task];
cancelDragRef.current = startPointerDrag(
e,
source,
@@ -478,7 +512,7 @@ export function AgentsView() {
if (e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey) return;
if ((e.target as Element).closest("button, input, textarea, [data-tree-toggle]")) return;
const key = (e.target as Element).closest<HTMLElement>("[data-tree-key]")?.dataset.treeKey;
if (key && tasks.has(key)) showTask(key);
if (key && tasks.has(key)) previewTask(key);
}}
onFocus={() => setFocusedTaskList(() => [...selectedRef.current])}
onBlur={(e) => {
@@ -554,7 +588,7 @@ export function AgentsView() {
lead?.kind === "task" &&
sel.has(lead.task.id)
)
showTask(lead.task.id);
previewTask(lead.task.id);
}}
onActivate={(n) => n.kind === "task" && showTask(n.task.id)}
onContextMenu={(n, sel, e) => {
+27 -8
Переглянути файл
@@ -57,6 +57,7 @@ import { withQuote } from "./conversation";
import {
EMPTY_ORGANIZE,
PINNED_SECTION,
canReorderTask,
compactOrder,
customSection,
loadOrganize,
@@ -1184,7 +1185,8 @@ export function useAgentCommands(
return extra.length > 0 ? [...filtered, ...extra] : filtered;
}
export function openTask(task: string) {
/** Opens the task's session; `focus: false` opens it in the editor without taking focus (a click in the task list). */
export function openTask(task: string, options: { focus?: boolean } = {}) {
if (routeToWindow(task)) return;
forgetClosed(task);
if (useAgents.getState().sessionLocation === "toolWindow") {
@@ -1192,13 +1194,13 @@ export function openTask(task: string) {
return;
}
useAgents.setState({ lastTask: task, homeOpen: false, lastComposer: task });
openTaskInEditor(task);
openTaskInEditor(task, options.focus ?? true);
}
function openTaskInEditor(task: string) {
function openTaskInEditor(task: string, focus = true) {
// The title rides along so a restored tab has it before the tasks load.
const title = useAgents.getState().tasks.get(task)?.title;
void editorService().openInput({ kind: SESSION_KIND, key: sessionKey(task), data: { task, title } }, { focus: true });
void editorService().openInput({ kind: SESSION_KIND, key: sessionKey(task), data: { task, title } }, { focus });
}
function showDockedTask(task: string) {
@@ -2189,10 +2191,27 @@ export function moveTasksToStatusGroup(tasks: readonly string[]) {
});
}
/** Places `sourceId` before or after `targetId` (moving it into the target's section when needed). */
export function reorderTask(sourceId: string, targetId: string, position: "before" | "after") {
const tasks = useAgents.getState().tasks.values();
changeOrganize((organize) => reorderTaskInOrganize(organize, tasks, sourceId, targetId, position));
/**
* Places `sourceIds` (in list order) before or after `targetId`, keeping their relative order.
* Tasks that can't go beside the target (another status than its status group) stay where they are.
*/
export function reorderTasks(sourceIds: readonly string[], targetId: string, position: "before" | "after") {
const tasks = [...useAgents.getState().tasks.values()];
changeOrganize((organize) => {
let next = organize;
// Before: each goes right before the target. After: each goes after the one placed last.
let anchor = targetId;
const byId = new Map(tasks.map((t) => [t.id, t]));
for (const id of sourceIds) {
if (id === targetId) continue;
const source = byId.get(id);
const target = byId.get(anchor);
if (!source || !target || !canReorderTask(source, target, next)) continue;
next = reorderTaskInOrganize(next, tasks, id, anchor, position);
if (position === "after") anchor = id;
}
return next;
});
}
/** Reorders a custom group before or after another custom group. */
+7
Переглянути файл
@@ -285,6 +285,11 @@ export const taskActions: Action[] = [
hidden: true,
run: ({ arg }) => {
if (typeof arg === "string") openTask(arg);
// `{ task, focus: false }`: a click in the task list opens the session and keeps focus there.
else if (arg && typeof arg === "object" && typeof (arg as { task?: unknown }).task === "string") {
const { task, focus } = arg as { task: string; focus?: unknown };
openTask(task, { focus: focus !== false });
}
},
},
{
@@ -396,6 +401,8 @@ export const taskActions: Action[] = [
title: "Delete Agent Tasks",
category: "Agents",
hidden: true,
// Without an argument the shortcut deletes the task list's selection.
keyWhen: "agentTaskListFocus",
run: ({ arg }) => confirmDelete(resolveTasks(arg)),
},
{
+59 -3
Переглянути файл
@@ -7,19 +7,28 @@ import listStyles from "@/ui/List.module.css";
const listIdes = vi.fn();
const importJetBrainsSettings = vi.fn();
const notify = vi.fn();
const importRecent = vi.fn();
const loadRecent = vi.fn();
vi.mock("@/platform/ipc", async (original) => ({
...(await original<typeof import("@/platform/ipc")>()),
call: <T,>(result: Promise<T>) => result,
commands: { settingsListJetbrainsIdes: () => listIdes() },
commands: {
settingsListJetbrainsIdes: () => listIdes(),
recentImportJetbrains: (path: string, dryRun: boolean) => importRecent(path, dryRun),
},
}));
vi.mock("../jetbrainsSettings", () => ({ importJetBrainsSettings: (path: string) => importJetBrainsSettings(path) }));
vi.mock("../jetbrainsSettings", async (original) => ({
...(await original<typeof import("../jetbrainsSettings")>()),
importJetBrainsSettings: (path: string) => importJetBrainsSettings(path),
}));
vi.mock("@/features/welcome/recent", () => ({ loadRecent: () => loadRecent() }));
vi.mock("@/workbench/contributions", async (original) => ({
...(await original<typeof import("@/workbench/contributions")>()),
notifications: () => ({ notify }),
}));
const { importFromJetBrainsIde } = await import("../projectActions");
const { importFromJetBrainsIde, importJetBrainsRecentProjects } = await import("../projectActions");
const idea = {
ide: "IntelliJ IDEA 2025.2",
@@ -110,3 +119,50 @@ describe("Manage IDE Settings › Import Settings from JetBrains IDE…", () =>
expect(importJetBrainsSettings).toHaveBeenCalledExactlyOnceWith(ides[59]!.path);
});
});
describe("Import Recent Projects from JetBrains IDE…", () => {
async function pickFirst(run: () => Promise<void>) {
let done!: Promise<void>;
await act(async () => {
done = run();
});
const list = screen.getByRole("listbox", { name: "Import Recent Projects from JetBrains IDE" });
await act(async () => {
fireEvent.keyDown(list, { key: "Enter" });
await done;
});
}
it("merges the chosen IDE's recent projects, refreshes the list and says what it did", async () => {
listIdes.mockResolvedValue([idea, studio]);
importRecent.mockResolvedValue({ imported: 3, missing: 2, groups: 1 });
await pickFirst(importJetBrainsRecentProjects);
expect(importRecent).toHaveBeenCalledExactlyOnceWith(idea.path, false);
expect(loadRecent).toHaveBeenCalled();
expect(notify).toHaveBeenCalledWith(
expect.objectContaining({
level: "info",
title: "Recent projects imported",
body: "Imported 3 recent projects and 1 project groups, skipped 2 whose folder is missing.",
}),
);
});
it("warns when there is nothing new", async () => {
listIdes.mockResolvedValue([idea]);
importRecent.mockResolvedValue({ imported: 0, missing: 1, groups: 0 });
await pickFirst(importJetBrainsRecentProjects);
expect(notify).toHaveBeenCalledWith(
expect.objectContaining({ level: "warning", title: "No new recent projects to import" }),
);
});
it("reports a failure", async () => {
listIdes.mockResolvedValue([idea]);
importRecent.mockRejectedValue(new Error("denied"));
await pickFirst(importJetBrainsRecentProjects);
expect(notify).toHaveBeenCalledWith(
expect.objectContaining({ level: "error", title: "Cannot import recent projects" }),
);
});
});
+30
Переглянути файл
@@ -6,6 +6,8 @@ const set = vi.fn();
const notify = vi.fn();
const execute = vi.fn();
const marketCall = vi.fn();
const importRecent = vi.fn();
const loadRecent = vi.fn();
const market = [
{ id: "ruyimg.codeglance-pro", name: "CodeGlance Pro", installed: null, compatible: true },
{ id: "solhovoy.grep-console", name: "Grep Console", installed: null, compatible: true },
@@ -22,9 +24,11 @@ vi.mock("@/platform/ipc", async (original) => {
settingsGetGlobal: async () => ({ editor }),
settingsSet: (scope: string, key: string, value: string) => set(scope, key, value),
pluginMarket: () => marketCall(),
recentImportJetbrains: (path: string, dryRun: boolean) => importRecent(path, dryRun),
},
};
});
vi.mock("@/features/welcome/recent", () => ({ loadRecent: () => loadRecent() }));
vi.mock("@/platform/actions", async (original) => ({
...(await original<typeof import("@/platform/actions")>()),
executeAction: (id: string, arg?: unknown) => execute(id, arg),
@@ -58,6 +62,7 @@ beforeEach(() => {
});
set.mockResolvedValue({ status: "ok", data: { editor } });
marketCall.mockResolvedValue({ status: "ok", data: market });
importRecent.mockResolvedValue({ status: "ok", data: { imported: 0, missing: 0, groups: 0 } });
// jsdom has no canvas: the import falls back to the font size for the line height.
vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockReturnValue(null);
});
@@ -150,3 +155,28 @@ it("says so when the plugin marketplace cannot be reached, without blaming the p
expect(screen.getByText(/Plugins without a counterpart/)).not.toHaveTextContent("CodeGlancePro");
await act(async () => fireEvent.click(screen.getByRole("button", { name: "Cancel" })));
});
it("lists an IDE's recent projects and merges them on Import", async () => {
read.mockResolvedValue({ status: "ok", data: { entries: [], files: {} } });
importRecent.mockResolvedValue({ status: "ok", data: { imported: 4, missing: 1, groups: 2 } });
render(<MessagesHost />);
let done!: Promise<void>;
await act(async () => {
done = importJetBrainsSettings("/settings/IDE");
});
expect(importRecent).toHaveBeenCalledExactlyOnceWith("/settings/IDE", true);
expect(screen.getByText("Recent projects")).toBeInTheDocument();
expect(screen.getByText("4 new, 2 new project groups, 1 skipped (folder missing)")).toBeInTheDocument();
await act(async () => {
fireEvent.click(screen.getByRole("button", { name: "Import" }));
await done;
});
expect(importRecent).toHaveBeenLastCalledWith("/settings/IDE", false);
expect(loadRecent).toHaveBeenCalled();
expect(notify).toHaveBeenCalledWith(
expect.objectContaining({
title: "Settings imported",
body: "Imported 4 recent projects and 2 project groups, skipped 1 whose folder is missing.",
}),
);
});
+1
Переглянути файл
@@ -27,6 +27,7 @@ vi.mock("@/platform/ipc", async (original) => {
settingsGetGlobal: async () => ({ editor }),
settingsSet: (scope: string, key: string, value: string) => set(scope, key, value),
languages: async () => [python],
recentImportJetbrains: async () => ({ status: "ok", data: { imported: 0, missing: 0, groups: 0 } }),
},
};
});
+32 -3
Переглянути файл
@@ -6,7 +6,13 @@
* out). The rest is listed as not imported.
*/
import { Fragment, useEffect, useState } from "react";
import type { CustomKeymap, JetBrainsSettings, LanguageCodeStyle, LanguageInfo } from "@/bindings";
import type {
CustomKeymap,
JetBrainsRecentImport,
JetBrainsSettings,
LanguageCodeStyle,
LanguageInfo,
} from "@/bindings";
import { actionToggled, executeAction, getAction } from "@/platform/actions";
import { customSchemes } from "@/platform/colorScheme";
import { createFontProbeCanvas, fontsLoaded, monoFontFamily } from "@/platform/fonts";
@@ -18,6 +24,7 @@ import { guessOs } from "@/platform/platformInfo";
import { useProject } from "@/platform/project";
import { notifications } from "@/workbench/contributions";
import { ask } from "@/workbench/messages";
import { loadRecent } from "@/features/welcome/recent";
import { parseJetBrainsTemplates, type JetBrainsTemplateImport } from "@/features/templates/live/jetbrains";
import { saveImportedTemplates } from "@/features/templates/live/store";
import styles from "./app.module.css";
@@ -480,10 +487,25 @@ function Summary({ plan, pending }: { plan: JetBrainsImportPlan; pending?: Promi
);
}
/** What importing a JetBrains IDE's recent projects did. */
export function recentImportSummary({ imported, groups, missing }: JetBrainsRecentImport): string {
return tx`Imported ${imported} recent projects and ${groups} project groups, skipped ${missing} whose folder is missing.`;
}
/** Reads `path`, asks, then writes the mapped settings to the global layer. */
export async function importJetBrainsSettings(path: string) {
const bundle = await call(commands.settingsReadJetbrains(path));
const plan = await planJetBrainsImport(bundle, await commands.settingsGetGlobal());
// An IDE's settings folder (not an exported archive) has its recent projects.
const recent = await call(commands.recentImportJetbrains(path, true)).catch(() => null);
const hasRecent = !!recent && (recent.imported > 0 || recent.groups > 0);
if (hasRecent) {
const { imported, groups, missing } = recent;
plan.rows.push({
label: tx("Recent projects"),
value: tx`${imported} new, ${groups} new project groups, ${missing} skipped (folder missing)`,
});
}
const plugins = plan.plugins;
// Looked up while the confirmation is open; it shows the answer when it comes.
const pending = plugins?.candidates.length
@@ -491,7 +513,7 @@ export async function importJetBrainsSettings(path: string) {
.then((market) => suggestPlugins(plugins.candidates, market))
.catch(() => null)
: undefined;
if (!plan.writes.length && !plan.liveTemplates?.templates.length && !pending && !plugins?.vim) {
if (!plan.writes.length && !plan.liveTemplates?.templates.length && !pending && !plugins?.vim && !hasRecent) {
const details = [...plan.invalid, ...(plan.liveTemplates?.skipped ?? [])].join(", ");
notifications().notify({
level: "warning",
@@ -515,7 +537,14 @@ export async function importJetBrainsSettings(path: string) {
if (plan.liveTemplates?.templates.length) saveImportedTemplates(plan.liveTemplates.templates);
useProject.setState({ settings });
if (plugins?.vim && !actionToggled(getAction("vim.toggle"))) void executeAction("vim.toggle");
notifications().notify({ level: "info", title: "Settings imported", body: path, key: "app.settingsImport" });
const imported = hasRecent ? await call(commands.recentImportJetbrains(path, false)).catch(() => null) : null;
if (imported) void loadRecent();
notifications().notify({
level: "info",
title: "Settings imported",
body: imported ? recentImportSummary(imported) : path,
key: "app.settingsImport",
});
if (useProject.getState().project && plan.inspectionProfiles?.length)
offerInspectionProfiles(plan.inspectionProfiles);
void pending?.then((s) => s?.install.length && offerPlugins(s.install));
+53 -16
Переглянути файл
@@ -9,7 +9,8 @@ import { call, commands, isTauri } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { notifications, registerEditorBanner } from "@/workbench/contributions";
import { pickItems, promptInput } from "@/workbench/inputDialogs";
import { importJetBrainsSettings } from "./jetbrainsSettings";
import { loadRecent } from "@/features/welcome/recent";
import { importJetBrainsSettings, recentImportSummary } from "./jetbrainsSettings";
import { showNewProject } from "./NewProject";
import { tx } from "@/platform/i18n";
@@ -114,24 +115,30 @@ async function importSettings() {
}
}
/** The settings folder of the JetBrains IDE the user picks; undefined when none is installed or the pick is cancelled. */
async function pickJetBrainsIde(title: string): Promise<string | undefined> {
const ides = await call(commands.settingsListJetbrainsIdes());
if (!ides.length) {
notifications().notify({
level: "warning",
title: "No JetBrains IDE settings were found on this computer",
key: "app.settingsImport",
});
return;
}
const picked = await pickItems({
title,
items: ides.map((ide) => ({ key: ide.path, label: ide.ide })),
multiple: false,
});
return picked?.[0];
}
/** Import Settings from a JetBrains IDE installed on this computer, without exporting a `settings.zip` first. */
export async function importFromJetBrainsIde() {
try {
const ides = await call(commands.settingsListJetbrainsIdes());
if (!ides.length) {
notifications().notify({
level: "warning",
title: "No JetBrains IDE settings were found on this computer",
key: "app.settingsImport",
});
return;
}
const picked = await pickItems({
title: tx("Import Settings from JetBrains IDE"),
items: ides.map((ide) => ({ key: ide.path, label: ide.ide })),
multiple: false,
});
if (picked?.[0]) await importJetBrainsSettings(picked[0]);
const path = await pickJetBrainsIde(tx("Import Settings from JetBrains IDE"));
if (path) await importJetBrainsSettings(path);
} catch (e) {
notifications().notify({
level: "error",
@@ -142,6 +149,29 @@ export async function importFromJetBrainsIde() {
}
}
/** Adds the recent projects and project groups of a JetBrains IDE to the Welcome screen's. */
export async function importJetBrainsRecentProjects() {
try {
const path = await pickJetBrainsIde(tx("Import Recent Projects from JetBrains IDE"));
if (!path) return;
const result = await call(commands.recentImportJetbrains(path, false));
void loadRecent();
notifications().notify({
level: result.imported || result.groups ? "info" : "warning",
title: result.imported || result.groups ? "Recent projects imported" : "No new recent projects to import",
body: recentImportSummary(result),
key: "app.recentImport",
});
} catch (e) {
notifications().notify({
level: "error",
title: "Cannot import recent projects",
body: errorText(e),
key: "app.recentImport",
});
}
}
async function renameProject() {
const project = useProject.getState().project;
if (!project) return;
@@ -219,6 +249,13 @@ export function projectActions(): Action[] {
keywords: ["intellij", "pycharm", "webstorm", "android studio", "migrate", "manage ide settings"],
run: desktop(importFromJetBrainsIde),
},
{
id: "file.importJetBrainsRecentProjects",
title: "Import Recent Projects from JetBrains IDE…",
category: "File",
keywords: ["intellij", "pycharm", "webstorm", "android studio", "migrate", "project groups"],
run: desktop(importJetBrainsRecentProjects),
},
{
id: "file.togglePowerSave",
title: "Power Save Mode",
+11
Переглянути файл
@@ -70,9 +70,20 @@
.body {
display: flex;
flex-direction: column;
height: var(--usages-height);
min-height: var(--usages-min-height);
padding: 2px 0;
box-sizing: content-box;
}
/* Resized: the list takes the height the preview leaves. */
.popup[data-resized] .focus {
flex: 1 1 0;
}
.popup[data-resized] .body {
flex: 1 1 0;
height: auto;
min-height: var(--usages-min-height);
}
.body > * {
flex: 1;
}
+44 -3
Переглянути файл
@@ -3,7 +3,7 @@
* filters), an optional code preview and "Open in Find Window", which moves
* the found usages to the Find Usages tool window.
*/
import { useEffect, useMemo, useRef, useState, type KeyboardEvent } from "react";
import { useEffect, useMemo, useRef, useState, type CSSProperties, type KeyboardEvent } from "react";
import { create } from "zustand";
import clsx from "clsx";
import { EditorState, StateEffect, StateField } from "@codemirror/state";
@@ -55,6 +55,30 @@ export function setUsagesPopupPreview(preview: boolean) {
}
}
const SIZE_KEY = "openidea.usages.popupSize.v1";
const MIN_WIDTH = 360;
const MIN_HEIGHT = 160;
/** The size the popup was last resized to, if any (IDEA remembers Show Usages' size). */
function loadUsagesPopupSize(): { w: number; h: number } | null {
try {
const saved = JSON.parse(localStorage.getItem(SIZE_KEY) ?? "null") as { w?: unknown; h?: unknown } | null;
return typeof saved?.w === "number" && typeof saved.h === "number" && Number.isFinite(saved.w + saved.h)
? { w: Math.max(MIN_WIDTH, saved.w), h: Math.max(MIN_HEIGHT, saved.h) }
: null;
} catch {
return null;
}
}
function saveUsagesPopupSize(size: { w: number; h: number }) {
try {
localStorage.setItem(SIZE_KEY, JSON.stringify(size));
} catch {
// storage unavailable: the size lasts while the popup is open
}
}
/** Usages whose file name or line text contains the typed text (case-insensitive). */
export function filterUsages(items: readonly Usage[], filter: string): Usage[] {
const q = filter.trim().toLowerCase();
@@ -102,6 +126,7 @@ function UsagesPopupInner() {
[all, filter, accessOptions],
);
const [active, setActive] = useState(0);
const [initialSize] = useState(loadUsagesPopupSize);
const current = Math.min(active, items.length - 1);
const total = usageCount(groups);
const rowCount = Math.max(1, Math.min(14, items.length));
@@ -157,7 +182,18 @@ function UsagesPopupInner() {
const keys = shortcutLabel("find.usages");
return (
<Popup open anchor={anchor} onClose={close} aria-label="Usages" className={styles.popup}>
<Popup
open
anchor={anchor}
onClose={close}
aria-label="Usages"
className={styles.popup}
resizable="both"
minWidth={MIN_WIDTH}
minHeight={MIN_HEIGHT}
initialSize={initialSize}
onResized={saveUsagesPopupSize}
>
<div
className={styles.focus}
tabIndex={0}
@@ -221,7 +257,12 @@ function UsagesPopupInner() {
)}
<div
className={styles.body}
style={{ height: rowCount * rowHeight, minHeight: `min(${Math.min(rowCount, 3) * rowHeight}px, 18vh)` }}
style={
{
"--usages-height": `${rowCount * rowHeight}px`,
"--usages-min-height": `min(${Math.min(rowCount, 3) * rowHeight}px, 18vh)`,
} as CSSProperties
}
>
<List
items={items}
+15
Переглянути файл
@@ -109,6 +109,21 @@ describe("Show Usages popup", () => {
});
});
it("is resizable and opens at the size it was left at", () => {
localStorage.setItem("openidea.usages.popupSize.v1", JSON.stringify({ w: 900, h: 120 }));
try {
open();
expect(screen.getByRole("separator", { name: "Resize" })).toBeInTheDocument();
const popup = screen.getByRole("dialog", { name: "Usages" });
expect(popup).toHaveAttribute("data-resized");
// Clamped to the minimum height.
expect(popup.style.width).toBe("900px");
expect(popup.style.height).toBe("160px");
} finally {
localStorage.removeItem("openidea.usages.popupSize.v1");
}
});
it("the preview pane toggles", () => {
open();
expect(screen.queryByRole("region", { name: "Preview" })).toBeNull();
+2
Переглянути файл
@@ -61,6 +61,8 @@ describe("coverageSupports", () => {
expect(coverageSupports(cfg("bundle", ["exec", "rspec"], { isTest: true }))).toBe(true);
expect(coverageSupports(cfg("bundle", ["exec", "rake", "db:migrate"]))).toBe(false);
expect(coverageSupports(cfg("make", ["test"]))).toBe(false);
expect(coverageSupports(cfg("xcodebuild", ["test", "-scheme", "App"], { kind: "xcode-test" }))).toBe(true);
expect(coverageSupports(cfg("xcodebuild", ["build", "-scheme", "App"], { kind: "xcode" }))).toBe(false);
});
});
+1
Переглянути файл
@@ -19,6 +19,7 @@ const runsJvmTests = (args: readonly string[]) =>
* Node.js programs, Python and Ruby (scripts, rspec, test rake tasks).
*/
export function coverageSupports(config: Pick<RunConfig, "command" | "args" | "kind" | "isTest">): boolean {
if (config.kind === "xcode-test") return true;
const program = programName(config.command);
const args = config.args;
switch (program) {
+35
Переглянути файл
@@ -1,6 +1,8 @@
import { describe, expect, it } from "vitest";
import { EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { ensureSyntaxTree } from "@codemirror/language";
import { java } from "@codemirror/lang-java";
import { expressionAt } from "../editor/valueTooltip";
/** The expression around the `|` in `line`. */
@@ -35,3 +37,36 @@ describe("expression at the mouse for Quick Evaluate (#4772)", () => {
expect(at("a.getB().c|()", false)).toBe("c");
});
});
/** The expression around the `|` in a Java statement. */
function inJava(statement: string, calls: boolean) {
const prefix = "class A { void f() { ";
const doc = `${prefix}${statement} } }`;
const pos = doc.indexOf("|");
const view = new EditorView({ state: EditorState.create({ doc: doc.replace("|", ""), extensions: java() }) });
ensureSyntaxTree(view.state, view.state.doc.length, 1000);
const text = expressionAt(view, pos, { calls })?.text ?? null;
view.destroy();
return text;
}
describe("expression of an operator (#7000)", () => {
it("takes the expression the operator belongs to, as IDEA does", () => {
for (const calls of [false, true]) {
expect(inJava("if (a > 1 |&& !flag) {}", calls)).toBe("a > 1 && !flag");
expect(inJava("if (a |> 1 && !flag) {}", calls)).toBe("a > 1");
expect(inJava("if (a > 1 && |!flag) {}", calls)).toBe("!flag");
expect(inJava("x = c |? 1 : 2;", calls)).toBe("c ? 1 : 2");
// An identifier is still just the identifier.
expect(inJava("if (|a > 1 && !flag) {}", calls)).toBe("a");
}
});
it("leaves calls, increments and assignments to Quick Evaluate", () => {
expect(inJava("if (s.length() |> 0) {}", false)).toBeNull();
expect(inJava("if (s.length() |> 0) {}", true)).toBe("s.length() > 0");
expect(inJava("if (a |!= b) {}", false)).toBe("a != b");
expect(inJava("x = a |+ i++;", false)).toBeNull();
expect(inJava("x |= 1;", true)).toBeNull();
});
});
+24 -2
Переглянути файл
@@ -3,6 +3,7 @@
* while suspended, hovering an expression (or the selection under the mouse)
* evaluates it in the selected frame.
*/
import { syntaxTree } from "@codemirror/language";
import type { EditorState, Extension } from "@codemirror/state";
import type { DebugSessionId, Variable } from "@/bindings";
import { closeHoverTooltips, hoverTooltip, ViewPlugin, type EditorView, type ViewUpdate } from "@codemirror/view";
@@ -49,10 +50,29 @@ function openOf(t: string, i: number): number {
return -1;
}
/** Syntax nodes of an operator's expression (Lezer's Java, JS, Python, C++, Rust, Go grammars). */
const OPERATOR_EXPRESSION = /^(Binary|Unary|Ternary|Conditional)Expr(ession)?$/;
/** A call, an increment or an assignment: a plain hover doesn't evaluate those. */
const SIDE_EFFECTS = /[\p{L}\p{N}_$)\]]\s*\(|\+\+|--|(^|[^=!<>])=(?!=)/u;
/**
* As in IDEA, on an operator the expression it belongs to: `&&` gives `a > 1 && !flag`, `>` gives
* `a > 1`, `!` gives `!flag`. Without `calls` (a hover), not when evaluating it could change state.
*/
function operatorExpressionAt(state: EditorState, pos: number, calls: boolean) {
const token = syntaxTree(state).resolveInner(pos, 1);
const parent = token.parent;
if (token.firstChild || !parent || !OPERATOR_EXPRESSION.test(parent.name)) return null;
const text = state.sliceDoc(parent.from, parent.to);
if (text.includes("\n") || (!calls && SIDE_EFFECTS.test(text))) return null;
return { from: parent.from, to: parent.to, text };
}
/**
* Identifier (with `a.b.c` member access) around `pos`, or the selection containing it. With
* `calls`, as for Quick Evaluate: member chains through calls and indexing (`a.getB().c`,
* `items[i].name`) and the call of the identifier itself (`o.getX()`, `f(a, b)`).
* `items[i].name`) and the call of the identifier itself (`o.getX()`, `f(a, b)`). On an operator,
* the expression it belongs to.
*/
export function expressionAt(
view: EditorView,
@@ -69,7 +89,9 @@ export function expressionAt(
const t = line.text;
let start = pos - line.from;
let end = start;
if (!IDENT.test(t[end] ?? "") && !IDENT.test(t[start - 1] ?? "")) return null;
if (!IDENT.test(t[end] ?? "") && !IDENT.test(t[start - 1] ?? "")) {
return /\s/.test(t[end] ?? " ") ? null : operatorExpressionAt(state, pos, calls);
}
while (end < t.length && IDENT.test(t[end]!)) end++;
for (;;) {
while (start > 0 && IDENT.test(t[start - 1]!)) start--;
+29 -2
Переглянути файл
@@ -1,9 +1,11 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import type * as TauriCore from "@tauri-apps/api/core";
import type * as Ipc from "@/platform/ipc";
import { render } from "@testing-library/react";
import { act, render } from "@testing-library/react";
import { indentUnit } from "@codemirror/language";
import { EditorView } from "@codemirror/view";
import type { IdeEvent, NotebookSnapshot } from "@/bindings";
import type { IdeEvent, NotebookSnapshot, Settings } from "@/bindings";
import { useProject } from "@/platform/project";
import { focusedCellEditor } from "@/editor/api";
import { getContext, useContextKeys } from "@/platform/context";
import { CellEditor } from "./CellEditor";
@@ -140,3 +142,28 @@ describe("cell editor theme", () => {
await session.close();
});
});
describe("cell editor indentation", () => {
it("follows the editor tab size and updates it in place", async () => {
const session = makeSession();
await session.load();
const before = useProject.getState().settings;
useProject.setState({ settings: { ...before, editor: { ...before?.editor, tabSize: 8 } } as Settings });
try {
const { container, unmount } = render(
<CellEditor session={session} id="cell-a" source="typed text" type="code" frozen={false} />,
);
const view = EditorView.findFromDOM(container.querySelector(".cm-editor")!)!;
expect(view.state.tabSize).toBe(8);
expect(view.state.facet(indentUnit)).toBe(" ".repeat(8));
act(() =>
useProject.setState({ settings: { ...before, editor: { ...before?.editor, tabSize: 2 } } as Settings }),
);
expect(EditorView.findFromDOM(container.querySelector(".cm-editor")!)).toBe(view);
expect(view.state.tabSize).toBe(2);
unmount();
} finally {
useProject.setState({ settings: before });
}
});
});
+15 -2
Переглянути файл
@@ -25,8 +25,10 @@ import { openideaHighlightStyle } from "@/editor/core/cm/highlight";
import { selectionMarks } from "@/editor/core/cm/selectionMarks";
import { seamlessSelection } from "@/editor/core/cm/selectionLayer";
import { multiCaretMouse } from "@/editor/core/cm/multiCaret";
import { findLanguageDescription, loadSupport } from "@/editor/core/cm/languages";
import { tooltipBounds } from "@/editor/core/cm/setup";
import { findLanguageDescription, languageInfo, loadSupport } from "@/editor/core/cm/languages";
import { effectiveIndent, indentExtension, tooltipBounds } from "@/editor/core/cm/setup";
import { useProject } from "@/platform/project";
import type { EditorSettings } from "@/platform/ipc";
import { tx } from "@/platform/i18n";
import { setContext } from "@/platform/context";
import type { CellReveal, NotebookSession } from "./session";
@@ -40,6 +42,11 @@ function languageServices(type: string, doc: NotebookCellDoc | undefined) {
return cellEditorExtensions({ doc: doc.doc, path: doc.uri, language: "python", uiMode: "Python", readOnly: false });
}
/** A cell's indentation: the Python (code) or Markdown Code Style, else the editor's tab size. */
function cellIndent(settings: EditorSettings | undefined, type: string) {
return indentExtension(effectiveIndent(settings, languageInfo(type === "code" ? "python" : "markdown")));
}
/** Created once: every `EditorView.theme` call mounts new CSS rules into the document. */
const CELL_EDITOR_THEME = EditorView.theme({
"&.cm-editor": { height: "auto" },
@@ -67,6 +74,8 @@ export function CellEditor({
}) {
const host = useRef<HTMLDivElement>(null);
const view = useRef<EditorView | null>(null);
const editorSettings = useProject((s) => s.settings?.editor);
const indent = useRef(new Compartment());
const readonly = useRef(new Compartment());
const services = useRef(new Compartment());
const initialSource = useRef(source);
@@ -88,6 +97,7 @@ export function CellEditor({
highlightSpecialChars(),
bracketMatching(),
indentOnInput(),
indent.current.of(cellIndent(useProject.getState().settings?.editor, type)),
Prec.highest(
keymap.of([
{
@@ -173,6 +183,9 @@ export function CellEditor({
editor.destroy();
};
}, [session, id, type]);
useLayoutEffect(() => {
view.current?.dispatch({ effects: indent.current.reconfigure(cellIndent(editorSettings, type)) });
}, [editorSettings, type]);
useLayoutEffect(() => {
const editor = view.current;
if (!editor) return;
+27
Переглянути файл
@@ -0,0 +1,27 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { useEditorRegistry } from "@/editor/api";
import { createMemoryPluginsBackend, setPluginsBackend } from "../backend";
import { trackActivationEvents } from "../bridge";
afterEach(() => {
setPluginsBackend(null);
useEditorRegistry.setState({ active: null });
});
describe("activation events", () => {
it("fires on-language when the open file's language is recognized later", () => {
const backend = createMemoryPluginsBackend();
const activationEvent = vi.spyOn(backend, "activationEvent");
setPluginsBackend(backend);
const ctx = (language: string) => ({ active: { ctx: { path: "/p/page.twig", language } } }) as never;
useEditorRegistry.setState(ctx("plaintext"));
const stop = trackActivationEvents();
// A remote server redetects the file once it has the plugin's language.
useEditorRegistry.setState(ctx("twig"));
stop();
expect(activationEvent.mock.calls.filter(([kind]) => kind === "language").map(([, arg]) => arg)).toEqual([
"plaintext",
"twig",
]);
});
});
+5 -2
Переглянути файл
@@ -130,7 +130,7 @@ function scheduleRefresh() {
* Fires `on-language:<id>` and `on-file:<project-relative path>` for files
* opened in the editor; the backend activates the plugins waiting for them.
*/
function trackActivationEvents(): () => void {
export function trackActivationEvents(): () => void {
const seenLanguages = new Set<string>();
const report = (ctx: { path: string | null; language: string } | undefined) => {
if (!ctx?.path) return;
@@ -148,8 +148,11 @@ function trackActivationEvents(): () => void {
}
};
report(useEditorRegistry.getState().active?.ctx);
// Also when the open file's language changes: a remote project learns plugin languages after the
// window restored its tabs, so a `.twig` file is plain text until the server redetects it.
return useEditorRegistry.subscribe((s, prev) => {
if (s.active?.ctx.path !== prev.active?.ctx.path) report(s.active?.ctx);
if (s.active?.ctx.path !== prev.active?.ctx.path || s.active?.ctx.language !== prev.active?.ctx.language)
report(s.active?.ctx);
});
}
+2 -2
Переглянути файл
@@ -100,9 +100,9 @@ export function ProjectHeaderActions() {
{!alwaysSelect && (
<IconButton
icon="locate"
action="navigate.selectInProjectView"
action="project.selectOpenedFile"
title="Select Opened File"
shortcut={shortcutLabel("navigate.selectInProjectView")}
shortcut={shortcutLabel("project.selectOpenedFile")}
size="small"
/>
)}
+10
Переглянути файл
@@ -254,6 +254,16 @@ export function registerProjectActions(): () => void {
keywords: ["locate", "reveal", "scroll from source", "select opened file"],
run: ({ arg }) => void selectInProjectView(typeof arg === "string" ? arg : null),
},
{
// IDEA's SelectOpenedFileInProjectView: the Project view toolbar's locate button.
id: "project.selectOpenedFile",
title: "Select Opened File",
category: "Project View",
icon: "locate",
when: OPEN,
keywords: ["locate", "reveal", "scroll from source", "select in project view"],
run: () => void selectInProjectView(null),
},
{
id: "project.reveal",
title: "Reveal in Project View",
Loaded 100 of 150 files, more files were not shown because too many files have changed in this diff. Show more